2 Commits
Author SHA1 Message Date
Chad Curtis 346cea5f89 hi 2025-07-14 21:58:29 +00:00
Chad Curtis 3d97870b59 init 2025-07-14 21:40:30 +00:00
222 changed files with 3536 additions and 9282 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
CONTEXT.md
-1
View File
@@ -1 +0,0 @@
../.mcp.json
+1
View File
@@ -0,0 +1 @@
../CONTEXT.md
-6
View File
@@ -11,7 +11,6 @@ node_modules
dist
dist-ssr
*.local
.ai/
# Editor directories and files
.idea
@@ -24,8 +23,3 @@ dist-ssr
# Vercel
.vercel
# Secrets
.env
.env.*
!.env.example
+7 -4
View File
@@ -5,13 +5,16 @@ default:
timeout: 1 minute
stages:
- test
- build
- deploy
test:
stage: test
build:
stage: build
script:
- npm run test
- npm run build
only:
variables:
- $CI_DEFAULT_BRANCH != $CI_COMMIT_REF_NAME
pages:
stage: deploy
+1
View File
@@ -0,0 +1 @@
CONTEXT.md
+16
View File
@@ -0,0 +1,16 @@
# jsr registry should not be edited or removed
.npmrc
# vite client types are needed
src/vite-env.d.ts
# tsconfig is stable and working correctly, so should not be edited
tsconfig.json
tsconfig.app.json
tsconfig.node.json
# postcss config for Tailwind is stable and working correctly, so should not be edited unless upgrading Tailwind to v4
postcss.config.js
# vite config is stable and usually should not need to be edited
vite.config.ts
+1 -6
View File
@@ -1,14 +1,9 @@
{
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@nostrbook/mcp@latest"]
"args": ["-y", "xjsr", "@nostrbook/mcp"]
}
}
}
+1 -6
View File
@@ -1,14 +1,9 @@
{
"servers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@nostrbook/mcp@latest"]
"args": ["-y", "xjsr", "@nostrbook/mcp"]
}
}
}
-1089
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1 +1 @@
AGENTS.md
CONTEXT.md
-1
View File
@@ -1 +0,0 @@
AGENTS.md
+849
View File
@@ -0,0 +1,849 @@
# Project Overview
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
## Technology Stack
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
- **Vite**: Fast build tool and development server
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
- **TanStack Query**: For data fetching, caching, and state management
- **TypeScript**: For type-safe JavaScript development
## Project Structure
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
- `useAuthor`: Fetch user profile data by pubkey
- `useCurrentUser`: Get currently logged-in user
- `useNostrPublish`: Publish events to Nostr
- `useUploadFile`: Upload files via Blossom servers
- `useAppContext`: Access global app configuration
- `useTheme`: Theme management
- `useToast`: Toast notifications
- `useLocalStorage`: Persistent local storage
- `useLoggedInAccounts`: Manage multiple accounts
- `useLoginActions`: Authentication actions
- `useIsMobile`: Responsive design helper
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext)
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
- `AppRouter.tsx`: React Router configuration
## UI Components
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
- **Accordion**: Vertically collapsing content panels
- **Alert**: Displays important messages to users
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
- **AspectRatio**: Maintains consistent width-to-height ratio
- **Avatar**: User profile pictures with fallback support
- **Badge**: Small status descriptors for UI elements
- **Breadcrumb**: Navigation aid showing current location in hierarchy
- **Button**: Customizable button with multiple variants and sizes
- **Calendar**: Date picker component
- **Card**: Container with header, content, and footer sections
- **Carousel**: Slideshow for cycling through elements
- **Chart**: Data visualization component
- **Checkbox**: Selectable input element
- **Collapsible**: Toggle for showing/hiding content
- **Command**: Command palette for keyboard-first interfaces
- **ContextMenu**: Right-click menu component
- **Dialog**: Modal window overlay
- **Drawer**: Side-sliding panel (using vaul)
- **DropdownMenu**: Menu that appears from a trigger element
- **Form**: Form validation and submission handling
- **HoverCard**: Card that appears when hovering over an element
- **InputOTP**: One-time password input field
- **Input**: Text input field
- **Label**: Accessible form labels
- **Menubar**: Horizontal menu with dropdowns
- **NavigationMenu**: Accessible navigation component
- **Pagination**: Controls for navigating between pages
- **Popover**: Floating content triggered by a button
- **Progress**: Progress indicator
- **RadioGroup**: Group of radio inputs
- **Resizable**: Resizable panels and interfaces
- **ScrollArea**: Scrollable container with custom scrollbars
- **Select**: Dropdown selection component
- **Separator**: Visual divider between content
- **Sheet**: Side-anchored dialog component
- **Sidebar**: Navigation sidebar component
- **Skeleton**: Loading placeholder
- **Slider**: Input for selecting a value from a range
- **Sonner**: Toast notification manager
- **Switch**: Toggle switch control
- **Table**: Data table with headers and rows
- **Tabs**: Tabbed interface component
- **Textarea**: Multi-line text input
- **Toast**: Toast notification component
- **ToggleGroup**: Group of toggle buttons
- **Toggle**: Two-state button
- **Tooltip**: Informational text that appears on hover
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
## System Prompt Management
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
1. Edit CONTEXT.md directly
2. The changes take effect in the next session
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
## Nostr Protocol Integration
This project comes with custom hooks for querying and publishing events on the Nostr network.
### Nostr Implementation Guidelines
- 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.
#### Choosing Between Existing NIPs and Custom Kinds
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. 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.
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
4. **Extension Strategy**: When existing NIPs are close but not perfect:
- Use the existing kind as the base
- Add domain-specific tags for additional metadata
- Document the extensions in `NIP.md`
5. **When to Generate Custom Kinds**:
- No existing NIP covers the core functionality
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
**Example Decision Process**:
```
Need: Equipment marketplace for farmers
Options:
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
3. Custom kind - Perfect fit but no interoperability
Decision: Use NIP-99 + farming-specific tags for best balance
```
#### Tag Design Principles
When designing tags for Nostr events, follow these principles:
1. **Kind vs Tags Separation**:
- **Kind** = Schema/structure (how the data is organized)
- **Tags** = Semantics/categories (what the data represents)
- Don't create different kinds for the same data structure
2. **Use Single-Letter Tags for Categories**:
- **Relays only index single-letter tags** for efficient querying
- Use `t` tags for categorization, not custom multi-letter tags
- Multiple `t` tags allow items to belong to multiple categories
3. **Relay-Level Filtering**:
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
- Avoid client-side filtering when relay-level filtering is possible
- Consider query patterns when designing tag structure
4. **Tag Examples**:
```json
// ❌ Wrong: Multi-letter tag, not queryable at relay level
["product_type", "electronics"]
// ✅ Correct: Single-letter tag, relay-indexed and queryable
["t", "electronics"]
["t", "smartphone"]
["t", "android"]
```
5. **Querying Best Practices**:
```typescript
// ❌ Inefficient: Get all events, filter in JavaScript
const events = await nostr.query([{ kinds: [30402] }]);
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
// ✅ Efficient: Filter at relay level
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
```
#### `t` Tag Filtering for Community-Specific Content
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
**When to Use:**
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
- ❌ Generic platforms: Twitter clones, general Nostr clients
**Implementation:**
```typescript
// Publishing with community tag
createEvent({
kind: 1,
content: data.content,
tags: [['t', 'farming']]
});
// Querying community content
const events = await nostr.query([{
kinds: [1],
'#t': ['farming'],
limit: 20
}], { signal });
```
### Kind Ranges
An event's kind number determines the event's behavior and storage characteristics:
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
### Content Field Design Principles
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
#### Guidelines
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
- **Empty content is valid**: Many events need only tags with `content: ""`
- **Relays only index tags**: If you need to filter by a field, it must be a tag
#### Example
**✅ Good - queryable data in tags:**
```json
{
"kind": 30402,
"content": "",
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
}
```
**❌ Bad - structured data in content:**
```json
{
"kind": 30402,
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
"tags": [["d", "product-123"]]
}
```
### NIP.md
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
### The `useNostr` Hook
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
```typescript
import { useNostr } from '@nostrify/react';
function useCustomHook() {
const { nostr } = useNostr();
// ...
}
```
### Query Nostr Data with `useNostr` and Tanstack Query
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
```typescript
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/query';
function usePosts() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['posts'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
return events; // these events could be transformed into another format
},
});
}
```
#### Efficient Query Design
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
**✅ Efficient - Single query with multiple kinds:**
```typescript
// Query multiple event types in one request
const events = await nostr.query([
{
kinds: [1, 6, 16], // All repost kinds in one query
'#e': [eventId],
limit: 150,
}
], { signal });
// Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1);
const reposts = events.filter((e) => e.kind === 6);
const genericReposts = events.filter((e) => e.kind === 16);
```
**❌ Inefficient - Multiple separate queries:**
```typescript
// This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
]);
```
**Query Optimization Guidelines:**
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
3. **Adjust limits**: When combining queries, increase the limit appropriately
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
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
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.
```typescript
// Example validator function for NIP-52 calendar events
function validateCalendarEvent(event: NostrEvent): boolean {
// Check if it's a calendar event kind
if (![31922, 31923].includes(event.kind)) return false;
// Check for required tags according to NIP-52
const d = event.tags.find(([name]) => name === 'd')?.[1];
const title = event.tags.find(([name]) => name === 'title')?.[1];
const start = event.tags.find(([name]) => name === 'start')?.[1];
// All calendar events require 'd', 'title', and 'start' tags
if (!d || !title || !start) return false;
// Additional validation for date-based events (kind 31922)
if (event.kind === 31922) {
// start tag should be in YYYY-MM-DD format for date-based events
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
if (!dateRegex.test(start)) return false;
}
// Additional validation for time-based events (kind 31923)
if (event.kind === 31923) {
// start tag should be a unix timestamp for time-based events
const timestamp = parseInt(start);
if (isNaN(timestamp) || timestamp <= 0) return false;
}
return true;
}
function useCalendarEvents() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['calendar-events'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
// Filter events through validator to ensure they meet NIP-52 requirements
return events.filter(validateCalendarEvent);
},
});
}
```
### The `useAuthor` Hook
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
```tsx
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
function Post({ event }: { event: NostrEvent }) {
const author = useAuthor(event.pubkey);
const metadata: NostrMetadata | undefined = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(event.pubkey);
const profileImage = metadata?.picture;
// ...render elements with this data
}
```
#### `NostrMetadata` type
```ts
/** Kind 0 metadata. */
interface NostrMetadata {
/** A short description of the user. */
about?: string;
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
banner?: string;
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
bot?: boolean;
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
display_name?: string;
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
lud06?: string;
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
lud16?: string;
/** A short name to be displayed for the user. */
name?: string;
/** An email-like Nostr address according to NIP-05. */
nip05?: string;
/** A URL to the user's avatar. */
picture?: string;
/** A web URL related in any way to the event author. */
website?: string;
}
```
### The `useNostrPublish` Hook
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
```tsx
import { useState } from 'react';
import { useCurrentUser } from "@/hooks/useCurrentUser";
import { useNostrPublish } from '@/hooks/useNostrPublish';
export function MyComponent() {
const [ data, setData] = useState<Record<string, string>>({});
const { user } = useCurrentUser();
const { mutate: createEvent } = useNostrPublish();
const handleSubmit = () => {
createEvent({ kind: 1, content: data.content });
};
if (!user) {
return <span>You must be logged in to use this form.</span>;
}
return (
<form onSubmit={handleSubmit} disabled={!user}>
{/* ...some input fields */}
</form>
);
}
```
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
### Nostr Login
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
```tsx
import { LoginArea } from "@/components/auth/LoginArea";
function MyComponent() {
return (
<div>
{/* other components ... */}
<LoginArea className="max-w-60" />
</div>
);
}
```
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs and switching between accounts. It should not be wrapped in any conditional logic.
`LoginArea` displays a "Log in" button when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
### `npub`, `naddr`, and other Nostr addresses
Nostr defines a set identifiers in NIP-19. Their prefixes:
- `npub`: public keys
- `nsec`: private keys
- `note`: note ids
- `nprofile`: a nostr profile
- `nevent`: a nostr event
- `naddr`: a nostr replaceable event coordinate
- `nrelay`: a nostr relay (deprecated)
NIP-19 identifiers include a prefix, the number "1", then a base32-encoded data string.
#### Use in Filters
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
```ts
// ❌ Wrong: naddr is not decoded
const events = await nostr.query(
[{ ids: [naddr] }],
{ signal }
);
```
Corrected example:
```ts
// Import nip19 from nostr-tools
import { nip19 } from 'nostr-tools';
// Decode a NIP-19 identifier
const decoded = nip19.decode(value);
// Optional: guard certain types (depending on the use-case)
if (decoded.type !== 'naddr') {
throw new Error('Unsupported Nostr identifier');
}
// Get the addr object
const naddr = decoded.data;
// ✅ Correct: naddr is expanded into the correct filter
const events = await nostr.query(
[{
kinds: [naddr.kind],
authors: [naddr.pubkey],
'#d': [naddr.identifier],
}],
{ signal }
);
```
#### Use in URL Paths
For URL routing, use NIP-19 identifiers as path parameters (e.g., `/:nip19`) to create secure, universal links to Nostr events. Decode the identifier and render the appropriate component based on the type:
- Regular events: Use `/nevent1...` paths
- Replaceable/addressable events: Use `/naddr1...` paths
Always use `naddr` identifiers for addressable events instead of just the `d` tag value, as `naddr` contains the author pubkey needed to create secure filters. This prevents security issues where malicious actors could publish events with the same `d` tag to override content.
```ts
// Secure routing with naddr
const decoded = nip19.decode(params.nip19);
if (decoded.type === 'naddr' && decoded.data.kind === 30024) {
// Render ArticlePage component
}
```
### Nostr Edit Profile
To include an Edit Profile form, place the `EditProfileForm` component in the project:
```tsx
import { EditProfileForm } from "@/components/EditProfileForm";
function EditProfilePage() {
return (
<div>
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
<EditProfileForm />
</div>
);
}
```
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
### 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.
```tsx
import { useUploadFile } from "@/hooks/useUploadFile";
function MyComponent() {
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const handleUpload = async (file: File) => {
try {
// Provides an array of NIP-94 compatible tags
// The first tag in the array contains the URL
const [[_, url]] = await uploadFile(file);
// ...use the url
} catch (error) {
// ...handle errors
}
};
// ...rest of component
}
```
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
### Nostr Encryption and Decryption
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
```ts
// Get the current user
const { user } = useCurrentUser();
// Optional guard to check that nip44 is available
if (!user.signer.nip44) {
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
}
// Encrypt message to self
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
// Decrypt message to self
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
```
### Rendering Rich Text Content
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
```tsx
import { NoteContent } from "@/components/NoteContent";
export function Post(/* ...props */) {
// ...
return (
<CardContent className="pb-2">
<div className="whitespace-pre-wrap break-words">
<NoteContent event={post} className="text-sm" />
</div>
</CardContent>
);
}
```
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
```typescript
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.nostr.band",
};
```
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
## Routing
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
1. Create your page component in `/src/pages/`
2. Import it in `AppRouter.tsx`
3. Add the route above the catch-all `*` route:
```tsx
<Route path="/your-path" element={<YourComponent />} />
```
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
## Development Practices
- Uses React Query for data fetching and caching
- Follows shadcn/ui component patterns
- Implements Path Aliases with `@/` prefix for cleaner imports
- Uses Vite for fast development and production builds
- Component-based architecture with React hooks
- Default connection to one Nostr relay for best performance
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
- **Never use the `any` type**: Always use proper TypeScript types for type safety
## Loading States
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
```tsx
// Skeleton example matching component structure
<Card>
<CardHeader>
<div className="flex items-center space-x-3">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
</CardContent>
</Card>
```
### Empty States and No Content Found
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
```tsx
import { RelaySelector } from '@/components/RelaySelector';
import { Card, CardContent } from '@/components/ui/card';
// Empty state example
<div className="col-span-full">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
No results found. Try another relay?
</p>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
</div>
```
## Design Customization
**Tailor the site's look and feel based on the user's specific request.** This includes:
- **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 the `js-dev__npm_add_package` tool:
**Any Google Font can be installed** using the @fontsource packages. Examples:
- 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)
2. **Import the font** in `src/main.tsx`:
```typescript
import '@fontsource-variable/<font-name>';
```
3. **Update Tailwind configuration** in `tailwind.config.ts`:
```typescript
export default {
theme: {
extend: {
fontFamily: {
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
},
},
},
}
```
### Recommended Font Choices by Use Case
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
### Theme System
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
- `useTheme` hook for programmatic theme switching
- CSS custom properties defined in `src/index.css`
- Automatic dark mode support with `.dark` class
### Color Scheme Implementation
When users specify color schemes:
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
- Use Tailwind's color palette or define custom colors
- Ensure proper contrast ratios for accessibility
- Apply colors consistently across components (buttons, links, accents)
- Test both light and dark mode variants
### Component Styling Patterns
- Use `cn()` utility for conditional class merging
- Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
## Writing Tests
**Important for AI Assistants**: Only create tests when the user is experiencing a specific problem or explicitly requests tests. Do not proactively write tests for new features or components unless the user is having issues that require testing to diagnose or resolve.
### Test Setup
The project uses Vitest with jsdom environment and includes comprehensive test setup:
- **Testing Library**: React Testing Library with jest-dom matchers
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
- **Test App**: `TestApp` component provides all necessary context providers for testing
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
```tsx
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { MyComponent } from './MyComponent';
describe('MyComponent', () => {
it('renders correctly', () => {
render(
<TestApp>
<MyComponent />
</TestApp>
);
expect(screen.getByText('Expected text')).toBeInTheDocument();
});
});
```
## Testing Your Changes
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 this test passes without errors.**
-1
View File
@@ -1 +0,0 @@
AGENTS.md
+116
View File
@@ -0,0 +1,116 @@
# NIP-GNOME: Gnome Speak Translation Protocol
`draft` `optional`
## Abstract
This NIP defines a client-side translation protocol for converting kind 1 (Short Text Note) events into "Gnome Speak" - a whimsical fantasy language that transforms regular text into gnome-themed vocabulary and expressions.
## Motivation
To create an immersive and entertaining experience for users of gnome-themed Nostr clients, where all text content is automatically translated into a consistent fantasy language that maintains readability while adding magical woodland charm.
## Specification
### Translation Scope
- **MUST** translate all kind 1 events (Short Text Notes) into Gnome Speak
- **SHOULD NOT** translate other event kinds to maintain protocol compatibility
- **MUST** preserve original URLs, Nostr references (npub, note, etc.), and hashtags without translation
- **SHOULD** maintain the semantic meaning of the original text
### Translation Rules
#### Vocabulary Substitution
Common words are replaced with gnome-themed equivalents:
- Greetings: `hello` → `greetings, fellow earth-dweller`
- Technology: `computer` → `thinking-box of metal and magic`
- Time: `today` → `this blessed sun-cycle`
- Actions: `go` → `venture forth`
- People: `friend` → `companion of the woodland path`
#### Gnome Expressions
- Exclamations are enhanced with gnome phrases: `!` → `! By my pointy hat!`
- Sentence starters may be added: `In the sacred grove, ...`
- Sentence endings may be appended: `...as the ancients foretold.`
#### Special Formatting
- Bitcoin/crypto terms: `bitcoin` → `✨golden acorns of the digital realm✨`
- Nostr terms: `nostr` → `🍄message-mushroom🍄`
- Greetings: `gm` → `🌅when dew kisses the earth🌅`
### Implementation
#### Client Behavior
Clients implementing this NIP:
1. **MUST** detect kind 1 events
2. **MUST** apply Gnome Speak translation before displaying content
3. **SHOULD** preserve original content for editing/replying
4. **MAY** provide toggle to view original content
5. **SHOULD** indicate when content has been translated
#### Content Preservation
- Original event content **MUST** remain unchanged in storage/transmission
- Translation occurs only at display time
- Replies and quotes **SHOULD** reference original content, not translated
#### Tag Usage
Clients **MAY** add a `t` tag with value `gnome` to indicate gnome-themed content:
```json
{
"kind": 1,
"content": "Hello world!",
"tags": [["t", "gnome"]],
...
}
```
### Example
Original event:
```json
{
"kind": 1,
"content": "Good morning! Having coffee and checking bitcoin prices.",
"tags": [],
...
}
```
Displayed as:
```
"When dew kisses the earth! Partaking of bitter bean brew and witnessing ✨golden acorns of the digital realm✨ values, blessed by the forest spirits."
```
## Rationale
This approach provides:
1. **Immersive Experience**: Creates a consistent fantasy atmosphere
2. **Protocol Compatibility**: No changes to underlying Nostr protocol
3. **Reversibility**: Original content always preserved
4. **Interoperability**: Non-gnome clients display original content normally
## Security Considerations
- Translation is purely cosmetic and doesn't affect event integrity
- Original content validation remains unchanged
- No additional attack vectors introduced
## Implementation Status
This NIP is implemented in Gnome Nostr client as a client-side translation layer.
## References
- [NIP-01: Basic protocol flow description](https://github.com/nostr-protocol/nips/blob/master/01.md)
- [NIP-10: Text Notes and Threads](https://github.com/nostr-protocol/nips/blob/master/10.md)
+78 -2
View File
@@ -1,3 +1,79 @@
# MKStack
# 🍄 Gnome Nostr - The Sacred Network of Woodland Folk
Template for building Nostr client application with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
A magical Nostr client where all text notes (kind 1 events) are automatically translated into the ancient gnome tongue! Connect with fellow earth-dwellers across the message-mushroom network.
## ✨ Features
- **🍄 Gnome Speak Translation**: All kind 1 events are automatically translated into whimsical gnome language
- **🌲 Forest-Themed UI**: Beautiful gnome-inspired design with earthy colors and woodland aesthetics
- **🔗 Full Nostr Compatibility**: Works with any Nostr relay and preserves all protocol functionality
- **📱 Responsive Design**: Works perfectly on desktop and mobile devices
- **🌙 Dark/Light Mode**: Toggle between day forest and night forest themes
- **⚡ Lightning Fast**: Built with modern React, Vite, and TailwindCSS
## 🎭 Gnome Speak Examples
Regular text is magically transformed:
- `"Hello world!"` → `"Greetings, fellow earth-dweller world! By my pointy hat!"`
- `"Good morning everyone"` → `"🌅When dew kisses the earth🌅 all forest folk"`
- `"I love bitcoin"` → `"I cherish like precious gems ✨golden acorns of the digital realm✨"`
- `"This is about #nostr"` → `"This is a woodland proclamation about #nostr"` (hashtags preserved)
## 🛡️ Protocol Preservation
While the display is transformed into gnome speak, the underlying Nostr protocol remains unchanged:
- ✅ URLs are preserved and linkified
- ✅ Nostr references (npub, note, etc.) work normally
- ✅ Hashtags remain functional for filtering
- ✅ Original content is preserved for replies and quotes
- ✅ Compatible with all other Nostr clients
## 🏗️ Technical Details
- **Framework**: React 18 with TypeScript
- **Styling**: TailwindCSS with custom gnome theme
- **Nostr**: Nostrify for protocol integration
- **Font**: Comfortaa Variable for whimsical feel
- **Build**: Vite for fast development and production builds
## 🌟 Custom NIP
This client implements a custom translation protocol documented in `NIP.md`. The translation:
- Only affects kind 1 events (Short Text Notes)
- Preserves URLs, Nostr references, and hashtags
- Maintains semantic meaning while adding magical charm
- Is purely client-side - no protocol changes required
## 🚀 Getting Started
1. **Clone the repository**
2. **Install dependencies**: `npm install`
3. **Start development**: `npm run dev`
4. **Build for production**: `npm run build`
## 🎨 Customization
The gnome vocabulary can be extended in `src/lib/gnomeSpeak.ts`. Add new word mappings to enhance the magical transformation!
## 🤝 Contributing
Contributions are welcome! Whether you want to:
- Add more gnome vocabulary
- Improve the forest-themed UI
- Fix bugs or add features
- Enhance the translation algorithm
Feel free to open issues and pull requests.
## 📜 License
This project is open source and available under the MIT License.
---
*Vibed with [MKStack](https://soapbox.pub/mkstack) • Blessed by the forest spirits 🍄✨*
**May your mushrooms grow tall and your acorns be golden!** 🌰✨
+16
View File
@@ -0,0 +1,16 @@
{
"model": "claude-sonnet-4",
"temperature": 0.2,
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
Symlink
+1
View File
@@ -0,0 +1 @@
CONTEXT.md
+1
View File
@@ -0,0 +1 @@
hi
+6 -1
View File
@@ -4,10 +4,15 @@
<meta charset="UTF-8" />
<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>Gnome Nostr - The Sacred Network of Woodland Folk</title>
<meta name="description" content="A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!">
<meta property="og:type" content="website">
<meta property="og:title" content="Gnome Nostr - The Sacred Network of Woodland Folk">
<meta property="og:description" content="A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!">
<link rel="manifest" href="/manifest.webmanifest">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
</html>
+315 -465
View File
File diff suppressed because it is too large. Load diff
+5 -9
View File
@@ -7,15 +7,13 @@
"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": {
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^6.0.0",
"@fontsource-variable/comfortaa": "^5.2.6",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.1",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.5",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -53,20 +51,19 @@
"embla-carousel-react": "^8.3.0",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"next-themes": "^0.3.0",
"nostr-tools": "^2.13.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.0",
"react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2",
"recharts": "^2.12.7",
"sonner": "^1.5.0",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3",
"webln": "^0.3.2",
"zod": "^3.25.71"
},
"devDependencies": {
@@ -77,7 +74,6 @@
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@types/node": "^22.5.5",
"@types/qrcode": "^1.5.5",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react-swc": "^3.5.0",
+21
View File
@@ -0,0 +1,21 @@
{
"name": "Gnome Nostr - The Sacred Network of Woodland Folk",
"short_name": "Gnome Nostr",
"description": "A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!",
"start_url": "/",
"display": "standalone",
"background_color": "#f0f5f0",
"theme_color": "#d97706",
"icons": [
{
"src": "/icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icon-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
+32
View File
@@ -0,0 +1,32 @@
version: 1.0.0
title: Nostr Client Development
description: A recipe for building Nostr client applications
instructions: Create a Nostr client application according to the user's request.
extensions:
- type: builtin
name: developer
display_name: Developer Tools
timeout: 300
bundled: true
- type: stdio
name: nostr
cmd: npx
args:
- -y
- xjsr
- "@nostrbook/mcp"
envs: {}
timeout: 20
description: null
bundled: null
- type: stdio
name: fetch
cmd: uvx
args:
- mcp-server-fetch
envs: {}
timeout: 20
description: null
bundled: null
author:
contact: Alex Gleason <[email protected]>
-42
View File
@@ -1,42 +0,0 @@
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
@@ -1,7 +0,0 @@
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.js";
import App from './App';
test('App', () => {
render(<App />);
+14 -15
View File
@@ -5,14 +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.js';
import { Toaster } from "@/components/ui/toaster.js";
import { TooltipProvider } from "@/components/ui/tooltip.js";
import NostrProvider from '@/components/NostrProvider';
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider.js';
import { NWCProvider } from '@/contexts/NWCContext.js';
import { AppConfig } from '@/contexts/AppContext.js';
import AppRouter from "./AppRouter.js";
import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import AppRouter from './AppRouter';
const head = createHead({
plugins: [
@@ -49,14 +49,13 @@ export function App() {
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NWCProvider>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</NWCProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
-10
View File
@@ -1,10 +0,0 @@
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;
+3 -6
View File
@@ -1,9 +1,8 @@
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop.js";
import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index.js";
import { NIP19Page } from "./pages/NIP19Page.js";
import NotFound from "./pages/NotFound.js";
import Index from "./pages/Index";
import NotFound from "./pages/NotFound";
export function AppRouter() {
return (
@@ -11,8 +10,6 @@ export function AppRouter() {
<ScrollToTop />
<Routes>
<Route path="/" element={<Index />} />
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
<Route path="/:nip19" element={<NIP19Page />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} />
</Routes>
-65
View File
@@ -1,65 +0,0 @@
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]);
}
+5 -5
View File
@@ -1,7 +1,7 @@
import { ReactNode, useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage.js';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext.js';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
interface AppProviderProps {
children: ReactNode;
@@ -14,7 +14,7 @@ interface AppProviderProps {
}
// Zod schema for AppConfig validation
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
const AppConfigSchema: z.ZodType<AppConfig> = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
});
@@ -88,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
@@ -1,120 +0,0 @@
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.js';
import { useNostrPublish } from '@/hooks/useNostrPublish.js';
import { useToast } from '@/hooks/useToast.js';
import { Button } from '@/components/ui/button.js';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
import { Button } from '@/components/ui/button';
import {
Form,
FormControl,
@@ -13,14 +13,14 @@ import {
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';
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Loader2, Upload } from 'lucide-react';
import { NSchema as n, type NostrMetadata } from '@nostrify/nostrify';
import { useQueryClient } from '@tanstack/react-query';
import { useUploadFile } from '@/hooks/useUploadFile.js';
import { useUploadFile } from '@/hooks/useUploadFile';
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
@@ -1,41 +0,0 @@
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;
}
}
-113
View File
@@ -1,113 +0,0 @@
import { Component, ErrorInfo, ReactNode } from 'react';
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
errorInfo: ErrorInfo | null;
}
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode;
}
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null,
};
}
static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
return {
hasError: true,
error,
};
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('Error caught by ErrorBoundary:', error, errorInfo);
this.setState({
error,
errorInfo,
});
}
handleReset = () => {
this.setState({
hasError: false,
error: null,
errorInfo: null,
});
};
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<div className="max-w-md w-full space-y-4">
<div className="text-center">
<h2 className="text-2xl font-bold text-foreground mb-2">
Something went wrong
</h2>
<p className="text-muted-foreground">
An unexpected error occurred. The error has been reported.
</p>
</div>
<div className="bg-muted p-4 rounded-lg">
<details className="text-sm">
<summary className="cursor-pointer font-medium text-foreground">
Error details
</summary>
<div className="mt-2 space-y-2">
<div>
<strong className="text-foreground">Message:</strong>
<p className="text-muted-foreground mt-1">
{this.state.error?.message}
</p>
</div>
{this.state.error?.stack && (
<div>
<strong className="text-foreground">Stack trace:</strong>
<pre className="text-xs text-muted-foreground mt-1 overflow-auto max-h-32">
{this.state.error.stack}
</pre>
</div>
)}
</div>
</details>
</div>
<div className="flex gap-2">
<button
onClick={this.handleReset}
className="flex-1 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors"
>
Try again
</button>
<button
onClick={() => window.location.reload()}
className="flex-1 px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90 transition-colors"
>
Reload page
</button>
</div>
</div>
</div>
);
}
return this.props.children;
}
}
+193
View File
@@ -0,0 +1,193 @@
import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Send, Sparkles, Leaf } from 'lucide-react';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { translateToGnomeSpeak } from '@/lib/gnomeSpeak';
import { useToast } from '@/hooks/useToast';
export function GnomeComposer() {
const [content, setContent] = useState('');
const [isPreviewMode, setIsPreviewMode] = useState(false);
const { user } = useCurrentUser();
const { mutate: createEvent, isPending } = useNostrPublish();
const { toast } = useToast();
const author = useAuthor(user?.pubkey || '');
const metadata = author.data?.metadata;
const displayName = metadata?.name ?? (user?.pubkey ? genUserName(user.pubkey) : 'Anonymous Gnome');
const profileImage = metadata?.picture;
const handleSubmit = () => {
if (!content.trim()) {
toast({
title: "Empty woodland proclamation!",
description: "Even gnomes need something to say to the forest folk.",
variant: "destructive",
});
return;
}
if (!user) {
toast({
title: "Authentication required",
description: "You must be logged in to share woodland wisdom.",
variant: "destructive",
});
return;
}
createEvent(
{
kind: 1,
content: content.trim(),
tags: [['t', 'gnome']] // Tag all posts as gnome content
},
{
onSuccess: () => {
setContent('');
setIsPreviewMode(false);
toast({
title: "Woodland proclamation sent! 🍄",
description: "Your message has been carried by the forest winds to all the message-mushrooms.",
});
},
onError: (error) => {
toast({
title: "Forest spirits are troubled",
description: `Failed to send your proclamation: ${error.message}`,
variant: "destructive",
});
}
}
);
};
const gnomeTranslatedContent = content ? translateToGnomeSpeak(content) : '';
if (!user) {
return (
<Card className="mb-6 border-2 border-dashed border-muted">
<CardContent className="py-8 text-center">
<div className="space-y-4">
<div className="text-4xl">🍄</div>
<div>
<h3 className="font-semibold mb-2">Join the Forest Council</h3>
<p className="text-muted-foreground">
Log in to share your woodland wisdom with fellow gnomes across the message-mushroom network!
</p>
</div>
</div>
</CardContent>
</Card>
);
}
return (
<Card className="mb-6 border-2 border-primary/20 shadow-lg">
<CardHeader className="pb-3">
<div className="flex items-center space-x-3">
<Avatar className="h-10 w-10 border-2 border-primary/30">
<AvatarImage src={profileImage} alt={displayName} />
<AvatarFallback className="bg-primary text-primary-foreground font-bold">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1">
<div className="flex items-center space-x-2">
<CardTitle className="text-lg">Share Woodland Wisdom</CardTitle>
<Badge variant="secondary" className="gnome-wiggle">
🍄 Gnome Speak
</Badge>
</div>
<p className="text-sm text-muted-foreground">
Your words will be translated into the ancient gnome tongue
</p>
</div>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<div className="flex items-center justify-between">
<label className="text-sm font-medium">Your Message:</label>
<Button
variant="ghost"
size="sm"
onClick={() => setIsPreviewMode(!isPreviewMode)}
className="text-xs"
>
<Sparkles className="h-3 w-3 mr-1" />
{isPreviewMode ? 'Edit' : 'Preview Gnome Speak'}
</Button>
</div>
{!isPreviewMode ? (
<Textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Share your thoughts with the forest folk... (will be translated to gnome speak)"
className="min-h-[100px] resize-none border-2 border-border/50 focus:border-primary/50"
maxLength={280}
/>
) : (
<div className="min-h-[100px] p-3 border-2 border-accent/30 rounded-md bg-accent/5">
<p className="text-sm text-muted-foreground mb-2 font-medium">
🍄 Gnome Speak Translation:
</p>
<div className="text-sm leading-relaxed">
{gnomeTranslatedContent || (
<span className="text-muted-foreground italic">
Your gnome translation will appear here...
</span>
)}
</div>
</div>
)}
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>
{content.length}/280 characters
</span>
{content && (
<span className="text-accent">
✨ Will be auto-translated to gnome speak
</span>
)}
</div>
</div>
<div className="flex items-center justify-between pt-2">
<div className="flex items-center space-x-2 text-xs text-muted-foreground">
<Leaf className="h-3 w-3" />
<span>Broadcasting to message-mushroom network</span>
</div>
<Button
onClick={handleSubmit}
disabled={!content.trim() || isPending}
className="font-medium"
>
{isPending ? (
<>
<Sparkles className="h-4 w-4 mr-2 animate-spin" />
Sending to Forest...
</>
) : (
<>
<Send className="h-4 w-4 mr-2" />
Share Wisdom
</>
)}
</Button>
</div>
</CardContent>
</Card>
);
}
+221
View File
@@ -0,0 +1,221 @@
import { useQuery } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { Heart, MessageCircle, Repeat2 } from 'lucide-react';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { NoteContent } from '@/components/NoteContent';
import { RelaySelector } from '@/components/RelaySelector';
import type { NostrEvent } from '@nostrify/nostrify';
function GnomePost({ event }: { event: NostrEvent }) {
const author = useAuthor(event.pubkey);
const metadata = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(event.pubkey);
const profileImage = metadata?.picture;
const about = metadata?.about;
// Format timestamp
const timestamp = new Date(event.created_at * 1000);
const timeAgo = formatTimeAgo(timestamp);
return (
<Card className="mb-4 border-2 border-border/50 hover:border-primary/30 transition-all duration-300 hover:shadow-lg mushroom-glow">
<CardHeader className="pb-3">
<div className="flex items-start space-x-3">
<Avatar className="h-12 w-12 border-2 border-primary/20">
<AvatarImage src={profileImage} alt={displayName} />
<AvatarFallback className="bg-secondary text-secondary-foreground font-bold">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<div className="flex items-center space-x-2">
<h3 className="font-semibold text-foreground truncate">
{displayName}
</h3>
<Badge variant="secondary" className="text-xs gnome-wiggle">
🍄 Gnome
</Badge>
</div>
{about && (
<p className="text-sm text-muted-foreground truncate mt-1">
{about}
</p>
)}
<p className="text-xs text-muted-foreground mt-1">
{timeAgo} • via message-mushroom 🍄
</p>
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="mb-4">
<NoteContent event={event} className="text-sm leading-relaxed" />
</div>
{/* Gnome-themed interaction buttons */}
<div className="flex items-center space-x-6 pt-2 border-t border-border/30">
<Button variant="ghost" size="sm" className="text-muted-foreground hover:text-primary group">
<Heart className="h-4 w-4 mr-1 group-hover:fill-current transition-all" />
<span className="text-xs">Sprinkle Fairy Dust</span>
</Button>
<Button variant="ghost" size="sm" className="text-muted-foreground hover:text-accent group">
<MessageCircle className="h-4 w-4 mr-1" />
<span className="text-xs">Forest Whisper</span>
</Button>
<Button variant="ghost" size="sm" className="text-muted-foreground hover:text-secondary group">
<Repeat2 className="h-4 w-4 mr-1" />
<span className="text-xs">Spread Seeds</span>
</Button>
</div>
</CardContent>
</Card>
);
}
function GnomePostSkeleton() {
return (
<Card className="mb-4">
<CardHeader className="pb-3">
<div className="flex items-start space-x-3">
<Skeleton className="h-12 w-12 rounded-full" />
<div className="flex-1 space-y-2">
<div className="flex items-center space-x-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-5 w-16" />
</div>
<Skeleton className="h-3 w-32" />
<Skeleton className="h-3 w-20" />
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="space-y-2 mb-4">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
<Skeleton className="h-4 w-3/5" />
</div>
<div className="flex items-center space-x-6 pt-2 border-t border-border/30">
<Skeleton className="h-8 w-20" />
<Skeleton className="h-8 w-20" />
<Skeleton className="h-8 w-20" />
<Skeleton className="h-8 w-20" />
</div>
</CardContent>
</Card>
);
}
function formatTimeAgo(date: Date): string {
const now = new Date();
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
if (diffInSeconds < 60) {
return 'just now';
} else if (diffInSeconds < 3600) {
const minutes = Math.floor(diffInSeconds / 60);
return `${minutes}m ago`;
} else if (diffInSeconds < 86400) {
const hours = Math.floor(diffInSeconds / 3600);
return `${hours}h ago`;
} else {
const days = Math.floor(diffInSeconds / 86400);
return `${days}d ago`;
}
}
export function GnomeFeed() {
const { nostr } = useNostr();
const { data: posts, isLoading, error } = useQuery({
queryKey: ['gnome-feed'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
// Query for kind 1 events (text notes) that will be translated to gnome speak
const events = await nostr.query([
{
kinds: [1],
limit: 50,
}
], { signal });
// Sort by creation time (newest first)
return events.sort((a, b) => b.created_at - a.created_at);
},
refetchInterval: 30000, // Refetch every 30 seconds
});
if (error) {
return (
<div className="col-span-full">
<Card className="border-dashed border-destructive/50">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<div className="text-4xl">🍄💔</div>
<div>
<h3 className="font-semibold text-destructive mb-2">
The forest spirits are troubled!
</h3>
<p className="text-muted-foreground mb-4">
Unable to connect to the message-mushroom network. The woodland whispers have gone silent.
</p>
<RelaySelector className="w-full" />
</div>
</div>
</CardContent>
</Card>
</div>
);
}
if (isLoading) {
return (
<div className="space-y-4">
{Array.from({ length: 5 }).map((_, i) => (
<GnomePostSkeleton key={i} />
))}
</div>
);
}
if (!posts || posts.length === 0) {
return (
<div className="col-span-full">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<div className="text-6xl gnome-wiggle">🍄</div>
<div>
<h3 className="font-semibold mb-2">
The forest is quiet today...
</h3>
<p className="text-muted-foreground mb-4">
No woodland proclamations found. Perhaps the gnomes are all busy tending their gardens? Try another message-mushroom relay to discover more forest folk!
</p>
<RelaySelector className="w-full" />
</div>
</div>
</CardContent>
</Card>
</div>
);
}
return (
<div className="space-y-4">
{posts.map((post) => (
<GnomePost key={post.id} event={post} />
))}
</div>
);
}
+88
View File
@@ -0,0 +1,88 @@
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { LoginArea } from '@/components/auth/LoginArea';
import { RelaySelector } from '@/components/RelaySelector';
import { useTheme } from '@/hooks/useTheme';
import { Moon, Sun, Leaf, TreePine, Sparkles } from 'lucide-react';
export function GnomeHeader() {
const { theme, setTheme } = useTheme();
return (
<Card className="mb-6 border-2 border-primary/30 bg-gradient-to-r from-primary/5 via-accent/5 to-secondary/5">
<CardContent className="py-6">
<div className="flex flex-col space-y-4">
{/* Main header */}
<div className="flex items-center justify-between">
<div className="flex items-center space-x-4">
<div className="text-3xl gnome-wiggle">🍄</div>
<div>
<h1 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Gnome Nostr
</h1>
<p className="text-sm text-muted-foreground">
The sacred network of woodland folk
</p>
</div>
</div>
<div className="flex items-center space-x-3">
<Badge variant="secondary" className="hidden md:flex items-center space-x-1">
<Sparkles className="h-3 w-3" />
<span>Gnome Speak</span>
</Badge>
<Button
variant="ghost"
size="sm"
onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
className="text-muted-foreground hover:text-foreground"
>
{theme === 'light' ? (
<Moon className="h-4 w-4" />
) : (
<Sun className="h-4 w-4" />
)}
<span className="hidden sm:inline ml-1">
{theme === 'light' ? 'Night Forest' : 'Day Forest'}
</span>
</Button>
<LoginArea className="max-w-48" />
</div>
</div>
{/* Info and controls bar */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between space-y-3 sm:space-y-0 pt-3 border-t border-border/30">
<div className="flex items-center space-x-4 text-xs text-muted-foreground">
<div className="flex items-center space-x-1">
<TreePine className="h-3 w-3" />
<span className="hidden sm:inline">Text notes translated to gnome speak</span>
<span className="sm:hidden">Gnome translation active</span>
</div>
</div>
<div className="flex items-center space-x-2">
<Leaf className="h-3 w-3 text-muted-foreground" />
<span className="text-xs text-muted-foreground">Relay:</span>
<RelaySelector className="max-w-48" />
</div>
</div>
{/* Welcome message */}
<div className="bg-accent/10 border border-accent/20 rounded-lg p-4 text-center">
<p className="text-sm text-accent-foreground">
<span className="font-medium">🌟 Welcome to the enchanted forest!</span>
<br />
<span className="text-xs text-muted-foreground mt-1 block">
All text notes are magically translated into the ancient gnome tongue.
Share your woodland wisdom with fellow earth-dwellers!
</span>
</p>
</div>
</div>
</CardContent>
</Card>
);
}
-45
View File
@@ -1,45 +0,0 @@
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;
+1 -1
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.js';
import { useAppContext } from '@/hooks/useAppContext';
interface NostrProviderProps {
children: React.ReactNode;
-77
View File
@@ -1,77 +0,0 @@
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
@@ -1,98 +0,0 @@
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");
});
});
+9 -7
View File
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp.js';
import { NoteContent } from "./NoteContent.js";
import { TestApp } from '@/test/TestApp';
import { NoteContent } from './NoteContent';
import type { NostrEvent } from '@nostrify/nostrify';
describe('NoteContent', () => {
@@ -22,9 +22,10 @@ describe('NoteContent', () => {
</TestApp>
);
const link = screen.getByRole('link', { name: 'https://example.com' });
// The URL should still be linkified even after gnome translation
const link = screen.getByRole('link', { name: /https:\/\/example/ });
expect(link).toBeInTheDocument();
expect(link).toHaveAttribute('href', 'https://example.com');
expect(link.getAttribute('href')).toMatch(/https:\/\/example/);
expect(link).toHaveAttribute('target', '_blank');
});
@@ -93,9 +94,10 @@ describe('NoteContent', () => {
</TestApp>
);
// Hashtags are preserved during gnome translation
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 +125,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
+9 -4
View File
@@ -2,9 +2,10 @@ 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.js';
import { genUserName } from '@/lib/genUserName.js';
import { cn } from '@/lib/utils.js';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { cn } from '@/lib/utils';
import { translateToGnomeSpeak, shouldTranslateToGnomeSpeak } from '@/lib/gnomeSpeak';
interface NoteContentProps {
event: NostrEvent;
@@ -18,7 +19,11 @@ export function NoteContent({
}: NoteContentProps) {
// Process the content to render mentions, links, etc.
const content = useMemo(() => {
const text = event.content;
// Translate to gnome speak if it's a kind 1 event
const originalText = event.content;
const text = shouldTranslateToGnomeSpeak(event.kind)
? translateToGnomeSpeak(originalText)
: originalText;
// Regex to find URLs, Nostr references, and hashtags
const regex = /(https?:\/\/[^\s]+)|nostr:(npub1|note1|nprofile1|nevent1)([023456789acdefghjklmnpqrstuvwxyz]+)|(#\w+)/g;
-65
View File
@@ -1,65 +0,0 @@
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.js";
import { Button } from "@/components/ui/button.js";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
@@ -8,14 +8,14 @@ import {
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command.js";
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover.js";
} from "@/components/ui/popover";
import { useState } from "react";
import { useAppContext } from "@/hooks/useAppContext.js";
import { useAppContext } from "@/hooks/useAppContext";
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
@@ -1,9 +0,0 @@
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
export function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
-87
View File
@@ -1,87 +0,0 @@
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] }));
}
-395
View File
@@ -1,395 +0,0 @@
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';
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC.js';
interface WalletModalProps {
children?: React.ReactNode;
className?: string;
}
// Extracted AddWalletContent to prevent re-renders
const AddWalletContent = forwardRef<HTMLDivElement, {
alias: string;
setAlias: (value: string) => void;
connectionUri: string;
setConnectionUri: (value: string) => void;
}>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (
<div className="space-y-4 px-4" ref={ref}>
<div>
<Label htmlFor="alias">Wallet Name (optional)</Label>
<Input
id="alias"
placeholder="My Lightning Wallet"
value={alias}
onChange={(e) => setAlias(e.target.value)}
/>
</div>
<div>
<Label htmlFor="connection-uri">Connection URI</Label>
<Textarea
id="connection-uri"
placeholder="nostr+walletconnect://..."
value={connectionUri}
onChange={(e) => setConnectionUri(e.target.value)}
rows={3}
/>
</div>
</div>
));
AddWalletContent.displayName = 'AddWalletContent';
// Extracted WalletContent to prevent re-renders
const WalletContent = forwardRef<HTMLDivElement, {
hasWebLN: boolean;
isDetecting: boolean;
hasNWC: boolean;
connections: NWCConnection[];
connectionInfo: Record<string, NWCInfo>;
activeConnection: string | null;
handleSetActive: (cs: string) => void;
handleRemoveConnection: (cs: string) => void;
setAddDialogOpen: (open: boolean) => void;
}>(({
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen
}, ref) => (
<div className="space-y-6 px-4 pb-4" ref={ref}>
{/* Current Status */}
<div className="space-y-3">
<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">
<div className="flex items-center gap-3">
<Globe className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">WebLN</p>
<p className="text-xs text-muted-foreground">Browser extension</p>
</div>
</div>
<div className="flex items-center gap-2">
{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>
{/* NWC */}
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Nostr Wallet Connect</p>
<p className="text-xs text-muted-foreground">
{connections.length > 0
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
: "Remote wallet connection"
}
</p>
</div>
</div>
<div className="flex items-center gap-2">
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
{hasNWC ? "Ready" : "None"}
</Badge>
</div>
</div>
</div>
</div>
<Separator />
{/* NWC Management */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="font-medium">Nostr Wallet Connect</h3>
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
<Plus className="h-4 w-4 mr-1" />
Add
</Button>
</div>
{/* Connected Wallets List */}
{connections.length === 0 ? (
<div className="text-center py-6 text-muted-foreground">
<p className="text-sm">No wallets connected</p>
</div>
) : (
<div className="space-y-2">
{connections.map((connection) => {
const info = connectionInfo[connection.connectionString];
const isActive = activeConnection === connection.connectionString;
return (
<div key={connection.connectionString} className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}>
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
{connection.alias || info?.alias || 'Lightning Wallet'}
</p>
<p className="text-xs text-muted-foreground">
NWC Connection
</p>
</div>
</div>
<div className="flex items-center gap-2">
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
{!isActive && (
<Button
size="sm"
variant="ghost"
onClick={() => handleSetActive(connection.connectionString)}
>
<Zap className="h-3 w-3" />
</Button>
)}
<Button
size="sm"
variant="ghost"
onClick={() => handleRemoveConnection(connection.connectionString)}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
);
})}
</div>
)}
</div>
{/* Help */}
{!hasWebLN && connections.length === 0 && (
<>
<Separator />
<div className="text-center py-4 space-y-2">
<p className="text-sm text-muted-foreground">
Install a WebLN extension or connect a NWC wallet for zaps.
</p>
</div>
</>
)}
</div>
));
WalletContent.displayName = 'WalletContent';
export function WalletModal({ children, className }: WalletModalProps) {
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: string) => {
removeConnection(connectionString);
};
const handleSetActive = (connectionString: string) => {
setActiveConnection(connectionString);
toast({
title: 'Active wallet changed',
description: 'The selected wallet is now active for zaps.',
});
};
const walletContentProps = {
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen,
};
const addWalletDialog = (
<Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Connect NWC Wallet</DialogTitle>
<DialogDescription>
Enter your connection string from a compatible wallet.
</DialogDescription>
</DialogHeader>
<AddWalletContent
alias={alias}
setAlias={setAlias}
connectionUri={connectionUri}
setConnectionUri={setConnectionUri}
/>
<DialogFooter className="px-4">
<Button
onClick={handleAddConnection}
disabled={isConnecting || !connectionUri.trim()}
className="w-full"
>
{isConnecting ? 'Connecting...' : 'Connect'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
if (isMobile) {
return (
<>
<Drawer open={open} onOpenChange={setOpen}>
<DrawerTrigger asChild>
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Wallet Settings
</Button>
)}
</DrawerTrigger>
<DrawerContent className="h-full">
<DrawerHeader className="text-center relative">
<DrawerClose asChild>
<Button variant="ghost" size="sm" className="absolute right-4 top-4">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</Button>
</DrawerClose>
<DrawerTitle className="flex items-center justify-center gap-2 pt-2">
<Wallet className="h-5 w-5" />
Lightning Wallet
</DrawerTitle>
<DrawerDescription>
Connect your lightning wallet to send zaps instantly.
</DrawerDescription>
</DrawerHeader>
<div className="overflow-y-auto">
<WalletContent {...walletContentProps} />
</div>
</DrawerContent>
</Drawer>
{/* Render Add Wallet as a separate Drawer for mobile */}
<Drawer open={addDialogOpen} onOpenChange={setAddDialogOpen}>
<DrawerContent>
<DrawerHeader>
<DrawerTitle>Connect NWC Wallet</DrawerTitle>
<DrawerDescription>
Enter your connection string from a compatible wallet.
</DrawerDescription>
</DrawerHeader>
<AddWalletContent
alias={alias}
setAlias={setAlias}
connectionUri={connectionUri}
setConnectionUri={setConnectionUri}
/>
<div className="p-4">
<Button
onClick={handleAddConnection}
disabled={isConnecting || !connectionUri.trim()}
className="w-full"
>
{isConnecting ? 'Connecting...' : 'Connect'}
</Button>
</div>
</DrawerContent>
</Drawer>
</>
);
}
return (
<>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Wallet Settings
</Button>
)}
</DialogTrigger>
<DialogContent className="sm:max-w-[500px] max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5" />
Lightning Wallet
</DialogTitle>
<DialogDescription>
Connect your lightning wallet to send zaps instantly.
</DialogDescription>
</DialogHeader>
<WalletContent {...walletContentProps} />
</DialogContent>
</Dialog>
{addWalletDialog}
</>
);
}
-23
View File
@@ -1,23 +0,0 @@
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') })] }) }));
}
-58
View File
@@ -1,58 +0,0 @@
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';
interface ZapButtonProps {
target: Event;
className?: string;
showCount?: boolean;
zapData?: { count: number; totalSats: number; isLoading?: boolean };
}
export function ZapButton({
target,
className = "text-xs ml-1",
showCount = true,
zapData: externalZapData
}: ZapButtonProps) {
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 (
<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
@@ -1,164 +0,0 @@
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 }) })] })] }));
}
-470
View File
@@ -1,470 +0,0 @@
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 type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
interface ZapDialogProps {
target: Event;
children?: React.ReactNode;
className?: string;
}
const presetAmounts = [
{ amount: 1, icon: Sparkle },
{ amount: 50, icon: Sparkles },
{ amount: 100, icon: Zap },
{ amount: 250, icon: Star },
{ amount: 1000, icon: Rocket },
];
interface ZapContentProps {
invoice: string | null;
amount: number | string;
comment: string;
isZapping: boolean;
qrCodeUrl: string;
copied: boolean;
hasWebLN: boolean;
handleZap: () => void;
handleCopy: () => void;
openInWallet: () => void;
setAmount: (amount: number | string) => void;
setComment: (comment: string) => void;
inputRef: React.RefObject<HTMLInputElement>;
zap: (amount: number, comment: string) => void;
}
// Moved ZapContent outside of ZapDialog to prevent re-renders causing focus loss
const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
invoice,
amount,
comment,
isZapping,
qrCodeUrl,
copied,
hasWebLN,
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">
{hasWebLN && (
<Button
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">
Scan the QR code or copy the invoice to pay with any Lightning wallet.
</div>
</div>
</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"
>
<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"
/>
<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} size="default">
{isZapping ? (
'Creating invoice...'
) : (
<>
<Zap className="h-4 w-4 mr-2" />
Zap {amount} sats
</>
)}
</Button>
</div>
</>
)}
</div>
));
ZapContent.displayName = 'ZapContent';
export function ZapDialog({ target, children, className }: ZapDialogProps) {
const [open, setOpen] = useState(false);
const { user } = useCurrentUser();
const { data: author } = useAuthor(target.pubkey);
const { toast } = useToast();
const { webln, activeNWC, hasWebLN, detectWebLN } = useWallet();
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
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();
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 (
<Drawer
open={open}
onOpenChange={(newOpen) => {
// Reset invoice when closing
if (!newOpen) {
setInvoice(null);
setQrCodeUrl('');
}
setOpen(newOpen);
}}
dismissible={true} // Always allow dismissal via drag
snapPoints={invoice ? [0.5, 0.75, 0.98] : [0.98]}
activeSnapPoint={invoice ? 0.98 : 0.98}
modal={true}
shouldScaleBackground={false}
fadeFromIndex={0}
>
<DrawerTrigger asChild>
<div className={`cursor-pointer ${className || ''}`}>
{children}
</div>
</DrawerTrigger>
<DrawerContent
key={invoice ? 'payment' : 'form'}
className={cn(
"transition-all duration-300",
invoice ? "h-full max-h-screen" : "max-h-[98vh]"
)}
data-testid="zap-modal"
>
<DrawerHeader className="text-center relative">
{/* Back button when showing invoice */}
{invoice && (
<Button
variant="ghost"
size="sm"
onClick={() => {
setInvoice(null);
setQrCodeUrl('');
}}
className="absolute left-4 top-4 flex items-center gap-2"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{/* Close button */}
<DrawerClose asChild>
<Button
variant="ghost"
size="sm"
className="absolute right-4 top-4"
>
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</Button>
</DrawerClose>
<DrawerTitle className="text-lg break-words pt-2">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DrawerTitle>
<DrawerDescription className="text-sm break-words text-center">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
)}
</DrawerDescription>
</DrawerHeader>
<div className="flex-1 overflow-y-auto px-4 pb-4">
<ZapContent {...contentProps} />
</div>
</DrawerContent>
</Drawer>
);
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<div className={`cursor-pointer ${className || ''}`}>
{children}
</div>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px] max-h-[95vh] overflow-hidden" data-testid="zap-modal">
<DialogHeader>
<DialogTitle className="text-lg break-words">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DialogTitle>
<DialogDescription className="text-sm text-center break-words">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
<>
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>
);
}
-19
View File
@@ -1,19 +0,0 @@
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" })] })] })] }));
}
+6 -16
View File
@@ -1,19 +1,18 @@
// 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 { ChevronDown, LogOut, UserIcon, UserPlus } 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, type Account } from '@/hooks/useLoggedInAccounts.js';
import { genUserName } from '@/lib/genUserName.js';
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { RelaySelector } from '@/components/RelaySelector';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
interface AccountSwitcherProps {
onAddAccountClick: () => void;
@@ -64,15 +63,6 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<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>Wallet Settings</span>
</DropdownMenuItem>
</WalletModal>
<DropdownMenuItem
onClick={onAddAccountClick}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
-21
View File
@@ -1,21 +0,0 @@
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) })] }));
}
+16 -25
View File
@@ -2,13 +2,13 @@
// 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';
import { User } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { AccountSwitcher } from './AccountSwitcher';
import { cn } from '@/lib/utils';
export interface LoginAreaProps {
className?: string;
@@ -29,27 +29,18 @@ export function LoginArea({ className }: LoginAreaProps) {
{currentUser ? (
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
) : (
<div className="flex gap-3 justify-center">
<Button
onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
>
<User className='w-4 h-4' />
<span className='truncate'>Log in</span>
</Button><Button
onClick={() => setSignupDialogOpen(true)}
variant="outline"
className="flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all"
>
<UserPlus className="w-4 h-4" />
<span>Sign Up</span>
</Button>
</div>
<Button
onClick={() => setLoginDialogOpen(true)}
className='flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in'
>
<User className='w-4 h-4' />
<span className='truncate'>Log in</span>
</Button>
)}
<LoginDialog
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/>
-168
View File
@@ -1,168 +0,0 @@
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;
+100 -256
View File
@@ -1,15 +1,19 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useRef, useState, useEffect } from 'react';
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
import { Button } from '@/components/ui/button.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';
import React, { useRef, useState } from 'react';
import { Shield, Upload } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import { Input } from '@/components/ui/input.tsx';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog.tsx';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs.tsx';
import { useLoginActions } from '@/hooks/useLoginActions';
interface LoginDialogProps {
isOpen: boolean;
@@ -18,124 +22,54 @@ interface LoginDialogProps {
onSignup?: () => void;
}
const validateNsec = (nsec: string) => {
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
};
const validateBunkerUri = (uri: string) => {
return uri.startsWith('bunker://');
};
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState('');
const [errors, setErrors] = useState<{
nsec?: string;
bunker?: string;
file?: string;
extension?: string;
}>({});
const fileInputRef = useRef<HTMLInputElement>(null);
const login = useLoginActions();
// Reset all state when dialog opens/closes
useEffect(() => {
if (isOpen) {
// Reset state when dialog opens
setIsLoading(false);
setIsFileLoading(false);
setNsec('');
setBunkerUri('');
setErrors({});
// Reset file input
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
}
}, [isOpen]);
const handleExtensionLogin = async () => {
const handleExtensionLogin = () => {
setIsLoading(true);
setErrors(prev => ({ ...prev, extension: undefined }));
try {
if (!('nostr' in window)) {
throw new Error('Nostr extension not found. Please install a NIP-07 extension.');
}
await login.extension();
login.extension();
onLogin();
onClose();
} catch (e: unknown) {
const error = e as Error;
console.error('Bunker login failed:', error);
console.error('Nsec login failed:', error);
} catch (error) {
console.error('Extension login failed:', error);
setErrors(prev => ({
...prev,
extension: error instanceof Error ? error.message : 'Extension login failed'
}));
} finally {
setIsLoading(false);
}
};
const executeLogin = (key: string) => {
setIsLoading(true);
setErrors({});
// Use a timeout to allow the UI to update before the synchronous login call
setTimeout(() => {
try {
login.nsec(key);
onLogin();
onClose();
} catch {
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
setIsLoading(false);
}
}, 50);
};
const handleKeyLogin = () => {
if (!nsec.trim()) {
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
return;
}
if (!validateNsec(nsec)) {
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
return;
}
executeLogin(nsec);
};
const handleBunkerLogin = async () => {
if (!bunkerUri.trim()) {
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
return;
}
if (!validateBunkerUri(bunkerUri)) {
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
return;
}
if (!nsec.trim()) return;
setIsLoading(true);
setErrors(prev => ({ ...prev, bunker: undefined }));
try {
await login.bunker(bunkerUri);
login.nsec(nsec);
onLogin();
onClose();
// Clear the URI from memory
setBunkerUri('');
} catch {
setErrors(prev => ({
...prev,
bunker: 'Failed to connect to bunker. Please check the URI.'
}));
} catch (error) {
console.error('Nsec login failed:', error);
} finally {
setIsLoading(false);
}
};
const handleBunkerLogin = () => {
if (!bunkerUri.trim() || !bunkerUri.startsWith('bunker://')) return;
setIsLoading(true);
try {
login.bunker(bunkerUri);
onLogin();
onClose();
} catch (error) {
console.error('Bunker login failed:', error);
} finally {
setIsLoading(false);
}
@@ -145,27 +79,10 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
const file = e.target.files?.[0];
if (!file) return;
setIsFileLoading(true);
setErrors({});
const reader = new FileReader();
reader.onload = (event) => {
setIsFileLoading(false);
const content = event.target?.result as string;
if (content) {
const trimmedContent = content.trim();
if (validateNsec(trimmedContent)) {
executeLogin(trimmedContent);
} else {
setErrors({ file: 'File does not contain a valid secret key.' });
}
} else {
setErrors({ file: 'Could not read file content.' });
}
};
reader.onerror = () => {
setIsFileLoading(false);
setErrors({ file: 'Failed to read file.' });
setNsec(content.trim());
};
reader.readAsText(file);
};
@@ -177,139 +94,58 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
}
};
const defaultTab = 'nostr' in window ? 'extension' : 'key';
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl overflow-y-scroll")}
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative')}>
<DialogDescription className="text-center">
Sign up or log in to continue
</DialogDescription>
<DialogContent className='sm:max-w-md p-0 overflow-hidden rounded-2xl'>
<DialogHeader className='px-6 pt-6 pb-0 relative'>
<DialogTitle className='text-xl font-semibold text-center'>Log in</DialogTitle>
<DialogDescription className='text-center text-muted-foreground mt-2'>
Access your account securely with your preferred method
</DialogDescription>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1'>
{/* Prominent Sign Up Section */}
<div className='relative p-4 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 border border-blue-200 dark:border-blue-800 overflow-hidden'>
<div className='relative z-10 text-center space-y-3'>
<div className='flex justify-center items-center gap-2 mb-2'>
<Sparkles className='w-5 h-5 text-blue-600' />
<span className='font-semibold text-blue-800 dark:text-blue-200'>
New to Nostr?
</span>
</div>
<p className='text-sm text-blue-700 dark:text-blue-300'>
Create a new account to get started. It's free and open.
</p>
<Button
onClick={handleSignupClick}
className='w-full rounded-full py-3 text-base font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg border-0'
>
<UserPlus className='w-4 h-4 mr-2' />
<span>Sign Up</span>
</Button>
</div>
</div>
{/* Divider */}
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-gray-300 dark:border-gray-600'></div>
</div>
<div className='relative flex justify-center text-sm'>
<span className='px-3 bg-background text-muted-foreground'>
<span>Or log in</span>
</span>
</div>
</div>
{/* Login Methods */}
<Tabs defaultValue={defaultTab} className="w-full">
<TabsList className="grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4">
<TabsTrigger value="extension" className="flex items-center gap-2">
<Shield className="w-4 h-4" />
<span>Extension</span>
</TabsTrigger>
<TabsTrigger value="key" className="flex items-center gap-2">
<KeyRound className="w-4 h-4" />
<span>Key</span>
</TabsTrigger>
<TabsTrigger value="bunker" className="flex items-center gap-2">
<Cloud className="w-4 h-4" />
<span>Bunker</span>
</TabsTrigger>
<div className='px-6 py-8 space-y-6'>
<Tabs defaultValue={'nostr' in window ? 'extension' : 'key'} className='w-full'>
<TabsList className='grid grid-cols-3 mb-6'>
<TabsTrigger value='extension'>Extension</TabsTrigger>
<TabsTrigger value='key'>Nsec</TabsTrigger>
<TabsTrigger value='bunker'>Bunker</TabsTrigger>
</TabsList>
<TabsContent value='extension' className='space-y-3 bg-muted'>
{errors.extension && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{errors.extension}</AlertDescription>
</Alert>
)}
<TabsContent value='extension' className='space-y-4'>
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'>
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' />
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
Login with one click using the browser extension
</p>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
<Button
className='w-full rounded-full py-6'
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
</TabsContent>
<TabsContent value='key' className='space-y-4'>
<div className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='nsec' className='text-sm font-medium'>
Secret Key (nsec)
<label htmlFor='nsec' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Enter your nsec
</label>
<Input
type='password'
id='nsec'
type="password"
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
className={`rounded-lg ${
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
}`}
onChange={(e) => setNsec(e.target.value)}
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary'
placeholder='nsec1...'
autoComplete="off"
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
<Button
className='w-full rounded-full py-3'
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
>
{isLoading ? 'Verifying...' : 'Log In'}
</Button>
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-muted'></div>
</div>
<div className='relative flex justify-center text-xs'>
<span className='px-2 bg-background text-muted-foreground'>
or
</span>
</div>
</div>
<div className='text-center'>
<p className='text-sm mb-2 text-gray-600 dark:text-gray-400'>Or upload a key file</p>
<input
type='file'
accept='.txt'
@@ -319,21 +155,25 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
/>
<Button
variant='outline'
className='w-full'
className='w-full dark:border-gray-700 dark:bg-gray-800 dark:hover:bg-gray-700'
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
>
<Upload className='w-4 h-4 mr-2' />
{isFileLoading ? 'Reading File...' : 'Upload Your Key File'}
Upload Nsec File
</Button>
{errors.file && (
<p className="text-sm text-red-500 mt-2">{errors.file}</p>
)}
</div>
<Button
className='w-full rounded-full py-6 mt-4'
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
>
{isLoading ? 'Verifying...' : 'Login with Nsec'}
</Button>
</div>
</TabsContent>
<TabsContent value='bunker' className='space-y-3 bg-muted'>
<TabsContent value='bunker' className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Bunker URI
@@ -341,36 +181,40 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
<Input
id='bunkerUri'
value={bunkerUri}
onChange={(e) => {
setBunkerUri(e.target.value);
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
}}
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
errors.bunker ? 'border-red-500' : ''
}`}
onChange={(e) => setBunkerUri(e.target.value)}
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary'
placeholder='bunker://'
autoComplete="off"
/>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
{bunkerUri && !bunkerUri.startsWith('bunker://') && (
<p className='text-red-500 text-xs'>URI must start with bunker://</p>
)}
</div>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim()}
>
{isLoading ? 'Connecting...' : 'Login with Bunker'}
</Button>
</div>
<Button
className='w-full rounded-full py-6'
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim() || !bunkerUri.startsWith('bunker://')}
>
{isLoading ? 'Connecting...' : 'Login with Bunker'}
</Button>
</TabsContent>
</Tabs>
<div className='text-center text-sm'>
<p className='text-gray-600 dark:text-gray-400'>
Don't have an account?{' '}
<button
onClick={handleSignupClick}
className='text-primary hover:underline font-medium'
>
Sign up
</button>
</p>
</div>
</div>
</DialogContent>
</Dialog>
);
};
);
};
export default LoginDialog;
-266
View File
@@ -1,266 +0,0 @@
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;
+109 -650
View File
@@ -1,704 +1,163 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useState, useEffect, useRef } from 'react';
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, CheckCircle, Upload, Globe } from 'lucide-react';
import { Button } from '@/components/ui/button.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 React, { useState } from 'react';
import { Download, Key } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog.tsx';
import { toast } from '@/hooks/useToast.ts';
import { useLoginActions } from '@/hooks/useLoginActions';
import { generateSecretKey, nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils.js';
interface SignupDialogProps {
isOpen: boolean;
onClose: () => void;
onComplete?: () => void;
}
const sanitizeFilename = (filename: string) => {
return filename.replace(/[^a-z0-9_.-]/gi, '_');
}
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete }) => {
const [step, setStep] = useState<'welcome' | 'generate' | 'download' | 'profile' | 'done'>('welcome');
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const [step, setStep] = useState<'generate' | 'download' | 'done'>('generate');
const [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [showSparkles, setShowSparkles] = useState(false);
const [keySecured, setKeySecured] = useState<'none' | 'downloaded'>('none');
const [profileData, setProfileData] = useState({
name: '',
about: '',
picture: ''
});
const login = useLoginActions();
const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const avatarFileInputRef = useRef<HTMLInputElement>(null);
// Generate a proper nsec key using nostr-tools
const generateKey = () => {
setIsLoading(true);
setShowSparkles(true);
// Add a dramatic pause for the key generation effect
setTimeout(() => {
try {
// Generate a new secret key
const sk = generateSecretKey();
// Convert to nsec format
setNsec(nip19.nsecEncode(sk));
setStep('download');
toast({
title: 'Your Secret Key is Ready!',
description: 'A new secret key has been generated for you.',
});
} catch {
toast({
title: 'Error',
description: 'Failed to generate key. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
setShowSparkles(false);
}
}, 2000);
try {
// Generate a new secret key
const sk = generateSecretKey();
// Convert to nsec format
setNsec(nip19.nsecEncode(sk));
setStep('download');
} catch (error) {
console.error('Failed to generate key:', error);
toast({
title: 'Error',
description: 'Failed to generate key. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};
const downloadKey = () => {
try {
// Create a blob with the key text
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
// Create a blob with the key text
const blob = new Blob([nsec], { type: 'text/plain' });
const url = globalThis.URL.createObjectURL(blob);
// Sanitize filename
const filename = sanitizeFilename('nostr-nsec-key.txt');
// Create a temporary link element and trigger download
const a = document.createElement('a');
a.href = url;
a.download = 'nsec.txt';
document.body.appendChild(a);
a.click();
// Create a temporary link element and trigger download
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
// Clean up
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
// Clean up immediately
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
// Mark as secured
setKeySecured('downloaded');
toast({
title: 'Secret Key Saved!',
description: 'Your key has been safely stored.',
});
} catch {
toast({
title: 'Download failed',
description: 'Could not download the key file. Please copy it manually.',
variant: 'destructive',
});
}
toast({
title: 'Key downloaded',
description: 'Your key has been downloaded. Keep it safe!',
});
};
const finishSignup = () => {
login.nsec(nsec);
setStep('done');
onClose();
const finishKeySetup = () => {
try {
login.nsec(nsec);
setStep('profile');
} catch {
toast({
title: 'Login Failed',
description: 'Failed to login with the generated key. Please try again.',
variant: 'destructive',
});
}
toast({
title: 'Account created',
description: 'You are now logged in.',
});
};
const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
// Reset file input
e.target.value = '';
// Validate file type
if (!file.type.startsWith('image/')) {
toast({
title: 'Invalid file type',
description: 'Please select an image file for your avatar.',
variant: 'destructive',
});
return;
}
// Validate file size (max 5MB)
if (file.size > 5 * 1024 * 1024) {
toast({
title: 'File too large',
description: 'Avatar image must be smaller than 5MB.',
variant: 'destructive',
});
return;
}
try {
const tags = await uploadFile(file);
// Get the URL from the first tag
const url = tags[0]?.[1];
if (url) {
setProfileData(prev => ({ ...prev, picture: url }));
toast({
title: 'Avatar uploaded!',
description: 'Your avatar has been uploaded successfully.',
});
}
} catch {
toast({
title: 'Upload failed',
description: 'Failed to upload avatar. Please try again.',
variant: 'destructive',
});
}
};
const finishSignup = async (skipProfile = false) => {
// Mark signup completion time for fallback welcome modal
localStorage.setItem('signup_completed', Date.now().toString());
try {
// Publish profile if user provided information
if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) {
const metadata: Record<string, string> = {};
if (profileData.name) metadata.name = profileData.name;
if (profileData.about) metadata.about = profileData.about;
if (profileData.picture) metadata.picture = profileData.picture;
await publishEvent({
kind: 0,
content: JSON.stringify(metadata),
});
toast({
title: 'Profile Created!',
description: 'Your profile has been set up.',
});
}
// Close signup and show welcome modal
onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
} else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
}
} catch {
toast({
title: 'Profile Setup Failed',
description: 'Your account was created but profile setup failed. You can update it later.',
variant: 'destructive',
});
// Still proceed to completion even if profile failed
onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
} else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
}
}
};
const getTitle = () => {
if (step === 'welcome') return (
<span className="flex items-center justify-center gap-2">
Create Your Account
</span>
);
if (step === 'generate') return (
<span className="flex items-center justify-center gap-2">
Generating Your Key
</span>
);
if (step === 'download') return (
<span className="flex items-center justify-center gap-2">
Secret Key
</span>
);
if (step === 'profile') return (
<span className="flex items-center justify-center gap-2">
Create Your Profile
</span>
);
return (
<span className="flex items-center justify-center gap-2">
Welcome!
</span>
);
};
// Reset state when dialog opens
useEffect(() => {
if (isOpen) {
setStep('welcome');
setIsLoading(false);
setNsec('');
setShowSparkles(false);
setKeySecured('none');
setProfileData({ name: '', about: '', picture: '' });
}
}, [isOpen]);
// Add sparkle animation effect
useEffect(() => {
if (showSparkles) {
const interval = setInterval(() => {
// This will trigger re-renders for sparkle animation
}, 100);
return () => clearInterval(interval);
}
}, [showSparkles]);
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent
className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl flex flex-col")}
>
<DialogHeader className={cn('px-6 pt-6 pb-1 relative flex-shrink-0')}>
<DialogTitle className={cn('font-semibold text-center text-lg')}>
{getTitle()}
<DialogContent className='sm:max-w-md p-0 overflow-hidden rounded-2xl'>
<DialogHeader className='px-6 pt-6 pb-0 relative'>
<DialogTitle className='text-xl font-semibold text-center'>
{step === 'generate' && 'Create Your Account'}
{step === 'download' && 'Download Your Key'}
{step === 'done' && 'Setting Up Your Account'}
</DialogTitle>
<DialogDescription className='text-center text-muted-foreground mt-2'>
{step === 'generate' && 'Generate a secure key for your account'}
{step === 'download' && "Keep your key safe - you'll need it to log in"}
{step === 'done' && 'Finalizing your account setup'}
</DialogDescription>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-scroll flex-1'>
{/* Welcome Step - New engaging introduction */}
{step === 'welcome' && (
<div className='text-center space-y-4'>
{/* Hero illustration */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50'>
<div className='flex justify-center items-center space-x-4 mb-3'>
<div className='relative'>
<UserPlus className='w-12 h-12 text-blue-600' />
<Sparkles className='w-4 h-4 text-yellow-500 absolute -top-1 -right-1 animate-pulse' />
</div>
<Globe className='w-16 h-16 text-blue-700 animate-spin-slow' />
<div className='relative'>
<FileText className='w-12 h-12 text-blue-600' />
<Sparkles className='w-4 h-4 text-yellow-500 absolute -top-1 -left-1 animate-pulse' style={{animationDelay: '0.3s'}} />
</div>
</div>
{/* Benefits */}
<div className='grid grid-cols-1 gap-2 text-sm'>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<Shield className='w-4 h-4' />
Decentralized and censorship-resistant
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<User className='w-4 h-4' />
You are in control of your data
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<Globe className='w-4 h-4' />
Join a global network
</div>
</div>
</div>
<div className='space-y-3'>
<Button
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
onClick={() => setStep('generate')}
>
<LogIn className='w-5 h-5 mr-2' />
Get Started
</Button>
</div>
</div>
)}
{/* Generate Step - Enhanced with animations */}
<div className='px-6 py-8 space-y-6'>
{step === 'generate' && (
<div className='text-center space-y-4'>
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-purple-100 dark:from-blue-950/50 dark:to-purple-950/50 overflow-hidden'>
{/* Animated background elements */}
{showSparkles && (
<div className='absolute inset-0'>
{[...Array(12)].map((_, i) => (
<Sparkles
key={i}
className={`absolute w-4 h-4 text-yellow-400 animate-ping`}
style={{
left: `${Math.random() * 80 + 10}%`,
top: `${Math.random() * 80 + 10}%`,
animationDelay: `${Math.random() * 2}s`
}}
/>
))}
</div>
)}
<div className='relative z-10'>
{isLoading ? (
<div className='space-y-3'>
<div className='relative'>
<Key className='w-20 h-20 text-primary mx-auto animate-pulse' />
<div className='absolute inset-0 flex items-center justify-center'>
<div className='w-24 h-24 border-4 border-yellow-400 border-t-transparent rounded-full animate-spin'></div>
</div>
</div>
<div className='space-y-2'>
<p className='text-lg font-semibold text-primary flex items-center justify-center gap-2'>
<Sparkles className='w-5 h-5' />
Generating your secret key...
</p>
<p className='text-sm text-muted-foreground'>
Creating your secure key
</p>
</div>
</div>
) : (
<div className='space-y-3'>
<Key className='w-20 h-20 text-primary mx-auto' />
<div className='space-y-2'>
<p className='text-lg font-semibold'>
Ready to generate your secret key?
</p>
<p className='text-sm text-muted-foreground px-5'>
This key will be your password to access applications within the Nostr network.
</p>
</div>
</div>
)}
</div>
<div className='text-center space-y-6'>
<div className='p-4 rounded-lg bg-gray-50 dark:bg-gray-800 flex items-center justify-center'>
<Key className='w-16 h-16 text-primary' />
</div>
{!isLoading && (
<Button
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
onClick={generateKey}
disabled={isLoading}
>
<Sparkles className='w-5 h-5 mr-2' />
Generate My Secret Key
</Button>
)}
<p className='text-sm text-gray-600 dark:text-gray-300'>
We'll generate a secure key for your account. You'll need this key to log in later.
</p>
<Button
className='w-full rounded-full py-6'
onClick={generateKey}
disabled={isLoading}
>
{isLoading ? 'Generating key...' : 'Generate my key'}
</Button>
</div>
)}
{/* Download Step - Whimsical and magical */}
{step === 'download' && (
<div className='text-center space-y-4'>
{/* Key reveal */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden'>
{/* Sparkles */}
<div className='absolute inset-0 pointer-events-none'>
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
<Sparkles className='absolute bottom-3 right-4 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '1.5s'}} />
</div>
<div className='relative z-10 flex justify-center items-center mb-3'>
<div className='relative'>
<div className='w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg animate-pulse'>
<Key className='w-8 h-8 text-indigo-800' />
</div>
<div className='absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce'>
<Sparkles className='w-3 h-3 text-white' />
</div>
</div>
</div>
<div className='relative z-10 space-y-2'>
<p className='text-base font-semibold'>
Your secret key has been generated!
</p>
{/* Warning */}
<div className='relative mx-auto max-w-sm'>
<div className='p-3 bg-gradient-to-r from-amber-100 via-yellow-50 to-amber-100 dark:from-amber-950/40 dark:via-yellow-950/20 dark:to-amber-950/40 rounded-lg border-2 border-amber-300 dark:border-amber-700 shadow-md'>
<div className='flex items-center gap-2 mb-1'>
<FileText className='w-3 h-3 text-amber-700' />
<span className='text-xs font-bold text-amber-800 dark:text-amber-200'>
Important Warning
</span>
</div>
<p className='text-xs text-red-700 dark:text-amber-300 italic'>
This key is your primary and only means of accessing your account. Store it safely and securely.
</p>
</div>
</div>
</div>
<div className='space-y-6'>
<div className='p-4 rounded-lg border bg-gray-50 dark:bg-gray-800 overflow-auto'>
<code className='text-xs break-all'>{nsec}</code>
</div>
{/* Key vault */}
{/* Security options */}
<div className='space-y-3'>
<div className='grid grid-cols-1 gap-2'>
{/* Download Option */}
<Card className={`cursor-pointer transition-all duration-200 ${
keySecured === 'downloaded'
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20'
}`}>
<CardContent className='p-3'>
<Button
variant="ghost"
className='w-full h-auto p-0 justify-start hover:bg-transparent'
onClick={downloadKey}
>
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${
keySecured === 'downloaded'
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'
}`}>
{keySecured === 'downloaded' ? (
<CheckCircle className='w-4 h-4 text-green-600' />
) : (
<Download className='w-4 h-4 text-primary' />
)}
</div>
<div className='flex-1 text-left'>
<div className='font-medium text-sm'>
Download as File
</div>
<div className='text-xs text-muted-foreground'>
Save as nostr-nsec-key.txt file
</div>
</div>
{keySecured === 'downloaded' && (
<div className='text-xs font-medium text-green-600'>
✓ Downloaded
</div>
)}
</div>
</Button>
</CardContent>
</Card>
</div>
{/* Continue button */}
<Button
className={`w-full rounded-full py-4 text-base font-semibold transform transition-all duration-200 shadow-lg ${
keySecured === 'downloaded'
? 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 dark:from-blue-950/50 dark:to-purple-950/50 hover:scale-105'
: 'bg-gradient-to-r from-blue-600/60 to-indigo-600/60 text-muted cursor-not-allowed'
}`}
onClick={finishKeySetup}
disabled={keySecured !== 'downloaded'}
>
<LogIn className='w-4 h-4 mr-2 flex-shrink-0' />
<span className="text-center leading-tight">
{keySecured === 'none' ? (
<>
Please download your key first
</>
) : (
<>
<span className="hidden sm:inline">My Key is Safe - Continue</span>
<span className="sm:hidden">Key Secured - Continue</span>
</>
)}
</span>
</Button>
</div>
</div>
)}
{/* Profile Step - Optional profile setup */}
{step === 'profile' && (
<div className='text-center space-y-4'>
{/* Profile setup illustration */}
<div className='relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden'>
{/* Sparkles */}
<div className='absolute inset-0 pointer-events-none'>
<Sparkles className='absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '0s'}} />
<Sparkles className='absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse' style={{animationDelay: '0.5s'}} />
<Sparkles className='absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse' style={{animationDelay: '1s'}} />
</div>
<div className='relative z-10 flex justify-center items-center mb-3'>
<div className='relative'>
<div className='w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg'>
<User className='w-8 h-8 text-blue-800' />
</div>
<div className='absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce'>
<Sparkles className='w-3 h-3 text-white' />
</div>
</div>
</div>
<div className='relative z-10 space-y-2'>
<p className='text-base font-semibold'>
Almost there! Let's set up your profile
</p>
<p className='text-sm text-muted-foreground'>
Your profile is your identity on Nostr.
</p>
</div>
<div className='text-sm text-gray-600 dark:text-gray-300 space-y-2'>
<p className='font-medium text-red-500'>Important:</p>
<ul className='list-disc pl-5 space-y-1'>
<li>This is your only way to access your account</li>
<li>Store it somewhere safe</li>
<li>Never share this key with anyone</li>
</ul>
</div>
{/* Publishing status indicator */}
{isPublishing && (
<div className='relative p-4 rounded-xl bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/30 dark:to-indigo-950/30 border border-blue-200 dark:border-blue-800'>
<div className='flex items-center justify-center gap-3'>
<div className='w-5 h-5 border-2 border-blue-600 border-t-transparent rounded-full animate-spin' />
<span className='text-sm font-medium text-blue-700 dark:text-blue-300'>
Publishing your profile...
</span>
</div>
</div>
)}
{/* Profile form */}
<div className={`space-y-4 text-left ${isPublishing ? 'opacity-50 pointer-events-none' : ''}`}>
<div className='space-y-2'>
<label htmlFor='profile-name' className='text-sm font-medium'>
Display Name
</label>
<Input
id='profile-name'
value={profileData.name}
onChange={(e) => setProfileData(prev => ({ ...prev, name: e.target.value }))}
placeholder='Your name'
className='rounded-lg'
disabled={isPublishing}
/>
</div>
<div className='space-y-2'>
<label htmlFor='profile-about' className='text-sm font-medium'>
Bio
</label>
<Textarea
id='profile-about'
value={profileData.about}
onChange={(e) => setProfileData(prev => ({ ...prev, about: e.target.value }))}
placeholder='Tell others about yourself...'
className='rounded-lg resize-none'
rows={3}
disabled={isPublishing}
/>
</div>
<div className='space-y-2'>
<label htmlFor='profile-picture' className='text-sm font-medium'>
Avatar
</label>
<div className='flex gap-2'>
<Input
id='profile-picture'
value={profileData.picture}
onChange={(e) => setProfileData(prev => ({ ...prev, picture: e.target.value }))}
placeholder='https://example.com/your-avatar.jpg'
className='rounded-lg flex-1'
disabled={isPublishing}
/>
<input
type='file'
accept='image/*'
className='hidden'
ref={avatarFileInputRef}
onChange={handleAvatarUpload}
/>
<Button
type='button'
variant='outline'
size='icon'
onClick={() => avatarFileInputRef.current?.click()}
disabled={isUploading || isPublishing}
className='rounded-lg shrink-0'
title='Upload avatar image'
>
{isUploading ? (
<div className='w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin' />
) : (
<Upload className='w-4 h-4' />
)}
</Button>
</div>
</div>
</div>
{/* Action buttons */}
<div className='space-y-3'>
<Button
className='w-full rounded-full py-4 text-base font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none'
onClick={() => finishSignup(false)}
disabled={isPublishing || isUploading}
>
{isPublishing ? (
<>
<div className='w-4 h-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin' />
Creating Profile...
</>
) : (
<>
<User className='w-4 h-4 mr-2' />
Create Profile & Finish
</>
)}
</Button>
<div className='flex flex-col space-y-3'>
<Button
variant='outline'
className='w-full rounded-full py-3 disabled:opacity-50 disabled:cursor-not-allowed'
onClick={() => finishSignup(true)}
disabled={isPublishing || isUploading}
className='w-full'
onClick={downloadKey}
>
{isPublishing ? (
<>
<div className='w-4 h-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin' />
Setting up account...
</>
) : (
'Skip for now'
)}
<Download className='w-4 h-4 mr-2' />
Download Key
</Button>
<Button
className='w-full rounded-full py-6'
onClick={finishSignup}
>
I've saved my key, continue
</Button>
</div>
</div>
)}
{step === 'done' && (
<div className='flex justify-center items-center py-8'>
<div className='animate-spin rounded-full h-12 w-12 border-b-2 border-primary'></div>
</div>
)}
</div>
</DialogContent>
</Dialog>
-29
View File
@@ -1,29 +0,0 @@
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))) }) }))] }));
}
-153
View File
@@ -1,153 +0,0 @@
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { NostrEvent } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor.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';
interface CommentProps {
root: NostrEvent | URL;
comment: NostrEvent;
depth?: number;
maxDepth?: number;
limit?: number;
}
export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: CommentProps) {
const [showReplyForm, setShowReplyForm] = useState(false);
const [showReplies, setShowReplies] = useState(depth < 2); // Auto-expand first 2 levels
const author = useAuthor(comment.pubkey);
const { data: commentsData } = useComments(root, limit);
const metadata = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(comment.pubkey)
const timeAgo = formatDistanceToNow(new Date(comment.created_at * 1000), { addSuffix: true });
// Get direct replies to this comment
const replies = commentsData?.getDirectReplies(comment.id) || [];
const hasReplies = replies.length > 0;
return (
<div className={`space-y-3 ${depth > 0 ? 'ml-6 border-l-2 border-muted pl-4' : ''}`}>
<Card className="bg-card/50">
<CardContent className="p-4">
<div className="space-y-3">
{/* Comment Header */}
<div className="flex items-start justify-between">
<div className="flex items-center space-x-3">
<Link to={`/${nip19.npubEncode(comment.pubkey)}`}>
<Avatar className="h-8 w-8 hover:ring-2 hover:ring-primary/30 transition-all cursor-pointer">
<AvatarImage src={metadata?.picture} />
<AvatarFallback className="text-xs">
{displayName.charAt(0)}
</AvatarFallback>
</Avatar>
</Link>
<div>
<Link
to={`/${nip19.npubEncode(comment.pubkey)}`}
className="font-medium text-sm hover:text-primary transition-colors"
>
{displayName}
</Link>
<p className="text-xs text-muted-foreground">{timeAgo}</p>
</div>
</div>
</div>
{/* Comment Content */}
<div className="text-sm">
<NoteContent event={comment} className="text-sm" />
</div>
{/* Comment Actions */}
<div className="flex items-center justify-between pt-2">
<div className="flex items-center space-x-2">
<Button
variant="ghost"
size="sm"
onClick={() => setShowReplyForm(!showReplyForm)}
className="h-8 px-2 text-xs"
>
<MessageSquare className="h-3 w-3 mr-1" />
Reply
</Button>
{hasReplies && (
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
<CollapsibleTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 px-2 text-xs">
{showReplies ? (
<ChevronDown className="h-3 w-3 mr-1" />
) : (
<ChevronRight className="h-3 w-3 mr-1" />
)}
{replies.length} {replies.length === 1 ? 'reply' : 'replies'}
</Button>
</CollapsibleTrigger>
</Collapsible>
)}
</div>
{/* Comment menu */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 px-2 text-xs"
aria-label="Comment options"
>
<MoreHorizontal className="h-3 w-3" />
</Button>
</DropdownMenuTrigger>
</DropdownMenu>
</div>
</div>
</CardContent>
</Card>
{/* Reply Form */}
{showReplyForm && (
<div className="ml-6">
<CommentForm
root={root}
reply={comment}
onSuccess={() => setShowReplyForm(false)}
placeholder="Write a reply..."
compact
/>
</div>
)}
{/* Replies */}
{hasReplies && (
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
<CollapsibleContent className="space-y-3">
{replies.map((reply) => (
<Comment
key={reply.id}
root={root}
comment={reply}
depth={depth + 1}
maxDepth={maxDepth}
limit={limit}
/>
))}
</CollapsibleContent>
</Collapsible>
)}
</div>
);
}
-29
View File
@@ -1,29 +0,0 @@
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')] })] })] }) }) }));
}
-90
View File
@@ -1,90 +0,0 @@
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 { NostrEvent } from '@nostrify/nostrify';
import { MessageSquare, Send } from 'lucide-react';
interface CommentFormProps {
root: NostrEvent | URL;
reply?: NostrEvent | URL;
onSuccess?: () => void;
placeholder?: string;
compact?: boolean;
}
export function CommentForm({
root,
reply,
onSuccess,
placeholder = "Write a comment...",
compact = false
}: CommentFormProps) {
const [content, setContent] = useState('');
const { user } = useCurrentUser();
const { mutate: postComment, isPending } = usePostComment();
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!content.trim() || !user) return;
postComment(
{ content: content.trim(), root, reply },
{
onSuccess: () => {
setContent('');
onSuccess?.();
},
}
);
};
if (!user) {
return (
<Card className={compact ? "border-dashed" : ""}>
<CardContent className={compact ? "p-4" : "p-6"}>
<div className="text-center space-y-4">
<div className="flex items-center justify-center space-x-2 text-muted-foreground">
<MessageSquare className="h-5 w-5" />
<span>Sign in to {reply ? 'reply' : 'comment'}</span>
</div>
<LoginArea />
</div>
</CardContent>
</Card>
);
}
return (
<Card className={compact ? "border-dashed" : ""}>
<CardContent className={compact ? "p-4" : "p-6"}>
<form onSubmit={handleSubmit} className="space-y-4">
<Textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder={placeholder}
className={compact ? "min-h-[80px]" : "min-h-[100px]"}
disabled={isPending}
/>
<div className="flex justify-between items-center">
<span className="text-sm text-muted-foreground">
{reply ? 'Replying to comment' : 'Adding to the discussion'}
</span>
<Button
type="submit"
disabled={!content.trim() || isPending}
size={compact ? "sm" : "default"}
>
<Send className="h-4 w-4 mr-2" />
{isPending ? 'Posting...' : (reply ? 'Reply' : 'Comment')}
</Button>
</div>
</form>
</CardContent>
</Card>
);
}
@@ -1,16 +0,0 @@
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))) }))] })] }));
}
-100
View File
@@ -1,100 +0,0 @@
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 type { NostrEvent } from '@nostrify/nostrify';
import { CommentForm } from "./CommentForm.js";
import { Comment } from "./Comment.js";
interface CommentsSectionProps {
root: NostrEvent | URL;
title?: string;
emptyStateMessage?: string;
emptyStateSubtitle?: string;
className?: string;
limit?: number;
}
export function CommentsSection({
root,
title = "Comments",
emptyStateMessage = "No comments yet",
emptyStateSubtitle = "Be the first to share your thoughts!",
className,
limit = 500,
}: CommentsSectionProps) {
const { data: commentsData, isLoading, error } = useComments(root, limit);
const comments = commentsData?.topLevelComments || [];
if (error) {
return (
<Card className="rounded-none sm:rounded-lg mx-0 sm:mx-0">
<CardContent className="px-2 py-6 sm:p-6">
<div className="text-center text-muted-foreground">
<MessageSquare className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p>Failed to load comments</p>
</div>
</CardContent>
</Card>
);
}
return (
<Card className={cn("rounded-none sm:rounded-lg mx-0 sm:mx-0", className)}>
<CardHeader className="px-2 pt-6 pb-4 sm:p-6">
<CardTitle className="flex items-center space-x-2">
<MessageSquare className="h-5 w-5" />
<span>{title}</span>
{!isLoading && (
<span className="text-sm font-normal text-muted-foreground">
({comments.length})
</span>
)}
</CardTitle>
</CardHeader>
<CardContent className="px-2 pb-6 pt-4 sm:p-6 sm:pt-0 space-y-6">
{/* Comment Form */}
<CommentForm root={root} />
{/* Comments List */}
{isLoading ? (
<div className="space-y-4">
{[...Array(3)].map((_, i) => (
<Card key={i} className="bg-card/50">
<CardContent className="p-4">
<div className="space-y-3">
<div className="flex items-center space-x-3">
<Skeleton className="h-8 w-8 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
</div>
<Skeleton className="h-16 w-full" />
</div>
</CardContent>
</Card>
))}
</div>
) : comments.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
<MessageSquare className="h-12 w-12 mx-auto mb-4 opacity-30" />
<p className="text-lg font-medium mb-2">{emptyStateMessage}</p>
<p className="text-sm">{emptyStateSubtitle}</p>
</div>
) : (
<div className="space-y-4">
{comments.map((comment) => (
<Comment
key={comment.id}
root={root}
comment={comment}
/>
))}
</div>
)}
</CardContent>
</Card>
);
}
-13
View File
@@ -1,13 +0,0 @@
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.js"
import { cn } from "@/lib/utils"
const Accordion = AccordionPrimitive.Root
-26
View File
@@ -1,26 +0,0 @@
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.js"
import { buttonVariants } from "@/components/ui/button-variants.js"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button-variants"
const AlertDialog = AlertDialogPrimitive.Root
-22
View File
@@ -1,22 +0,0 @@
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.js"
import { cn } from "@/lib/utils"
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
@@ -1,3 +0,0 @@
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio";
const AspectRatio = AspectRatioPrimitive.Root;
export { AspectRatio };
-11
View File
@@ -1,11 +0,0 @@
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.js"
import { cn } from "@/lib/utils"
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
-14
View File
@@ -1,14 +0,0 @@
import { cva } from "class-variance-authority";
export const badgeVariants = cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", {
variants: {
variant: {
default: "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive: "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
});
-7
View File
@@ -1,7 +0,0 @@
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.js"
import { badgeVariants } from "./badge-variants.js"
import { cn } from "@/lib/utils"
import { badgeVariants } from "./badge-variants"
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
-23
View File
@@ -1,23 +0,0 @@
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.js"
import { cn } from "@/lib/utils"
const Breadcrumb = React.forwardRef<
HTMLElement,
-23
View File
@@ -1,23 +0,0 @@
import { cva } from "class-variance-authority";
export const buttonVariants = cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", {
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline: "border border-input 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",
},
});
-11
View File
@@ -1,11 +0,0 @@
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.js"
import { buttonVariants } from "./button-variants.js"
import { cn } from "@/lib/utils"
import { buttonVariants } from "./button-variants"
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
-36
View File
@@ -1,36 +0,0 @@
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.js";
import { buttonVariants } from "@/components/ui/button-variants.js";
import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button-variants";
export type CalendarProps = React.ComponentProps<typeof DayPicker>;
-16
View File
@@ -1,16 +0,0 @@
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.js"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
-98
View File
@@ -1,98 +0,0 @@
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.js"
import { Button } from "@/components/ui/button.js"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
type CarouselApi = UseEmblaCarouselType[1]
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
-130
View File
@@ -1,130 +0,0 @@
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.js"
import { cn } from "@/lib/utils"
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const
-8
View File
@@ -1,8 +0,0 @@
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.js"
import { cn } from "@/lib/utils"
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
-5
View File
@@ -1,5 +0,0 @@
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
@@ -1,28 +0,0 @@
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.js"
import { Dialog, DialogContent } from "@/components/ui/dialog.js"
import { cn } from "@/lib/utils"
import { Dialog, DialogContent } from "@/components/ui/dialog"
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
-33
View File
@@ -1,33 +0,0 @@
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.js"
import { cn } from "@/lib/utils"
const ContextMenu = ContextMenuPrimitive.Root
Loaded 100 of 222 files, more files were not shown because too many files have changed in this diff. Show more