107 Commits
Author SHA1 Message Date
Alex Gleason 1d58b3939f Merge remote-tracking branch 'gitlab/main' into nodenext 2025-09-02 19:27:44 -05:00
Chad Curtis a98151688d Fix linter 2025-09-02 16:23:14 +00:00
Alex Gleason 4ca8523016 .jsx -> .js 2025-09-02 10:20:54 -05:00
Alex Gleason de59de94c3 AGENTS.md: jsx -> js 2025-09-02 09:25:02 -05:00
Alex Gleason a55b3418f4 AGENTS.md: Import Extensions 2025-09-02 02:07:03 -05:00
Alex Gleason 9741f440eb Switch to nodenext, add file extensions to all imports 2025-09-02 01:42:31 -05:00
Chad Curtis d1744b7d71 Merge branch 'infiniteScroll' into 'main'
Add context for pagination (i.e., infinite feed scroll)

See merge request soapbox-pub/mkstack!16
2025-09-01 22:02:49 +00:00
Chad Curtis 6458b24305 Add react-intersection-observer per AGENTS.md 2025-09-01 21:26:23 +00:00
Chad CurtisandAlex Gleason 9114c7db86 Apply 1 suggestion(s) to 1 file(s)
Co-authored-by: Alex Gleason <[email protected]>
2025-09-01 21:25:34 +00:00
Chad CurtisandAlex Gleason b2cc0aef79 Apply 1 suggestion(s) to 1 file(s)
Co-authored-by: Alex Gleason <[email protected]>
2025-09-01 21:25:16 +00:00
Chad CurtisandAlex Gleason 363b2e3ebb Apply 1 suggestion(s) to 1 file(s)
Co-authored-by: Alex Gleason <[email protected]>
2025-09-01 21:25:10 +00:00
Chad CurtisandAlex Gleason 37ff1d6957 Apply 1 suggestion(s) to 1 file(s)
Co-authored-by: Alex Gleason <[email protected]>
2025-09-01 21:24:11 +00:00
Chad CurtisandAlex Gleason 2baccf1ea0 Apply 1 suggestion(s) to 1 file(s)
Co-authored-by: Alex Gleason <[email protected]>
2025-09-01 21:23:55 +00:00
Chad CurtisandAlex Gleason dddeb7fc61 Apply 1 suggestion(s) to 1 file(s)
Co-authored-by: Alex Gleason <[email protected]>
2025-09-01 21:23:33 +00:00
Chad Curtis cf64f2ca83 Update context for pagination duplication potential. 2025-09-01 21:01:19 +00:00
Chad Curtis 0d327372fe Add infinite scroll to AGENTS.md 2025-09-01 20:48:35 +00:00
Alex Gleason b4a1a46430 Remove .github/copilot-instructions.md
https://docs.github.com/en/enterprise-cloud@latest/copilot/tutorials/coding-agent/get-the-best-results#adding-custom-instructions-to-your-repository
2025-09-01 15:28:13 -05:00
Chad Curtis d5c37a13c7 Merge branch 'signupImprovements' into 'main'
Signup flow - simplify text + remove copy button

See merge request soapbox-pub/mkstack!15
2025-09-01 20:11:14 +00:00
Chad Curtis 1879cd18f5 rename key file 2025-09-01 20:00:56 +00:00
Chad Curtis 8ff4046308 Further simplify signup 2025-09-01 19:47:39 +00:00
Chad Curtis be0f74543c Remove copy button from signup flow. npm i 2025-09-01 19:43:53 +00:00
Alex Gleason c0f822a4f4 Remove agent.json 2025-08-31 20:33:12 -05:00
Alex Gleason 480d5905d7 Remove .cursorrules
https://docs.cursor.com/en/context/rules#agents-md
2025-08-31 20:29:54 -05:00
Alex Gleason 31d2aa4761 Remove .goosehints and .gooseignore 2025-08-31 20:28:50 -05:00
Alex Gleason b52374f0db Remove codex.md 2025-08-31 20:27:17 -05:00
Alex Gleason 5c1cff5618 AGENTS.md in AGENTS.md 2025-08-31 20:17:52 -05:00
Alex Gleason e335e787ff Make AGENTS.md the primary context file that gets loaded 2025-08-31 20:11:43 -05:00
Alex Gleason 241a235ce1 gitignore .ai/ 2025-08-30 17:44:58 -05:00
Alex Gleason df80653a83 Update mcp servers 2025-08-18 21:55:35 -05:00
Alex Gleason a862d30e8e Remove sonner 2025-08-09 19:45:54 -08:00
Alex Gleason 5eeb424d43 Revert "Add .ai-history/ to .gitignore"
This reverts commit b6d31cdd9d.
2025-07-30 00:11:29 -05:00
Alex Gleason b6d31cdd9d Add .ai-history/ to .gitignore 2025-07-28 23:55:20 -05:00
Chad Curtis 7473c794cc Merge branch 'zapSupport' into 'main'
Implement Zap + NWC Wallet support

See merge request soapbox-pub/mkstack!11
2025-07-26 00:12:25 +00:00
Chad Curtis 0c039bfbcf revert gitlab-ci to upstream version for now 2025-07-26 00:09:58 +00:00
Chad Curtis 36237fd5b6 attempt to isolate gitlab logic to mainline mkstack 2025-07-25 23:51:13 +00:00
Chad Curtis 1de668785f CONTEXT update per review feedback 2025-07-25 23:47:46 +00:00
Chad Curtis c231ee40ac Merge branch 'main' of gitlab.com:soapbox-pub/mkstack into zapSupport 2025-07-25 23:45:15 +00:00
Alex Gleason fbbf7f8c39 npm audit fix 2025-07-23 16:30:18 -05:00
Chad Curtis 23508f361b clean up mobile drawer height fix 2025-07-17 23:37:19 +00:00
Chad Curtis 612aacb00b Merge branch 'main' of gitlab.com:soapbox-pub/mkstack into zapSupport 2025-07-17 22:38:39 +00:00
Chad Curtis 23f01f7dda Merge branch 'errorBoundary' into 'main'
Add an ErrorBoundary to the default template

See merge request soapbox-pub/mkstack!13
2025-07-17 22:37:17 +00:00
Chad Curtis 68959e0e77 remove iframe postmessage 2025-07-17 22:19:12 +00:00
Chad Curtis d17fc5ddd7 Add default ErrorBoundary with iframe postMessage to template. 2025-07-17 17:18:58 +00:00
Alex Gleason c5dabfdb3a Merge branch 'running-tests' into 'main'
CONTEXT.md: clarify writing tests vs running tests

See merge request soapbox-pub/mkstack!12
2025-07-17 03:47:51 +00:00
Alex Gleason 2cb807a4eb CONTEXT.md: clarify writing tests vs running tests 2025-07-16 22:43:57 -05:00
Alex Gleason 58bd5b1a4e Merge branch 'signupTemplate' into 'main'
Create expanded signup template

See merge request soapbox-pub/mkstack!7
2025-07-16 18:55:04 +00:00
Chad Curtis 2543c9c806 CONTEXT.md update 2025-07-16 18:52:10 +00:00
Alex Gleason 94e29c2f45 Upgrade Nostrify 2025-07-15 15:56:06 -05:00
Alex Gleason 6491300bc6 Merge branch 'bare-nip19-paths' into 'main'
CONTEXT.md: Enhance NIP-19 section

Closes #9

See merge request soapbox-pub/mkstack!9
2025-07-15 17:06:35 +00:00
Chad Curtis d393975ccb generic colors 2025-07-14 21:38:30 +00:00
Chad Curtis 3f25629923 review updates 2025-07-14 21:12:26 +00:00
Chad Curtis c7cfc0fe99 Merge branch 'main' of gitlab.com:soapbox-pub/mkstack into signupTemplate 2025-07-14 21:05:29 +00:00
sepehr-safari 04912496be CONTEXT.md: Introduce NIP19Page.tsx boilerplate and proper routing 2025-07-14 18:25:27 +03:00
Chad Curtis 21540d251f reduce unused functions, consolidate uri check 2025-07-14 15:20:34 +00:00
Chad Curtis 97a493c218 fix redraw issue for wallet configuration 2025-07-14 14:21:57 +00:00
Chad Curtis 6845e6cf7c Fallback to manual payment if webln fails - might be due to user intentionally closing out of it v2 2025-07-14 13:50:22 +00:00
Chad Curtis 3101532a2b Fallback to manual payment if webln fails - might be due to user intentionally closing out of it 2025-07-14 13:50:02 +00:00
Chad Curtis 7c9f3cb797 functional fix for drawer height bug on mobile 2025-07-14 13:01:49 +00:00
Alex Gleason a76c292fec "Writing Tests" clarifications 2025-07-14 02:53:25 -05:00
Chad Curtis 4c129251c7 more potential mobile sizing fixes for vh 2025-07-14 07:44:12 +00:00
Chad Curtis 0484b10a96 fix state issue which resulted in text edits causing repeated focus loss 2025-07-14 07:23:33 +00:00
Chad Curtis 230183bd0c more mobile fixes 2025-07-14 07:09:15 +00:00
Chad Curtis a92f80b6e3 small styling fixes + fix potential memory leaks 2025-07-14 06:27:29 +00:00
Chad Curtis a51094e157 update gitlab ci to expect template failures in the default state 2025-07-14 04:04:50 +00:00
Chad Curtis ab54efba47 merge in from upstream and resolve conflicts 2025-07-14 03:58:49 +00:00
Chad Curtis 0a2474d2f5 mobile enhancements 2025-07-14 03:06:17 +00:00
Alex Gleason 62add9ec26 Merge branch 'comments' into 'main'
Add CommentsSection for NIP-22 (kind 1111) comments

See merge request soapbox-pub/mkstack!10
2025-07-14 02:47:24 +00:00
Chad Curtis 661a5e1eac shorten empty state text to one line 2025-07-14 02:23:20 +00:00
Chad Curtis 9d8b5a3f43 another set of context + zap button fixes 2025-07-14 02:11:23 +00:00
Chad Curtis 8f51db5a49 nwc icon change + context fix 2025-07-14 02:01:30 +00:00
Chad Curtis c98a6bbf64 scrollable manual zap, handle undef target 2025-07-14 01:51:48 +00:00
Chad Curtis 9ed8676d17 context updae + app nwccontext 2025-07-14 01:40:04 +00:00
Chad Curtis 8183e3cc5a cleanup + shakespeare-like manual zap modal 2025-07-14 01:16:31 +00:00
Chad Curtis 0bc03017bb further refinement 2025-07-14 01:03:04 +00:00
Alex Gleason f75ddb6654 Add CommentsSection for NIP-22 (kind 1111) comments 2025-07-13 18:45:25 -05:00
sepehr-safari ebdd4dcb84 CONTEXT.md: Enhance NIP-19 section with extended explanations and real-world implementation guidance 2025-07-14 01:41:34 +03:00
Alex Gleason 3b48df1093 gitlab-ci: run tests in CI, not build (always before deploy) 2025-07-13 17:33:00 -05:00
Chad Curtis 7eecec7506 tidying 2025-07-13 20:12:42 +00:00
Chad Curtis 8c34dbc8d5 further refinement for new app builds 2025-07-13 19:52:58 +00:00
Chad Curtis 45ff37e752 messy, nwc support +_wallet fixes 2025-07-13 17:53:30 +00:00
Chad Curtis 11ac73776c zap in context.md 2025-07-13 06:51:24 +00:00
Chad Curtis 14eccbcb6f wallet configuration settings + nwc baseline support 2025-07-13 06:47:45 +00:00
Chad Curtis 55bf545646 cleanup + icons 2025-07-13 05:59:56 +00:00
Chad Curtis ec1a9777de use event directly 2025-07-13 04:09:32 +00:00
Alex Gleason 5a5c05c1d4 Merge branch 'main' of gitlab.com:soapbox-pub/mkstack 2025-07-12 18:56:31 -05:00
Alex Gleason f7736ddfb1 Upgrade Nostrify 2025-07-12 18:56:22 -05:00
Chad Curtis 7fdcb658b3 use single zaps component 2025-07-12 19:23:50 +00:00
Chad Curtis c37df875b9 user fix 2025-07-12 19:20:34 +00:00
Chad Curtis d68f2d8486 minimal zap support 2025-07-12 19:19:41 +00:00
Alex Gleason b11e843196 Merge branch 'add-gemini-cli' into 'main'
feat: add gemini-cli support

See merge request soapbox-pub/mkstack!8
2025-07-09 14:36:03 +00:00
Derek Ross 414e0bf029 feat: add gemini-cli support 2025-07-08 23:04:45 -04:00
Chad Curtis 7b49400951 fix login state not being reset after using key file upload method 2025-07-08 14:30:15 +00:00
Chad Curtis e226ec42a5 Make wording and icons generic 2025-07-08 14:19:17 +00:00
Chad Curtis baaf7e6ab4 Pull signup flow from Treasures 2025-07-08 13:54:02 +00:00
Alex Gleason 39afb03570 Stronger language against writing unnecessary tests 2025-07-06 18:44:42 -05:00
Alex Gleason 83db2fd539 CONTEXT.md: advise to add "alt" tags 2025-07-05 19:14:30 -05:00
Alex Gleason a2eab78ae3 Improve AppConfigSchema type 2025-07-05 17:50:21 -05:00
Alex Gleason 65b974fb41 vitest: suppress DOM output that exceeds AI context windows 2025-07-05 12:45:16 -05:00
Alex Gleason cadbc02947 Remove unused goose recipe file 2025-07-05 12:33:59 -05:00
Alex Gleason 37aaadbd70 gitignore .env files 2025-07-05 12:33:22 -05:00
Alex Gleason 0cda9cb7fc LoginDialog: use a password input
Fixes https://gitlab.com/soapbox-pub/mkstack/-/issues/13
2025-07-03 19:14:11 -05:00
Alex Gleason 49952a10bf Parse AppConfig with a zod schema 2025-07-03 19:04:40 -05:00
Alex Gleason fce2a3da23 Give Dork 1 beer 2025-06-26 17:57:28 -05:00
Alex Gleason 15dbc6df85 AccountSwitcher: modal={false} 2025-06-26 10:35:59 -05:00
Alex Gleason 508fa84466 Default to Primal relay 2025-06-24 20:38:59 -05:00
Alex Gleason b7ff219e6e avatar: object-cover 2025-06-23 22:49:53 -05:00
Alex Gleason b9750b3759 Update "Vibe with MKStack" link 2025-06-21 14:33:00 -05:00
209 changed files with 9229 additions and 1670 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
CONTEXT.md
+1
View File
@@ -0,0 +1 @@
../.mcp.json
-1
View File
@@ -1 +0,0 @@
../CONTEXT.md
+6
View File
@@ -11,6 +11,7 @@ node_modules
dist
dist-ssr
*.local
.ai/
# Editor directories and files
.idea
@@ -23,3 +24,8 @@ dist-ssr
# Vercel
.vercel
# Secrets
.env
.env.*
!.env.example
+4 -7
View File
@@ -5,16 +5,13 @@ default:
timeout: 1 minute
stages:
- build
- test
- deploy
build:
stage: build
test:
stage: test
script:
- npm run build
only:
variables:
- $CI_DEFAULT_BRANCH != $CI_COMMIT_REF_NAME
- npm run test
pages:
stage: deploy
-1
View File
@@ -1 +0,0 @@
CONTEXT.md
-16
View File
@@ -1,16 +0,0 @@
# 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
+6 -1
View File
@@ -1,9 +1,14 @@
{
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "xjsr", "@nostrbook/mcp"]
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
+6 -1
View File
@@ -1,9 +1,14 @@
{
"servers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "xjsr", "@nostrbook/mcp"]
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
+1089
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1 +1 @@
CONTEXT.md
AGENTS.md
-849
View File
@@ -1,849 +0,0 @@
# 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/tools/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.**
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
-15
View File
@@ -1,15 +0,0 @@
{
"model": "claude-sonnet-4",
"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"]
}
}
}
-1
View File
@@ -1 +0,0 @@
CONTEXT.md
+475 -315
View File
File diff suppressed because it is too large. Load diff
+10 -5
View File
@@ -7,12 +7,15 @@
"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",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.1",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.5",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -50,20 +53,21 @@
"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",
"zod": "^3.23.8"
"webln": "^0.3.2",
"zod": "^3.25.71"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
@@ -73,6 +77,7 @@
"@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",
-32
View File
@@ -1,32 +0,0 @@
version: 1.0.0
title: Nostr Client Development
description: A recipe for building Nostr client applications
instructions: Create a Nostr client application according to the user's request.
extensions:
- type: builtin
name: developer
display_name: Developer Tools
timeout: 300
bundled: true
- type: stdio
name: nostr
cmd: npx
args:
- -y
- xjsr
- "@nostrbook/mcp"
envs: {}
timeout: 20
description: null
bundled: null
- type: stdio
name: fetch
cmd: uvx
args:
- mcp-server-fetch
envs: {}
timeout: 20
description: null
bundled: null
author:
contact: Alex Gleason <[email protected]>
+42
View File
@@ -0,0 +1,42 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// NOTE: This file should normally not be modified unless you are adding a new provider.
// To add new routes, edit the AppRouter.tsx file.
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createHead, UnheadProvider } from '@unhead/react/client';
import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense } from 'react';
import NostrProvider from '@/components/NostrProvider.js';
import { Toaster } from "@/components/ui/toaster.js";
import { TooltipProvider } from "@/components/ui/tooltip.js";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider.js';
import { NWCProvider } from '@/contexts/NWCContext.js';
import AppRouter from "./AppRouter.js";
const head = createHead({
plugins: [
InferSeoMetaPlugin(),
],
});
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
staleTime: 60000, // 1 minute
gcTime: Infinity,
},
},
});
const defaultConfig = {
theme: "light",
relayUrl: "wss://relay.primal.net",
};
const presetRelays = [
{ url: 'wss://ditto.pub/relay', name: 'Ditto' },
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
{ url: 'wss://relay.damus.io', name: 'Damus' },
{ url: 'wss://relay.primal.net', name: 'Primal' },
];
export function App() {
return (_jsx(UnheadProvider, { head: head, children: _jsx(AppProvider, { storageKey: "nostr:app-config", defaultConfig: defaultConfig, presetRelays: presetRelays, children: _jsx(QueryClientProvider, { client: queryClient, children: _jsx(NostrLoginProvider, { storageKey: 'nostr:login', children: _jsx(NostrProvider, { children: _jsx(NWCProvider, { children: _jsxs(TooltipProvider, { children: [_jsx(Toaster, {}), _jsx(Suspense, { children: _jsx(AppRouter, {}) })] }) }) }) }) }) }) }));
}
export default App;
+7
View File
@@ -0,0 +1,7 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { render } from '@testing-library/react';
import { test } from 'vitest';
import App from "./App.js";
test('App', () => {
render(_jsx(App, {}));
});
+1 -1
View File
@@ -1,7 +1,7 @@
import { render } from '@testing-library/react';
import { test } from 'vitest';
import App from './App';
import App from "./App.js";
test('App', () => {
render(<App />);
+16 -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';
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import NostrProvider from '@/components/NostrProvider.js';
import { Toaster } from "@/components/ui/toaster.js";
import { TooltipProvider } from "@/components/ui/tooltip.js";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import AppRouter from './AppRouter';
import { AppProvider } from '@/components/AppProvider.js';
import { NWCProvider } from '@/contexts/NWCContext.js';
import { AppConfig } from '@/contexts/AppContext.js';
import AppRouter from "./AppRouter.js";
const head = createHead({
plugins: [
@@ -32,7 +32,7 @@ const queryClient = new QueryClient({
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.nostr.band",
relayUrl: "wss://relay.primal.net",
};
const presetRelays = [
@@ -49,13 +49,14 @@ export function App() {
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
<NWCProvider>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</NWCProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
+10
View File
@@ -0,0 +1,10 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop.js";
import Index from "./pages/Index.js";
import { NIP19Page } from "./pages/NIP19Page.js";
import NotFound from "./pages/NotFound.js";
export function AppRouter() {
return (_jsxs(BrowserRouter, { children: [_jsx(ScrollToTop, {}), _jsxs(Routes, { children: [_jsx(Route, { path: "/", element: _jsx(Index, {}) }), _jsx(Route, { path: "/:nip19", element: _jsx(NIP19Page, {}) }), _jsx(Route, { path: "*", element: _jsx(NotFound, {}) })] })] }));
}
export default AppRouter;
+6 -3
View File
@@ -1,8 +1,9 @@
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import { ScrollToTop } from "./components/ScrollToTop.js";
import Index from "./pages/Index";
import NotFound from "./pages/NotFound";
import Index from "./pages/Index.js";
import { NIP19Page } from "./pages/NIP19Page.js";
import NotFound from "./pages/NotFound.js";
export function AppRouter() {
return (
@@ -10,6 +11,8 @@ 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
@@ -0,0 +1,65 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage.js';
import { AppContext } from '@/contexts/AppContext.js';
// Zod schema for AppConfig validation
const AppConfigSchema = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
});
export function AppProvider(props) {
const { children, storageKey, defaultConfig, presetRelays, } = props;
// App configuration state with localStorage persistence
const [config, setConfig] = useLocalStorage(storageKey, defaultConfig, {
serialize: JSON.stringify,
deserialize: (value) => {
const parsed = JSON.parse(value);
return AppConfigSchema.parse(parsed);
}
});
// Generic config updater with callback pattern
const updateConfig = (updater) => {
setConfig(updater);
};
const appContextValue = {
config,
updateConfig,
presetRelays,
};
// Apply theme effects to document
useApplyTheme(config.theme);
return (_jsx(AppContext.Provider, { value: appContextValue, children: children }));
}
/**
* Hook to apply theme changes to the document root
*/
function useApplyTheme(theme) {
useEffect(() => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
if (theme === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')
.matches
? 'dark'
: 'light';
root.classList.add(systemTheme);
return;
}
root.classList.add(theme);
}, [theme]);
// Handle system theme changes when theme is set to "system"
useEffect(() => {
if (theme !== 'system')
return;
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
root.classList.add(systemTheme);
};
mediaQuery.addEventListener('change', handleChange);
return () => mediaQuery.removeEventListener('change', handleChange);
}, [theme]);
}
+22 -5
View File
@@ -1,6 +1,7 @@
import { ReactNode, useEffect } from 'react';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage.js';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext.js';
interface AppProviderProps {
children: ReactNode;
@@ -12,6 +13,12 @@ interface AppProviderProps {
presetRelays?: { name: string; url: string }[];
}
// Zod schema for AppConfig validation
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(),
});
export function AppProvider(props: AppProviderProps) {
const {
children,
@@ -21,7 +28,17 @@ export function AppProvider(props: AppProviderProps) {
} = props;
// App configuration state with localStorage persistence
const [config, setConfig] = useLocalStorage<AppConfig>(storageKey, defaultConfig);
const [config, setConfig] = useLocalStorage<AppConfig>(
storageKey,
defaultConfig,
{
serialize: JSON.stringify,
deserialize: (value: string) => {
const parsed = JSON.parse(value);
return AppConfigSchema.parse(parsed);
}
}
);
// Generic config updater with callback pattern
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
@@ -71,11 +88,11 @@ function useApplyTheme(theme: Theme) {
if (theme !== 'system') return;
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
root.classList.add(systemTheme);
};
+120
View File
@@ -0,0 +1,120 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useCurrentUser } from '@/hooks/useCurrentUser.js';
import { useNostrPublish } from '@/hooks/useNostrPublish.js';
import { useToast } from '@/hooks/useToast.js';
import { Button } from '@/components/ui/button.js';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from '@/components/ui/form.js';
import { Input } from '@/components/ui/input.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Switch } from '@/components/ui/switch.js';
import { Loader2, Upload } from 'lucide-react';
import { NSchema as n } from '@nostrify/nostrify';
import { useQueryClient } from '@tanstack/react-query';
import { useUploadFile } from '@/hooks/useUploadFile.js';
export const EditProfileForm = () => {
const queryClient = useQueryClient();
const { user, metadata } = useCurrentUser();
const { mutateAsync: publishEvent, isPending } = useNostrPublish();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const { toast } = useToast();
// Initialize the form with default values
const form = useForm({
resolver: zodResolver(n.metadata()),
defaultValues: {
name: '',
about: '',
picture: '',
banner: '',
website: '',
nip05: '',
bot: false,
},
});
// Update form values when user data is loaded
useEffect(() => {
if (metadata) {
form.reset({
name: metadata.name || '',
about: metadata.about || '',
picture: metadata.picture || '',
banner: metadata.banner || '',
website: metadata.website || '',
nip05: metadata.nip05 || '',
bot: metadata.bot || false,
});
}
}, [metadata, form]);
// Handle file uploads for profile picture and banner
const uploadPicture = async (file, field) => {
try {
// The first tuple in the array contains the URL
const [[_, url]] = await uploadFile(file);
form.setValue(field, url);
toast({
title: 'Success',
description: `${field === 'picture' ? 'Profile picture' : 'Banner'} uploaded successfully`,
});
}
catch (error) {
console.error(`Failed to upload ${field}:`, error);
toast({
title: 'Error',
description: `Failed to upload ${field === 'picture' ? 'profile picture' : 'banner'}. Please try again.`,
variant: 'destructive',
});
}
};
const onSubmit = async (values) => {
if (!user) {
toast({
title: 'Error',
description: 'You must be logged in to update your profile',
variant: 'destructive',
});
return;
}
try {
// Combine existing metadata with new values
const data = { ...metadata, ...values };
// Clean up empty values
for (const key in data) {
if (data[key] === '') {
delete data[key];
}
}
// Publish the metadata event (kind 0)
await publishEvent({
kind: 0,
content: JSON.stringify(data),
});
// Invalidate queries to refresh the data
queryClient.invalidateQueries({ queryKey: ['logins'] });
queryClient.invalidateQueries({ queryKey: ['author', user.pubkey] });
toast({
title: 'Success',
description: 'Your profile has been updated',
});
}
catch (error) {
console.error('Failed to update profile:', error);
toast({
title: 'Error',
description: 'Failed to update your profile. Please try again.',
variant: 'destructive',
});
}
};
return (_jsx(Form, { ...form, children: _jsxs("form", { onSubmit: form.handleSubmit(onSubmit), className: "space-y-6", children: [_jsx(FormField, { control: form.control, name: "name", render: ({ field }) => (_jsxs(FormItem, { children: [_jsx(FormLabel, { children: "Name" }), _jsx(FormControl, { children: _jsx(Input, { placeholder: "Your name", ...field }) }), _jsx(FormDescription, { children: "This is your display name that will be displayed to others." }), _jsx(FormMessage, {})] })) }), _jsx(FormField, { control: form.control, name: "about", render: ({ field }) => (_jsxs(FormItem, { children: [_jsx(FormLabel, { children: "Bio" }), _jsx(FormControl, { children: _jsx(Textarea, { placeholder: "Tell others about yourself", className: "resize-none", ...field }) }), _jsx(FormDescription, { children: "A short description about yourself." }), _jsx(FormMessage, {})] })) }), _jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-6", children: [_jsx(FormField, { control: form.control, name: "picture", render: ({ field }) => (_jsx(ImageUploadField, { field: field, label: "Profile Picture", placeholder: "https://example.com/profile.jpg", description: "URL to your profile picture. You can upload an image or provide a URL.", previewType: "square", onUpload: (file) => uploadPicture(file, 'picture') })) }), _jsx(FormField, { control: form.control, name: "banner", render: ({ field }) => (_jsx(ImageUploadField, { field: field, label: "Banner Image", placeholder: "https://example.com/banner.jpg", description: "URL to a wide banner image for your profile. You can upload an image or provide a URL.", previewType: "wide", onUpload: (file) => uploadPicture(file, 'banner') })) })] }), _jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-6", children: [_jsx(FormField, { control: form.control, name: "website", render: ({ field }) => (_jsxs(FormItem, { children: [_jsx(FormLabel, { children: "Website" }), _jsx(FormControl, { children: _jsx(Input, { placeholder: "https://yourwebsite.com", ...field }) }), _jsx(FormDescription, { children: "Your personal website or social media link." }), _jsx(FormMessage, {})] })) }), _jsx(FormField, { control: form.control, name: "nip05", render: ({ field }) => (_jsxs(FormItem, { children: [_jsx(FormLabel, { children: "NIP-05 Identifier" }), _jsx(FormControl, { children: _jsx(Input, { placeholder: "[email protected]", ...field }) }), _jsx(FormDescription, { children: "Your verified Nostr identifier." }), _jsx(FormMessage, {})] })) })] }), _jsx(FormField, { control: form.control, name: "bot", render: ({ field }) => (_jsxs(FormItem, { className: "flex flex-row items-center justify-between rounded-lg border p-4", children: [_jsxs("div", { className: "space-y-0.5", children: [_jsx(FormLabel, { className: "text-base", children: "Bot Account" }), _jsx(FormDescription, { children: "Mark this account as automated or a bot." })] }), _jsx(FormControl, { children: _jsx(Switch, { checked: field.value, onCheckedChange: field.onChange }) })] })) }), _jsxs(Button, { type: "submit", className: "w-full md:w-auto", disabled: isPending || isUploading, children: [(isPending || isUploading) && (_jsx(Loader2, { className: "mr-2 h-4 w-4 animate-spin" })), "Save Profile"] })] }) }));
};
const ImageUploadField = ({ field, label, placeholder, description, previewType, onUpload, }) => {
const fileInputRef = useRef(null);
return (_jsxs(FormItem, { children: [_jsx(FormLabel, { children: label }), _jsxs("div", { className: "flex flex-col gap-2", children: [_jsx(FormControl, { children: _jsx(Input, { placeholder: placeholder, name: field.name, value: field.value ?? '', onChange: e => field.onChange(e.target.value), onBlur: field.onBlur }) }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("input", { type: "file", ref: fileInputRef, accept: "image/*", className: "hidden", onChange: (e) => {
const file = e.target.files?.[0];
if (file) {
onUpload(file);
}
} }), _jsxs(Button, { type: "button", variant: "outline", size: "sm", onClick: () => fileInputRef.current?.click(), children: [_jsx(Upload, { className: "h-4 w-4 mr-2" }), "Upload Image"] }), field.value && (_jsx("div", { className: `h-10 ${previewType === 'square' ? 'w-10' : 'w-24'} rounded overflow-hidden`, children: _jsx("img", { src: field.value, alt: `${label} preview`, className: "h-full w-full object-cover" }) }))] })] }), _jsx(FormDescription, { children: description }), _jsx(FormMessage, {})] }));
};
+21 -21
View File
@@ -1,10 +1,10 @@
import React, { useEffect, useRef } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
import { Button } from '@/components/ui/button';
import { useCurrentUser } from '@/hooks/useCurrentUser.js';
import { useNostrPublish } from '@/hooks/useNostrPublish.js';
import { useToast } from '@/hooks/useToast.js';
import { Button } from '@/components/ui/button.js';
import {
Form,
FormControl,
@@ -13,14 +13,14 @@ import {
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
} from '@/components/ui/form.js';
import { Input } from '@/components/ui/input.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Switch } from '@/components/ui/switch.js';
import { Loader2, Upload } from 'lucide-react';
import { NSchema as n, type NostrMetadata } from '@nostrify/nostrify';
import { useQueryClient } from '@tanstack/react-query';
import { useUploadFile } from '@/hooks/useUploadFile';
import { useUploadFile } from '@/hooks/useUploadFile.js';
export const EditProfileForm: React.FC = () => {
const queryClient = useQueryClient();
@@ -151,10 +151,10 @@ export const EditProfileForm: React.FC = () => {
<FormItem>
<FormLabel>Bio</FormLabel>
<FormControl>
<Textarea
placeholder="Tell others about yourself"
className="resize-none"
{...field}
<Textarea
placeholder="Tell others about yourself"
className="resize-none"
{...field}
/>
</FormControl>
<FormDescription>
@@ -254,9 +254,9 @@ export const EditProfileForm: React.FC = () => {
)}
/>
<Button
type="submit"
className="w-full md:w-auto"
<Button
type="submit"
className="w-full md:w-auto"
disabled={isPending || isUploading}
>
{(isPending || isUploading) && (
@@ -308,8 +308,8 @@ const ImageUploadField: React.FC<ImageUploadFieldProps> = ({
/>
</FormControl>
<div className="flex items-center gap-2">
<input
type="file"
<input
type="file"
ref={fileInputRef}
accept="image/*"
className="hidden"
@@ -331,9 +331,9 @@ const ImageUploadField: React.FC<ImageUploadFieldProps> = ({
</Button>
{field.value && (
<div className={`h-10 ${previewType === 'square' ? 'w-10' : 'w-24'} rounded overflow-hidden`}>
<img
src={field.value}
alt={`${label} preview`}
<img
src={field.value}
alt={`${label} preview`}
className="h-full w-full object-cover"
/>
</div>
+41
View File
@@ -0,0 +1,41 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Component } from 'react';
export class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null,
};
}
static getDerivedStateFromError(error) {
return {
hasError: true,
error,
};
}
componentDidCatch(error, errorInfo) {
console.error('Error caught by ErrorBoundary:', error, errorInfo);
this.setState({
error,
errorInfo,
});
}
handleReset = () => {
this.setState({
hasError: false,
error: null,
errorInfo: null,
});
};
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (_jsx("div", { className: "min-h-screen bg-background flex items-center justify-center p-4", children: _jsxs("div", { className: "max-w-md w-full space-y-4", children: [_jsxs("div", { className: "text-center", children: [_jsx("h2", { className: "text-2xl font-bold text-foreground mb-2", children: "Something went wrong" }), _jsx("p", { className: "text-muted-foreground", children: "An unexpected error occurred. The error has been reported." })] }), _jsx("div", { className: "bg-muted p-4 rounded-lg", children: _jsxs("details", { className: "text-sm", children: [_jsx("summary", { className: "cursor-pointer font-medium text-foreground", children: "Error details" }), _jsxs("div", { className: "mt-2 space-y-2", children: [_jsxs("div", { children: [_jsx("strong", { className: "text-foreground", children: "Message:" }), _jsx("p", { className: "text-muted-foreground mt-1", children: this.state.error?.message })] }), this.state.error?.stack && (_jsxs("div", { children: [_jsx("strong", { className: "text-foreground", children: "Stack trace:" }), _jsx("pre", { className: "text-xs text-muted-foreground mt-1 overflow-auto max-h-32", children: this.state.error.stack })] }))] })] }) }), _jsxs("div", { className: "flex gap-2", children: [_jsx("button", { onClick: this.handleReset, className: "flex-1 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors", children: "Try again" }), _jsx("button", { onClick: () => window.location.reload(), className: "flex-1 px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90 transition-colors", children: "Reload page" })] })] }) }));
}
return this.props.children;
}
}
+113
View File
@@ -0,0 +1,113 @@
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;
}
}
+45
View File
@@ -0,0 +1,45 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useRef } from 'react';
import { NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrContext } from '@nostrify/react';
import { useQueryClient } from '@tanstack/react-query';
import { useAppContext } from '@/hooks/useAppContext.js';
const NostrProvider = (props) => {
const { children } = props;
const { config, presetRelays } = useAppContext();
const queryClient = useQueryClient();
// Create NPool instance only once
const pool = useRef(undefined);
// Use refs so the pool always has the latest data
const relayUrl = useRef(config.relayUrl);
// Update refs when config changes
useEffect(() => {
relayUrl.current = config.relayUrl;
queryClient.resetQueries();
}, [config.relayUrl, queryClient]);
// Initialize NPool only once
if (!pool.current) {
pool.current = new NPool({
open(url) {
return new NRelay1(url);
},
reqRouter(filters) {
return new Map([[relayUrl.current, filters]]);
},
eventRouter(_event) {
// Publish to the selected relay
const allRelays = new Set([relayUrl.current]);
// Also publish to the preset relays, capped to 5
for (const { url } of (presetRelays ?? [])) {
allRelays.add(url);
if (allRelays.size >= 5) {
break;
}
}
return [...allRelays];
},
});
}
return (_jsx(NostrContext.Provider, { value: { nostr: pool.current }, children: children }));
};
export default NostrProvider;
+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';
import { useAppContext } from '@/hooks/useAppContext.js';
interface NostrProviderProps {
children: React.ReactNode;
+77
View File
@@ -0,0 +1,77 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useMemo } from 'react';
import { Link } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor.js';
import { genUserName } from '@/lib/genUserName.js';
import { cn } from '@/lib/utils.js';
/** Parses content of text note events so that URLs and hashtags are linkified. */
export function NoteContent({ event, className, }) {
// Process the content to render mentions, links, etc.
const content = useMemo(() => {
const text = event.content;
// Regex to find URLs, Nostr references, and hashtags
const regex = /(https?:\/\/[^\s]+)|nostr:(npub1|note1|nprofile1|nevent1)([023456789acdefghjklmnpqrstuvwxyz]+)|(#\w+)/g;
const parts = [];
let lastIndex = 0;
let match;
let keyCounter = 0;
while ((match = regex.exec(text)) !== null) {
const [fullMatch, url, nostrPrefix, nostrData, hashtag] = match;
const index = match.index;
// Add text before this match
if (index > lastIndex) {
parts.push(text.substring(lastIndex, index));
}
if (url) {
// Handle URLs
parts.push(_jsx("a", { href: url, target: "_blank", rel: "noopener noreferrer", className: "text-blue-500 hover:underline", children: url }, `url-${keyCounter++}`));
}
else if (nostrPrefix && nostrData) {
// Handle Nostr references
try {
const nostrId = `${nostrPrefix}${nostrData}`;
const decoded = nip19.decode(nostrId);
if (decoded.type === 'npub') {
const pubkey = decoded.data;
parts.push(_jsx(NostrMention, { pubkey: pubkey }, `mention-${keyCounter++}`));
}
else {
// For other types, just show as a link
parts.push(_jsx(Link, { to: `/${nostrId}`, className: "text-blue-500 hover:underline", children: fullMatch }, `nostr-${keyCounter++}`));
}
}
catch {
// If decoding fails, just render as text
parts.push(fullMatch);
}
}
else if (hashtag) {
// Handle hashtags
const tag = hashtag.slice(1); // Remove the #
parts.push(_jsx(Link, { to: `/t/${tag}`, className: "text-blue-500 hover:underline", children: hashtag }, `hashtag-${keyCounter++}`));
}
lastIndex = index + fullMatch.length;
}
// Add any remaining text
if (lastIndex < text.length) {
parts.push(text.substring(lastIndex));
}
// If no special content was found, just use the plain text
if (parts.length === 0) {
parts.push(text);
}
return parts;
}, [event]);
return (_jsx("div", { className: cn("whitespace-pre-wrap break-words", className), children: content.length > 0 ? content : event.content }));
}
// Helper component to display user mentions
function NostrMention({ pubkey }) {
const author = useAuthor(pubkey);
const npub = nip19.npubEncode(pubkey);
const hasRealName = !!author.data?.metadata?.name;
const displayName = author.data?.metadata?.name ?? genUserName(pubkey);
return (_jsxs(Link, { to: `/${npub}`, className: cn("font-medium hover:underline", hasRealName
? "text-blue-500"
: "text-gray-500 hover:text-gray-700"), children: ["@", displayName] }));
}
+98
View File
@@ -0,0 +1,98 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp.js';
import { NoteContent } from "./NoteContent.js";
describe('NoteContent', () => {
it('linkifies URLs in kind 1 events', () => {
const event = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: 'Check out this link: https://example.com',
sig: 'test-sig',
};
render(_jsx(TestApp, { children: _jsx(NoteContent, { event: event }) }));
const link = screen.getByRole('link', { name: 'https://example.com' });
expect(link).toBeInTheDocument();
expect(link).toHaveAttribute('href', 'https://example.com');
expect(link).toHaveAttribute('target', '_blank');
});
it('linkifies URLs in kind 1111 events (comments)', () => {
const event = {
id: 'test-comment-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1111,
tags: [
['a', '30040:pubkey:identifier'],
['k', '30040'],
['p', 'pubkey'],
],
content: 'I think the log events should be different kind numbers instead of having a `log-type` tag. That way you can use normal Nostr filters to filter the log types. Also, the `note` type should just b a kind 1111: https://nostrbook.dev/kinds/1111',
sig: 'test-sig',
};
render(_jsx(TestApp, { children: _jsx(NoteContent, { event: event }) }));
const link = screen.getByRole('link', { name: 'https://nostrbook.dev/kinds/1111' });
expect(link).toBeInTheDocument();
expect(link).toHaveAttribute('href', 'https://nostrbook.dev/kinds/1111');
expect(link).toHaveAttribute('target', '_blank');
});
it('handles text without URLs correctly', () => {
const event = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1111,
tags: [],
content: 'This is just plain text without any links.',
sig: 'test-sig',
};
render(_jsx(TestApp, { children: _jsx(NoteContent, { event: event }) }));
expect(screen.getByText('This is just plain text without any links.')).toBeInTheDocument();
expect(screen.queryByRole('link')).not.toBeInTheDocument();
});
it('renders hashtags as links', () => {
const event = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: 'This is a post about #nostr and #bitcoin development.',
sig: 'test-sig',
};
render(_jsx(TestApp, { children: _jsx(NoteContent, { event: event }) }));
const nostrHashtag = screen.getByRole('link', { name: '#nostr' });
const bitcoinHashtag = screen.getByRole('link', { name: '#bitcoin' });
expect(nostrHashtag).toBeInTheDocument();
expect(bitcoinHashtag).toBeInTheDocument();
expect(nostrHashtag).toHaveAttribute('href', '/t/nostr');
expect(bitcoinHashtag).toHaveAttribute('href', '/t/bitcoin');
});
it('generates deterministic names for users without metadata and styles them differently', () => {
// Use a valid npub for testing
const event = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: `Mentioning nostr:npub1zg69v7ys40x77y352eufp27daufrg4ncjz4ummcjx3t83y9tehhsqepuh0`,
sig: 'test-sig',
};
render(_jsx(TestApp, { children: _jsx(NoteContent, { event: event }) }));
// The mention should be rendered with a deterministic name
const mention = screen.getByRole('link');
expect(mention).toBeInTheDocument();
// Should have muted styling for generated names (gray instead of blue)
expect(mention).toHaveClass('text-gray-500');
expect(mention).not.toHaveClass('text-blue-500');
// The text should start with @ and contain a generated name (not a truncated npub)
const linkText = mention.textContent;
expect(linkText).not.toMatch(/^@npub1/); // Should not be a truncated npub
expect(linkText).toEqual("@Swift Falcon");
});
});
+5 -5
View File
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { NoteContent } from './NoteContent';
import { TestApp } from '@/test/TestApp.js';
import { NoteContent } from "./NoteContent.js";
import type { NostrEvent } from '@nostrify/nostrify';
describe('NoteContent', () => {
@@ -95,7 +95,7 @@ describe('NoteContent', () => {
const nostrHashtag = screen.getByRole('link', { name: '#nostr' });
const bitcoinHashtag = screen.getByRole('link', { name: '#bitcoin' });
expect(nostrHashtag).toBeInTheDocument();
expect(bitcoinHashtag).toBeInTheDocument();
expect(nostrHashtag).toHaveAttribute('href', '/t/nostr');
@@ -123,11 +123,11 @@ describe('NoteContent', () => {
// The mention should be rendered with a deterministic name
const mention = screen.getByRole('link');
expect(mention).toBeInTheDocument();
// Should have muted styling for generated names (gray instead of blue)
expect(mention).toHaveClass('text-gray-500');
expect(mention).not.toHaveClass('text-blue-500');
// The text should start with @ and contain a generated name (not a truncated npub)
const linkText = mention.textContent;
expect(linkText).not.toMatch(/^@npub1/); // Should not be a truncated npub
+3 -3
View File
@@ -2,9 +2,9 @@ import { useMemo } from 'react';
import { type NostrEvent } from '@nostrify/nostrify';
import { Link } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { cn } from '@/lib/utils';
import { useAuthor } from '@/hooks/useAuthor.js';
import { genUserName } from '@/lib/genUserName.js';
import { cn } from '@/lib/utils.js';
interface NoteContentProps {
event: NostrEvent;
+65
View File
@@ -0,0 +1,65 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react";
import { cn } from "@/lib/utils.js";
import { Button } from "@/components/ui/button.js";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from "@/components/ui/command.js";
import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover.js";
import { useState } from "react";
import { useAppContext } from "@/hooks/useAppContext.js";
export function RelaySelector(props) {
const { className } = props;
const { config, updateConfig, presetRelays = [] } = useAppContext();
const selectedRelay = config.relayUrl;
const setSelectedRelay = (relay) => {
updateConfig((current) => ({ ...current, relayUrl: relay }));
};
const [open, setOpen] = useState(false);
const [inputValue, setInputValue] = useState("");
const selectedOption = presetRelays.find((option) => option.url === selectedRelay);
// Function to normalize relay URL by adding wss:// if no protocol is present
const normalizeRelayUrl = (url) => {
const trimmed = url.trim();
if (!trimmed)
return trimmed;
// Check if it already has a protocol
if (trimmed.includes('://')) {
return trimmed;
}
// Add wss:// prefix
return `wss://${trimmed}`;
};
// Handle adding a custom relay
const handleAddCustomRelay = (url) => {
setSelectedRelay?.(normalizeRelayUrl(url));
setOpen(false);
setInputValue("");
};
// Check if input value looks like a valid relay URL
const isValidRelayInput = (value) => {
const trimmed = value.trim();
if (!trimmed)
return false;
// Basic validation - should contain at least a domain-like structure
const normalized = normalizeRelayUrl(trimmed);
try {
new URL(normalized);
return true;
}
catch {
return false;
}
};
return (_jsxs(Popover, { open: open, onOpenChange: setOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { variant: "outline", role: "combobox", "aria-expanded": open, className: cn("justify-between", className), children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Wifi, { className: "h-4 w-4" }), _jsx("span", { className: "truncate", children: selectedOption
? selectedOption.name
: selectedRelay
? selectedRelay.replace(/^wss?:\/\//, '')
: "Select relay..." })] }), _jsx(ChevronsUpDown, { className: "ml-2 h-4 w-4 shrink-0 opacity-50" })] }) }), _jsx(PopoverContent, { className: "w-[300px] p-0", children: _jsxs(Command, { children: [_jsx(CommandInput, { placeholder: "Search relays or type URL...", value: inputValue, onValueChange: setInputValue }), _jsxs(CommandList, { children: [_jsx(CommandEmpty, { children: inputValue && isValidRelayInput(inputValue) ? (_jsxs(CommandItem, { onSelect: () => handleAddCustomRelay(inputValue), className: "cursor-pointer", children: [_jsx(Plus, { className: "mr-2 h-4 w-4" }), _jsxs("div", { className: "flex flex-col", children: [_jsx("span", { className: "font-medium", children: "Add custom relay" }), _jsx("span", { className: "text-xs text-muted-foreground", children: normalizeRelayUrl(inputValue) })] })] })) : (_jsx("div", { className: "py-6 text-center text-sm text-muted-foreground", children: inputValue ? "Invalid relay URL" : "No relay found." })) }), _jsxs(CommandGroup, { children: [presetRelays
.filter((option) => !inputValue ||
option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
option.url.toLowerCase().includes(inputValue.toLowerCase()))
.map((option) => (_jsxs(CommandItem, { value: option.url, onSelect: (currentValue) => {
setSelectedRelay(normalizeRelayUrl(currentValue));
setOpen(false);
setInputValue("");
}, children: [_jsx(Check, { className: cn("mr-2 h-4 w-4", selectedRelay === option.url ? "opacity-100" : "opacity-0") }), _jsxs("div", { className: "flex flex-col", children: [_jsx("span", { className: "font-medium", children: option.name }), _jsx("span", { className: "text-xs text-muted-foreground", children: option.url })] })] }, option.url))), inputValue && isValidRelayInput(inputValue) && (_jsxs(CommandItem, { onSelect: () => handleAddCustomRelay(inputValue), className: "cursor-pointer border-t", children: [_jsx(Plus, { className: "mr-2 h-4 w-4" }), _jsxs("div", { className: "flex flex-col", children: [_jsx("span", { className: "font-medium", children: "Add custom relay" }), _jsx("span", { className: "text-xs text-muted-foreground", children: normalizeRelayUrl(inputValue) })] })] }))] })] })] }) })] }));
}
+16 -16
View File
@@ -1,6 +1,6 @@
import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils.js";
import { Button } from "@/components/ui/button.js";
import {
Command,
CommandEmpty,
@@ -8,14 +8,14 @@ import {
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
} from "@/components/ui/command.js";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
} from "@/components/ui/popover.js";
import { useState } from "react";
import { useAppContext } from "@/hooks/useAppContext";
import { useAppContext } from "@/hooks/useAppContext.js";
interface RelaySelectorProps {
className?: string;
@@ -24,7 +24,7 @@ interface RelaySelectorProps {
export function RelaySelector(props: RelaySelectorProps) {
const { className } = props;
const { config, updateConfig, presetRelays = [] } = useAppContext();
const selectedRelay = config.relayUrl;
const setSelectedRelay = (relay: string) => {
updateConfig((current) => ({ ...current, relayUrl: relay }));
@@ -39,12 +39,12 @@ export function RelaySelector(props: RelaySelectorProps) {
const normalizeRelayUrl = (url: string): string => {
const trimmed = url.trim();
if (!trimmed) return trimmed;
// Check if it already has a protocol
if (trimmed.includes('://')) {
return trimmed;
}
// Add wss:// prefix
return `wss://${trimmed}`;
};
@@ -60,7 +60,7 @@ export function RelaySelector(props: RelaySelectorProps) {
const isValidRelayInput = (value: string): boolean => {
const trimmed = value.trim();
if (!trimmed) return false;
// Basic validation - should contain at least a domain-like structure
const normalized = normalizeRelayUrl(trimmed);
try {
@@ -83,9 +83,9 @@ export function RelaySelector(props: RelaySelectorProps) {
<div className="flex items-center gap-2">
<Wifi className="h-4 w-4" />
<span className="truncate">
{selectedOption
? selectedOption.name
: selectedRelay
{selectedOption
? selectedOption.name
: selectedRelay
? selectedRelay.replace(/^wss?:\/\//, '')
: "Select relay..."
}
@@ -96,8 +96,8 @@ export function RelaySelector(props: RelaySelectorProps) {
</PopoverTrigger>
<PopoverContent className="w-[300px] p-0">
<Command>
<CommandInput
placeholder="Search relays or type URL..."
<CommandInput
placeholder="Search relays or type URL..."
value={inputValue}
onValueChange={setInputValue}
/>
@@ -124,8 +124,8 @@ export function RelaySelector(props: RelaySelectorProps) {
</CommandEmpty>
<CommandGroup>
{presetRelays
.filter((option) =>
!inputValue ||
.filter((option) =>
!inputValue ||
option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
option.url.toLowerCase().includes(inputValue.toLowerCase())
)
+9
View File
@@ -0,0 +1,9 @@
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
export function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
+87
View File
@@ -0,0 +1,87 @@
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, forwardRef } from 'react';
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X } from 'lucide-react';
import { Button } from '@/components/ui/button.js';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog.js';
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle, DrawerTrigger, DrawerClose, } from '@/components/ui/drawer.js';
import { Input } from '@/components/ui/input.js';
import { Label } from '@/components/ui/label.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Badge } from '@/components/ui/badge.js';
import { Separator } from '@/components/ui/separator.js';
import { useNWC } from '@/hooks/useNWCContext.js';
import { useWallet } from '@/hooks/useWallet.js';
import { useToast } from '@/hooks/useToast.js';
import { useIsMobile } from '@/hooks/useIsMobile.js';
// Extracted AddWalletContent to prevent re-renders
const AddWalletContent = forwardRef(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (_jsxs("div", { className: "space-y-4 px-4", ref: ref, children: [_jsxs("div", { children: [_jsx(Label, { htmlFor: "alias", children: "Wallet Name (optional)" }), _jsx(Input, { id: "alias", placeholder: "My Lightning Wallet", value: alias, onChange: (e) => setAlias(e.target.value) })] }), _jsxs("div", { children: [_jsx(Label, { htmlFor: "connection-uri", children: "Connection URI" }), _jsx(Textarea, { id: "connection-uri", placeholder: "nostr+walletconnect://...", value: connectionUri, onChange: (e) => setConnectionUri(e.target.value), rows: 3 })] })] })));
AddWalletContent.displayName = 'AddWalletContent';
// Extracted WalletContent to prevent re-renders
const WalletContent = forwardRef(({ hasWebLN, isDetecting, hasNWC, connections, connectionInfo, activeConnection, handleSetActive, handleRemoveConnection, setAddDialogOpen }, ref) => (_jsxs("div", { className: "space-y-6 px-4 pb-4", ref: ref, children: [_jsxs("div", { className: "space-y-3", children: [_jsx("h3", { className: "font-medium", children: "Current Status" }), _jsxs("div", { className: "grid gap-3", children: [_jsxs("div", { className: "flex items-center justify-between p-3 border rounded-lg", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(Globe, { className: "h-4 w-4 text-muted-foreground" }), _jsxs("div", { children: [_jsx("p", { className: "text-sm font-medium", children: "WebLN" }), _jsx("p", { className: "text-xs text-muted-foreground", children: "Browser extension" })] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [hasWebLN && _jsx(CheckCircle, { className: "h-4 w-4 text-green-600" }), _jsx(Badge, { variant: hasWebLN ? "default" : "secondary", className: "text-xs", children: isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found" })] })] }), _jsxs("div", { className: "flex items-center justify-between p-3 border rounded-lg", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(WalletMinimal, { className: "h-4 w-4 text-muted-foreground" }), _jsxs("div", { children: [_jsx("p", { className: "text-sm font-medium", children: "Nostr Wallet Connect" }), _jsx("p", { className: "text-xs text-muted-foreground", children: connections.length > 0
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
: "Remote wallet connection" })] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [hasNWC && _jsx(CheckCircle, { className: "h-4 w-4 text-green-600" }), _jsx(Badge, { variant: hasNWC ? "default" : "secondary", className: "text-xs", children: hasNWC ? "Ready" : "None" })] })] })] })] }), _jsx(Separator, {}), _jsxs("div", { className: "space-y-4", children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsx("h3", { className: "font-medium", children: "Nostr Wallet Connect" }), _jsxs(Button, { size: "sm", variant: "outline", onClick: () => setAddDialogOpen(true), children: [_jsx(Plus, { className: "h-4 w-4 mr-1" }), "Add"] })] }), connections.length === 0 ? (_jsx("div", { className: "text-center py-6 text-muted-foreground", children: _jsx("p", { className: "text-sm", children: "No wallets connected" }) })) : (_jsx("div", { className: "space-y-2", children: connections.map((connection) => {
const info = connectionInfo[connection.connectionString];
const isActive = activeConnection === connection.connectionString;
return (_jsxs("div", { className: `flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`, children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(WalletMinimal, { className: "h-4 w-4 text-muted-foreground" }), _jsxs("div", { children: [_jsx("p", { className: "text-sm font-medium", children: connection.alias || info?.alias || 'Lightning Wallet' }), _jsx("p", { className: "text-xs text-muted-foreground", children: "NWC Connection" })] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [isActive && _jsx(CheckCircle, { className: "h-4 w-4 text-green-600" }), !isActive && (_jsx(Button, { size: "sm", variant: "ghost", onClick: () => handleSetActive(connection.connectionString), children: _jsx(Zap, { className: "h-3 w-3" }) })), _jsx(Button, { size: "sm", variant: "ghost", onClick: () => handleRemoveConnection(connection.connectionString), children: _jsx(Trash2, { className: "h-3 w-3" }) })] })] }, connection.connectionString));
}) }))] }), !hasWebLN && connections.length === 0 && (_jsxs(_Fragment, { children: [_jsx(Separator, {}), _jsx("div", { className: "text-center py-4 space-y-2", children: _jsx("p", { className: "text-sm text-muted-foreground", children: "Install a WebLN extension or connect a NWC wallet for zaps." }) })] }))] })));
WalletContent.displayName = 'WalletContent';
export function WalletModal({ children, className }) {
const [open, setOpen] = useState(false);
const [addDialogOpen, setAddDialogOpen] = useState(false);
const [connectionUri, setConnectionUri] = useState('');
const [alias, setAlias] = useState('');
const [isConnecting, setIsConnecting] = useState(false);
const isMobile = useIsMobile();
const { connections, activeConnection, connectionInfo, addConnection, removeConnection, setActiveConnection } = useNWC();
const { hasWebLN, isDetecting } = useWallet();
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
const { toast } = useToast();
const handleAddConnection = async () => {
if (!connectionUri.trim()) {
toast({
title: 'Connection URI required',
description: 'Please enter a valid NWC connection URI.',
variant: 'destructive',
});
return;
}
setIsConnecting(true);
try {
const success = await addConnection(connectionUri.trim(), alias.trim() || undefined);
if (success) {
setConnectionUri('');
setAlias('');
setAddDialogOpen(false);
}
}
finally {
setIsConnecting(false);
}
};
const handleRemoveConnection = (connectionString) => {
removeConnection(connectionString);
};
const handleSetActive = (connectionString) => {
setActiveConnection(connectionString);
toast({
title: 'Active wallet changed',
description: 'The selected wallet is now active for zaps.',
});
};
const walletContentProps = {
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen,
};
const addWalletDialog = (_jsx(Dialog, { open: addDialogOpen, onOpenChange: setAddDialogOpen, children: _jsxs(DialogContent, { className: "sm:max-w-[425px]", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: "Connect NWC Wallet" }), _jsx(DialogDescription, { children: "Enter your connection string from a compatible wallet." })] }), _jsx(AddWalletContent, { alias: alias, setAlias: setAlias, connectionUri: connectionUri, setConnectionUri: setConnectionUri }), _jsx(DialogFooter, { className: "px-4", children: _jsx(Button, { onClick: handleAddConnection, disabled: isConnecting || !connectionUri.trim(), className: "w-full", children: isConnecting ? 'Connecting...' : 'Connect' }) })] }) }));
if (isMobile) {
return (_jsxs(_Fragment, { children: [_jsxs(Drawer, { open: open, onOpenChange: setOpen, children: [_jsx(DrawerTrigger, { asChild: true, children: children || (_jsxs(Button, { variant: "outline", size: "sm", className: className, children: [_jsx(Wallet, { className: "h-4 w-4 mr-2" }), "Wallet Settings"] })) }), _jsxs(DrawerContent, { className: "h-full", children: [_jsxs(DrawerHeader, { className: "text-center relative", children: [_jsx(DrawerClose, { asChild: true, children: _jsxs(Button, { variant: "ghost", size: "sm", className: "absolute right-4 top-4", children: [_jsx(X, { className: "h-4 w-4" }), _jsx("span", { className: "sr-only", children: "Close" })] }) }), _jsxs(DrawerTitle, { className: "flex items-center justify-center gap-2 pt-2", children: [_jsx(Wallet, { className: "h-5 w-5" }), "Lightning Wallet"] }), _jsx(DrawerDescription, { children: "Connect your lightning wallet to send zaps instantly." })] }), _jsx("div", { className: "overflow-y-auto", children: _jsx(WalletContent, { ...walletContentProps }) })] })] }), _jsx(Drawer, { open: addDialogOpen, onOpenChange: setAddDialogOpen, children: _jsxs(DrawerContent, { children: [_jsxs(DrawerHeader, { children: [_jsx(DrawerTitle, { children: "Connect NWC Wallet" }), _jsx(DrawerDescription, { children: "Enter your connection string from a compatible wallet." })] }), _jsx(AddWalletContent, { alias: alias, setAlias: setAlias, connectionUri: connectionUri, setConnectionUri: setConnectionUri }), _jsx("div", { className: "p-4", children: _jsx(Button, { onClick: handleAddConnection, disabled: isConnecting || !connectionUri.trim(), className: "w-full", children: isConnecting ? 'Connecting...' : 'Connect' }) })] }) })] }));
}
return (_jsxs(_Fragment, { children: [_jsxs(Dialog, { open: open, onOpenChange: setOpen, children: [_jsx(DialogTrigger, { asChild: true, children: children || (_jsxs(Button, { variant: "outline", size: "sm", className: className, children: [_jsx(Wallet, { className: "h-4 w-4 mr-2" }), "Wallet Settings"] })) }), _jsxs(DialogContent, { className: "sm:max-w-[500px] max-h-[80vh] overflow-y-auto", children: [_jsxs(DialogHeader, { children: [_jsxs(DialogTitle, { className: "flex items-center gap-2", children: [_jsx(Wallet, { className: "h-5 w-5" }), "Lightning Wallet"] }), _jsx(DialogDescription, { children: "Connect your lightning wallet to send zaps instantly." })] }), _jsx(WalletContent, { ...walletContentProps })] })] }), addWalletDialog] }));
}
+395
View File
@@ -0,0 +1,395 @@
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
@@ -0,0 +1,23 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { ZapDialog } from '@/components/ZapDialog.js';
import { useZaps } from '@/hooks/useZaps.js';
import { useWallet } from '@/hooks/useWallet.js';
import { useCurrentUser } from '@/hooks/useCurrentUser.js';
import { useAuthor } from '@/hooks/useAuthor.js';
import { Zap } from 'lucide-react';
export function ZapButton({ target, className = "text-xs ml-1", showCount = true, zapData: externalZapData }) {
const { user } = useCurrentUser();
const { data: author } = useAuthor(target?.pubkey || '');
const { webln, activeNWC } = useWallet();
// Only fetch data if not provided externally
const { totalSats: fetchedTotalSats, isLoading } = useZaps(externalZapData ? [] : target ?? [], // Empty array prevents fetching if external data provided
webln, activeNWC);
// Don't show zap button if user is not logged in, is the author, or author has no lightning address
if (!user || !target || user.pubkey === target.pubkey || (!author?.metadata?.lud16 && !author?.metadata?.lud06)) {
return null;
}
// Use external data if provided, otherwise use fetched data
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
const showLoading = externalZapData?.isLoading || isLoading;
return (_jsx(ZapDialog, { target: target, children: _jsxs("div", { className: `flex items-center gap-1 ${className}`, children: [_jsx(Zap, { className: "h-4 w-4" }), _jsx("span", { className: "text-xs", children: showLoading ? ('...') : showCount && totalSats > 0 ? (`${totalSats.toLocaleString()}`) : ('Zap') })] }) }));
}
+58
View File
@@ -0,0 +1,58 @@
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
@@ -0,0 +1,164 @@
import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect, useRef, forwardRef } from 'react';
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X } from 'lucide-react';
import { Button } from '@/components/ui/button.js';
import { cn } from '@/lib/utils.js';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog.js';
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle, DrawerTrigger, DrawerClose, } from '@/components/ui/drawer.js';
import { Input } from '@/components/ui/input.js';
import { Label } from '@/components/ui/label.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Card, CardContent } from '@/components/ui/card.js';
import { Separator } from '@/components/ui/separator.js';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group.js';
import { useCurrentUser } from '@/hooks/useCurrentUser.js';
import { useAuthor } from '@/hooks/useAuthor.js';
import { useToast } from '@/hooks/useToast.js';
import { useZaps } from '@/hooks/useZaps.js';
import { useWallet } from '@/hooks/useWallet.js';
import { useIsMobile } from '@/hooks/useIsMobile.js';
import QRCode from 'qrcode';
const presetAmounts = [
{ amount: 1, icon: Sparkle },
{ amount: 50, icon: Sparkles },
{ amount: 100, icon: Zap },
{ amount: 250, icon: Star },
{ amount: 1000, icon: Rocket },
];
// Moved ZapContent outside of ZapDialog to prevent re-renders causing focus loss
const ZapContent = forwardRef(({ invoice, amount, comment, isZapping, qrCodeUrl, copied, hasWebLN, handleZap, handleCopy, openInWallet, setAmount, setComment, inputRef, zap, }, ref) => (_jsx("div", { ref: ref, children: invoice ? (_jsxs("div", { className: "flex flex-col h-full min-h-0", children: [_jsx("div", { className: "text-center pt-4", children: _jsxs("div", { className: "text-2xl font-bold", children: [amount, " sats"] }) }), _jsx(Separator, { className: "my-4" }), _jsxs("div", { className: "flex flex-col justify-center min-h-0 flex-1 px-2", children: [_jsx("div", { className: "flex justify-center", children: _jsx(Card, { className: "p-3 [@media(max-height:680px)]:max-w-[65vw] max-w-[95vw] mx-auto", children: _jsx(CardContent, { className: "p-0 flex justify-center", children: qrCodeUrl ? (_jsx("img", { src: qrCodeUrl, alt: "Lightning Invoice QR Code", className: "w-full h-auto aspect-square max-w-full object-contain" })) : (_jsx("div", { className: "w-full aspect-square bg-muted animate-pulse rounded" })) }) }) }), _jsxs("div", { className: "space-y-2 mt-4", children: [_jsx(Label, { htmlFor: "invoice", children: "Lightning Invoice" }), _jsxs("div", { className: "flex gap-2 min-w-0", children: [_jsx(Input, { id: "invoice", value: invoice, readOnly: true, className: "font-mono text-xs min-w-0 flex-1 overflow-hidden text-ellipsis", onClick: (e) => e.currentTarget.select() }), _jsx(Button, { variant: "outline", size: "icon", onClick: handleCopy, className: "shrink-0", children: copied ? (_jsx(Check, { className: "h-4 w-4 text-green-600" })) : (_jsx(Copy, { className: "h-4 w-4" })) })] })] }), _jsxs("div", { className: "space-y-3 mt-4", children: [hasWebLN && (_jsxs(Button, { onClick: () => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
}, disabled: isZapping, className: "w-full", size: "lg", children: [_jsx(Zap, { className: "h-4 w-4 mr-2" }), isZapping ? "Processing..." : "Pay with WebLN"] })), _jsxs(Button, { variant: "outline", onClick: openInWallet, className: "w-full", size: "lg", children: [_jsx(ExternalLink, { className: "h-4 w-4 mr-2" }), "Open in Lightning Wallet"] }), _jsx("div", { className: "text-xs sm:text-[.65rem] text-muted-foreground text-center", children: "Scan the QR code or copy the invoice to pay with any Lightning wallet." })] })] })] })) : (_jsxs(_Fragment, { children: [_jsxs("div", { className: "grid gap-3 px-4 py-4 w-full overflow-hidden", children: [_jsx(ToggleGroup, { type: "single", value: String(amount), onValueChange: (value) => {
if (value) {
setAmount(parseInt(value, 10));
}
}, className: "grid grid-cols-5 gap-1 w-full", children: presetAmounts.map(({ amount: presetAmount, icon: Icon }) => (_jsxs(ToggleGroupItem, { value: String(presetAmount), className: "flex flex-col h-auto min-w-0 text-xs px-1 py-2", children: [_jsx(Icon, { className: "h-4 w-4 mb-1" }), _jsx("span", { className: "truncate", children: presetAmount })] }, presetAmount))) }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("div", { className: "h-px flex-1 bg-muted" }), _jsx("span", { className: "text-xs text-muted-foreground", children: "OR" }), _jsx("div", { className: "h-px flex-1 bg-muted" })] }), _jsx(Input, { ref: inputRef, id: "custom-amount", type: "number", placeholder: "Custom amount", value: amount, onChange: (e) => setAmount(e.target.value), className: "w-full text-sm" }), _jsx(Textarea, { id: "custom-comment", placeholder: "Add a comment (optional)", value: comment, onChange: (e) => setComment(e.target.value), className: "w-full resize-none text-sm", rows: 2 })] }), _jsx("div", { className: "px-4 pb-4", children: _jsx(Button, { onClick: handleZap, className: "w-full", disabled: isZapping, size: "default", children: isZapping ? ('Creating invoice...') : (_jsxs(_Fragment, { children: [_jsx(Zap, { className: "h-4 w-4 mr-2" }), "Zap ", amount, " sats"] })) }) })] })) })));
ZapContent.displayName = 'ZapContent';
export function ZapDialog({ target, children, className }) {
const [open, setOpen] = useState(false);
const { user } = useCurrentUser();
const { data: author } = useAuthor(target.pubkey);
const { toast } = useToast();
const { webln, activeNWC, hasWebLN, detectWebLN } = useWallet();
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
const [amount, setAmount] = useState(100);
const [comment, setComment] = useState('');
const [copied, setCopied] = useState(false);
const [qrCodeUrl, setQrCodeUrl] = useState('');
const inputRef = useRef(null);
const isMobile = useIsMobile();
useEffect(() => {
if (target) {
setComment('Zapped with MKStack!');
}
}, [target]);
// Detect WebLN when dialog opens
useEffect(() => {
if (open && !hasWebLN) {
detectWebLN();
}
}, [open, hasWebLN, detectWebLN]);
// Generate QR code
useEffect(() => {
let isCancelled = false;
const generateQR = async () => {
if (!invoice) {
setQrCodeUrl('');
return;
}
try {
const url = await QRCode.toDataURL(invoice.toUpperCase(), {
width: 512,
margin: 2,
color: {
dark: '#000000',
light: '#FFFFFF',
},
});
if (!isCancelled) {
setQrCodeUrl(url);
}
}
catch (err) {
if (!isCancelled) {
console.error('Failed to generate QR code:', err);
}
}
};
generateQR();
return () => {
isCancelled = true;
};
}, [invoice]);
const handleCopy = async () => {
if (invoice) {
await navigator.clipboard.writeText(invoice);
setCopied(true);
toast({
title: 'Invoice copied',
description: 'Lightning invoice copied to clipboard',
});
setTimeout(() => setCopied(false), 2000);
}
};
const openInWallet = () => {
if (invoice) {
const lightningUrl = `lightning:${invoice}`;
window.open(lightningUrl, '_blank');
}
};
useEffect(() => {
if (open) {
setAmount(100);
setInvoice(null);
setCopied(false);
setQrCodeUrl('');
}
else {
// Clean up state when dialog closes
setAmount(100);
setInvoice(null);
setCopied(false);
setQrCodeUrl('');
}
}, [open, setInvoice]);
const handleZap = () => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
};
const contentProps = {
invoice,
amount,
comment,
isZapping,
qrCodeUrl,
copied,
hasWebLN,
handleZap,
handleCopy,
openInWallet,
setAmount,
setComment,
inputRef,
zap,
};
if (!user || user.pubkey === target.pubkey || !author?.metadata?.lud06 && !author?.metadata?.lud16) {
return null;
}
if (isMobile) {
// Use drawer for entire mobile flow, make it full-screen when showing invoice
return (_jsxs(Drawer, { open: open, onOpenChange: (newOpen) => {
// Reset invoice when closing
if (!newOpen) {
setInvoice(null);
setQrCodeUrl('');
}
setOpen(newOpen);
}, dismissible: true, snapPoints: invoice ? [0.5, 0.75, 0.98] : [0.98], activeSnapPoint: invoice ? 0.98 : 0.98, modal: true, shouldScaleBackground: false, fadeFromIndex: 0, children: [_jsx(DrawerTrigger, { asChild: true, children: _jsx("div", { className: `cursor-pointer ${className || ''}`, children: children }) }), _jsxs(DrawerContent, { className: cn("transition-all duration-300", invoice ? "h-full max-h-screen" : "max-h-[98vh]"), "data-testid": "zap-modal", children: [_jsxs(DrawerHeader, { className: "text-center relative", children: [invoice && (_jsx(Button, { variant: "ghost", size: "sm", onClick: () => {
setInvoice(null);
setQrCodeUrl('');
}, className: "absolute left-4 top-4 flex items-center gap-2", children: _jsx(ArrowLeft, { className: "h-4 w-4" }) })), _jsx(DrawerClose, { asChild: true, children: _jsxs(Button, { variant: "ghost", size: "sm", className: "absolute right-4 top-4", children: [_jsx(X, { className: "h-4 w-4" }), _jsx("span", { className: "sr-only", children: "Close" })] }) }), _jsx(DrawerTitle, { className: "text-lg break-words pt-2", children: invoice ? 'Lightning Payment' : 'Send a Zap' }), _jsx(DrawerDescription, { className: "text-sm break-words text-center", children: invoice ? ('Pay with Bitcoin Lightning Network') : ('Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!') })] }), _jsx("div", { className: "flex-1 overflow-y-auto px-4 pb-4", children: _jsx(ZapContent, { ...contentProps }) })] }, invoice ? 'payment' : 'form')] }));
}
return (_jsxs(Dialog, { open: open, onOpenChange: setOpen, children: [_jsx(DialogTrigger, { asChild: true, children: _jsx("div", { className: `cursor-pointer ${className || ''}`, children: children }) }), _jsxs(DialogContent, { className: "sm:max-w-[425px] max-h-[95vh] overflow-hidden", "data-testid": "zap-modal", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { className: "text-lg break-words", children: invoice ? 'Lightning Payment' : 'Send a Zap' }), _jsx(DialogDescription, { className: "text-sm text-center break-words", children: invoice ? ('Pay with Bitcoin Lightning Network') : (_jsx(_Fragment, { children: "Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!" })) })] }), _jsx("div", { className: "overflow-y-auto", children: _jsx(ZapContent, { ...contentProps }) })] })] }));
}
+470
View File
@@ -0,0 +1,470 @@
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
@@ -0,0 +1,19 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { ChevronDown, LogOut, UserIcon, UserPlus, Wallet } from 'lucide-react';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu.js';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.js';
import { RelaySelector } from '@/components/RelaySelector.js';
import { WalletModal } from '@/components/WalletModal.js';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts.js';
import { genUserName } from '@/lib/genUserName.js';
export function AccountSwitcher({ onAddAccountClick }) {
const { currentUser, otherUsers, setLogin, removeLogin } = useLoggedInAccounts();
if (!currentUser)
return null;
const getDisplayName = (account) => {
return account.metadata.name ?? genUserName(account.pubkey);
};
return (_jsxs(DropdownMenu, { modal: false, children: [_jsx(DropdownMenuTrigger, { asChild: true, children: _jsxs("button", { className: 'flex items-center gap-3 p-3 rounded-full hover:bg-accent transition-all w-full text-foreground', children: [_jsxs(Avatar, { className: 'w-10 h-10', children: [_jsx(AvatarImage, { src: currentUser.metadata.picture, alt: getDisplayName(currentUser) }), _jsx(AvatarFallback, { children: getDisplayName(currentUser).charAt(0) })] }), _jsx("div", { className: 'flex-1 text-left hidden md:block truncate', children: _jsx("p", { className: 'font-medium text-sm truncate', children: getDisplayName(currentUser) }) }), _jsx(ChevronDown, { className: 'w-4 h-4 text-muted-foreground' })] }) }), _jsxs(DropdownMenuContent, { className: 'w-56 p-2 animate-scale-in', children: [_jsx("div", { className: 'font-medium text-sm px-2 py-1.5', children: "Switch Relay" }), _jsx(RelaySelector, { className: "w-full" }), _jsx(DropdownMenuSeparator, {}), _jsx("div", { className: 'font-medium text-sm px-2 py-1.5', children: "Switch Account" }), otherUsers.map((user) => (_jsxs(DropdownMenuItem, { onClick: () => setLogin(user.id), className: 'flex items-center gap-2 cursor-pointer p-2 rounded-md', children: [_jsxs(Avatar, { className: 'w-8 h-8', children: [_jsx(AvatarImage, { src: user.metadata.picture, alt: getDisplayName(user) }), _jsx(AvatarFallback, { children: getDisplayName(user)?.charAt(0) || _jsx(UserIcon, {}) })] }), _jsx("div", { className: 'flex-1 truncate', children: _jsx("p", { className: 'text-sm font-medium', children: getDisplayName(user) }) }), user.id === currentUser.id && _jsx("div", { className: 'w-2 h-2 rounded-full bg-primary' })] }, user.id))), _jsx(DropdownMenuSeparator, {}), _jsx(WalletModal, { children: _jsxs(DropdownMenuItem, { className: 'flex items-center gap-2 cursor-pointer p-2 rounded-md', onSelect: (e) => e.preventDefault(), children: [_jsx(Wallet, { className: 'w-4 h-4' }), _jsx("span", { children: "Wallet Settings" })] }) }), _jsxs(DropdownMenuItem, { onClick: onAddAccountClick, className: 'flex items-center gap-2 cursor-pointer p-2 rounded-md', children: [_jsx(UserPlus, { className: 'w-4 h-4' }), _jsx("span", { children: "Add another account" })] }), _jsxs(DropdownMenuItem, { onClick: () => removeLogin(currentUser.id), className: 'flex items-center gap-2 cursor-pointer p-2 rounded-md text-red-500', children: [_jsx(LogOut, { className: 'w-4 h-4' }), _jsx("span", { children: "Log out" })] })] })] }));
}
+17 -7
View File
@@ -1,18 +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 { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react';
import { ChevronDown, LogOut, UserIcon, UserPlus, Wallet } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} 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';
} from '@/components/ui/dropdown-menu.js';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.js';
import { RelaySelector } from '@/components/RelaySelector.js';
import { WalletModal } from '@/components/WalletModal.js';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts.js';
import { genUserName } from '@/lib/genUserName.js';
interface AccountSwitcherProps {
onAddAccountClick: () => void;
@@ -28,7 +29,7 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
}
return (
<DropdownMenu>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-accent transition-all w-full text-foreground'>
<Avatar className='w-10 h-10'>
@@ -63,6 +64,15 @@ 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
@@ -0,0 +1,21 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { useState } from 'react';
import { User, UserPlus } from 'lucide-react';
import { Button } from '@/components/ui/button.js';
import LoginDialog from "./LoginDialog.js";
import SignupDialog from "./SignupDialog.js";
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts.js';
import { AccountSwitcher } from "./AccountSwitcher.js";
import { cn } from '@/lib/utils.js';
export function LoginArea({ className }) {
const { currentUser } = useLoggedInAccounts();
const [loginDialogOpen, setLoginDialogOpen] = useState(false);
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
const handleLogin = () => {
setLoginDialogOpen(false);
setSignupDialogOpen(false);
};
return (_jsxs("div", { className: cn("inline-flex items-center justify-center", className), children: [currentUser ? (_jsx(AccountSwitcher, { onAddAccountClick: () => setLoginDialogOpen(true) })) : (_jsxs("div", { className: "flex gap-3 justify-center", children: [_jsxs(Button, { onClick: () => setLoginDialogOpen(true), className: 'flex items-center gap-2 px-4 py-2 rounded-full bg-primary text-primary-foreground w-full font-medium transition-all hover:bg-primary/90 animate-scale-in', children: [_jsx(User, { className: 'w-4 h-4' }), _jsx("span", { className: 'truncate', children: "Log in" })] }), _jsxs(Button, { onClick: () => setSignupDialogOpen(true), variant: "outline", className: "flex items-center gap-2 px-4 py-2 rounded-full font-medium transition-all", children: [_jsx(UserPlus, { className: "w-4 h-4" }), _jsx("span", { children: "Sign Up" })] })] })), _jsx(LoginDialog, { isOpen: loginDialogOpen, onClose: () => setLoginDialogOpen(false), onLogin: handleLogin, onSignup: () => setSignupDialogOpen(true) }), _jsx(SignupDialog, { isOpen: signupDialogOpen, onClose: () => setSignupDialogOpen(false) })] }));
}
+25 -16
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 } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog';
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { AccountSwitcher } from './AccountSwitcher';
import { cn } from '@/lib/utils';
import { 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 interface LoginAreaProps {
className?: string;
@@ -29,18 +29,27 @@ export function LoginArea({ className }: LoginAreaProps) {
{currentUser ? (
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
) : (
<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>
<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>
)}
<LoginDialog
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/>
+168
View File
@@ -0,0 +1,168 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { useRef, useState, useEffect } from 'react';
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
import { Button } from '@/components/ui/button.js';
import { Input } from '@/components/ui/input.js';
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog.js";
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs.js';
import { Alert, AlertDescription } from '@/components/ui/alert.js';
import { useLoginActions } from '@/hooks/useLoginActions.js';
import { cn } from '@/lib/utils.js';
const validateNsec = (nsec) => {
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
};
const validateBunkerUri = (uri) => {
return uri.startsWith('bunker://');
};
const LoginDialog = ({ isOpen, onClose, onLogin, onSignup }) => {
const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState('');
const [errors, setErrors] = useState({});
const fileInputRef = useRef(null);
const login = useLoginActions();
// Reset all state when dialog opens/closes
useEffect(() => {
if (isOpen) {
// Reset state when dialog opens
setIsLoading(false);
setIsFileLoading(false);
setNsec('');
setBunkerUri('');
setErrors({});
// Reset file input
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
}
}, [isOpen]);
const handleExtensionLogin = async () => {
setIsLoading(true);
setErrors(prev => ({ ...prev, extension: undefined }));
try {
if (!('nostr' in window)) {
throw new Error('Nostr extension not found. Please install a NIP-07 extension.');
}
await login.extension();
onLogin();
onClose();
}
catch (e) {
const error = e;
console.error('Bunker login failed:', error);
console.error('Nsec login failed:', error);
console.error('Extension login failed:', error);
setErrors(prev => ({
...prev,
extension: error instanceof Error ? error.message : 'Extension login failed'
}));
}
finally {
setIsLoading(false);
}
};
const executeLogin = (key) => {
setIsLoading(true);
setErrors({});
// Use a timeout to allow the UI to update before the synchronous login call
setTimeout(() => {
try {
login.nsec(key);
onLogin();
onClose();
}
catch {
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
setIsLoading(false);
}
}, 50);
};
const handleKeyLogin = () => {
if (!nsec.trim()) {
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
return;
}
if (!validateNsec(nsec)) {
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
return;
}
executeLogin(nsec);
};
const handleBunkerLogin = async () => {
if (!bunkerUri.trim()) {
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
return;
}
if (!validateBunkerUri(bunkerUri)) {
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
return;
}
setIsLoading(true);
setErrors(prev => ({ ...prev, bunker: undefined }));
try {
await login.bunker(bunkerUri);
onLogin();
onClose();
// Clear the URI from memory
setBunkerUri('');
}
catch {
setErrors(prev => ({
...prev,
bunker: 'Failed to connect to bunker. Please check the URI.'
}));
}
finally {
setIsLoading(false);
}
};
const handleFileUpload = (e) => {
const file = e.target.files?.[0];
if (!file)
return;
setIsFileLoading(true);
setErrors({});
const reader = new FileReader();
reader.onload = (event) => {
setIsFileLoading(false);
const content = event.target?.result;
if (content) {
const trimmedContent = content.trim();
if (validateNsec(trimmedContent)) {
executeLogin(trimmedContent);
}
else {
setErrors({ file: 'File does not contain a valid secret key.' });
}
}
else {
setErrors({ file: 'Could not read file content.' });
}
};
reader.onerror = () => {
setIsFileLoading(false);
setErrors({ file: 'Failed to read file.' });
};
reader.readAsText(file);
};
const handleSignupClick = () => {
onClose();
if (onSignup) {
onSignup();
}
};
const defaultTab = 'nostr' in window ? 'extension' : 'key';
return (_jsx(Dialog, { open: isOpen, onOpenChange: onClose, children: _jsxs(DialogContent, { className: cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl overflow-y-scroll"), children: [_jsx(DialogHeader, { className: cn('px-6 pt-6 pb-1 relative'), children: _jsx(DialogDescription, { className: "text-center", children: "Sign up or log in to continue" }) }), _jsxs("div", { className: 'px-6 pt-2 pb-4 space-y-4 overflow-y-auto flex-1', children: [_jsx("div", { className: 'relative p-4 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 border border-blue-200 dark:border-blue-800 overflow-hidden', children: _jsxs("div", { className: 'relative z-10 text-center space-y-3', children: [_jsxs("div", { className: 'flex justify-center items-center gap-2 mb-2', children: [_jsx(Sparkles, { className: 'w-5 h-5 text-blue-600' }), _jsx("span", { className: 'font-semibold text-blue-800 dark:text-blue-200', children: "New to Nostr?" })] }), _jsx("p", { className: 'text-sm text-blue-700 dark:text-blue-300', children: "Create a new account to get started. It's free and open." }), _jsxs(Button, { onClick: handleSignupClick, className: 'w-full rounded-full py-3 text-base font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg border-0', children: [_jsx(UserPlus, { className: 'w-4 h-4 mr-2' }), _jsx("span", { children: "Sign Up" })] })] }) }), _jsxs("div", { className: 'relative', children: [_jsx("div", { className: 'absolute inset-0 flex items-center', children: _jsx("div", { className: 'w-full border-t border-gray-300 dark:border-gray-600' }) }), _jsx("div", { className: 'relative flex justify-center text-sm', children: _jsx("span", { className: 'px-3 bg-background text-muted-foreground', children: _jsx("span", { children: "Or log in" }) }) })] }), _jsxs(Tabs, { defaultValue: defaultTab, className: "w-full", children: [_jsxs(TabsList, { className: "grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4", children: [_jsxs(TabsTrigger, { value: "extension", className: "flex items-center gap-2", children: [_jsx(Shield, { className: "w-4 h-4" }), _jsx("span", { children: "Extension" })] }), _jsxs(TabsTrigger, { value: "key", className: "flex items-center gap-2", children: [_jsx(KeyRound, { className: "w-4 h-4" }), _jsx("span", { children: "Key" })] }), _jsxs(TabsTrigger, { value: "bunker", className: "flex items-center gap-2", children: [_jsx(Cloud, { className: "w-4 h-4" }), _jsx("span", { children: "Bunker" })] })] }), _jsxs(TabsContent, { value: 'extension', className: 'space-y-3 bg-muted', children: [errors.extension && (_jsxs(Alert, { variant: "destructive", children: [_jsx(AlertTriangle, { className: "h-4 w-4" }), _jsx(AlertDescription, { children: errors.extension })] })), _jsxs("div", { className: 'text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800', children: [_jsx(Shield, { className: 'w-12 h-12 mx-auto mb-3 text-primary' }), _jsx("p", { className: 'text-sm text-gray-600 dark:text-gray-300 mb-4', children: "Login with one click using the browser extension" }), _jsx("div", { className: "flex justify-center", children: _jsx(Button, { className: 'w-full rounded-full py-4', onClick: handleExtensionLogin, disabled: isLoading, children: isLoading ? 'Logging in...' : 'Login with Extension' }) })] })] }), _jsx(TabsContent, { value: 'key', className: 'space-y-4', children: _jsxs("div", { className: 'space-y-4', children: [_jsxs("div", { className: 'space-y-2', children: [_jsx("label", { htmlFor: 'nsec', className: 'text-sm font-medium', children: "Secret Key (nsec)" }), _jsx(Input, { id: 'nsec', type: "password", value: nsec, onChange: (e) => {
setNsec(e.target.value);
if (errors.nsec)
setErrors(prev => ({ ...prev, nsec: undefined }));
}, className: `rounded-lg ${errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''}`, placeholder: 'nsec1...', autoComplete: "off" }), errors.nsec && (_jsx("p", { className: "text-sm text-red-500", children: errors.nsec }))] }), _jsx(Button, { className: 'w-full rounded-full py-3', onClick: handleKeyLogin, disabled: isLoading || !nsec.trim(), children: isLoading ? 'Verifying...' : 'Log In' }), _jsxs("div", { className: 'relative', children: [_jsx("div", { className: 'absolute inset-0 flex items-center', children: _jsx("div", { className: 'w-full border-t border-muted' }) }), _jsx("div", { className: 'relative flex justify-center text-xs', children: _jsx("span", { className: 'px-2 bg-background text-muted-foreground', children: "or" }) })] }), _jsxs("div", { className: 'text-center', children: [_jsx("input", { type: 'file', accept: '.txt', className: 'hidden', ref: fileInputRef, onChange: handleFileUpload }), _jsxs(Button, { variant: 'outline', className: 'w-full', onClick: () => fileInputRef.current?.click(), disabled: isLoading || isFileLoading, children: [_jsx(Upload, { className: 'w-4 h-4 mr-2' }), isFileLoading ? 'Reading File...' : 'Upload Your Key File'] }), errors.file && (_jsx("p", { className: "text-sm text-red-500 mt-2", children: errors.file }))] })] }) }), _jsxs(TabsContent, { value: 'bunker', className: 'space-y-3 bg-muted', children: [_jsxs("div", { className: 'space-y-2', children: [_jsx("label", { htmlFor: 'bunkerUri', className: 'text-sm font-medium text-gray-700 dark:text-gray-400', children: "Bunker URI" }), _jsx(Input, { id: 'bunkerUri', value: bunkerUri, onChange: (e) => {
setBunkerUri(e.target.value);
if (errors.bunker)
setErrors(prev => ({ ...prev, bunker: undefined }));
}, className: `rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${errors.bunker ? 'border-red-500' : ''}`, placeholder: 'bunker://', autoComplete: "off" }), errors.bunker && (_jsx("p", { className: "text-sm text-red-500", children: errors.bunker }))] }), _jsx("div", { className: "flex justify-center", children: _jsx(Button, { className: 'w-full rounded-full py-4', onClick: handleBunkerLogin, disabled: isLoading || !bunkerUri.trim(), children: isLoading ? 'Connecting...' : 'Login with Bunker' }) })] })] })] })] }) }));
};
export default LoginDialog;
+253 -96
View File
@@ -1,19 +1,15 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import 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';
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';
interface LoginDialogProps {
isOpen: boolean;
@@ -22,54 +18,124 @@ 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();
const handleExtensionLogin = () => {
// 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.');
}
login.extension();
await login.extension();
onLogin();
onClose();
} catch (error) {
} catch (e: unknown) {
const error = e as Error;
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: 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()) return;
setIsLoading(true);
try {
login.nsec(nsec);
onLogin();
onClose();
} catch (error) {
console.error('Nsec login failed:', error);
} finally {
setIsLoading(false);
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 = () => {
if (!bunkerUri.trim() || !bunkerUri.startsWith('bunker://')) return;
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 {
login.bunker(bunkerUri);
await login.bunker(bunkerUri);
onLogin();
onClose();
} catch (error) {
console.error('Bunker login failed:', error);
// Clear the URI from memory
setBunkerUri('');
} catch {
setErrors(prev => ({
...prev,
bunker: 'Failed to connect to bunker. Please check the URI.'
}));
} finally {
setIsLoading(false);
}
@@ -79,10 +145,27 @@ 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;
setNsec(content.trim());
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);
};
@@ -94,57 +177,139 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
}
};
const defaultTab = 'nostr' in window ? 'extension' : 'key';
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className='sm:max-w-md p-0 overflow-hidden rounded-2xl'>
<DialogHeader className='px-6 pt-6 pb-0 relative'>
<DialogTitle className='text-xl font-semibold text-center'>Log in</DialogTitle>
<DialogDescription className='text-center text-muted-foreground mt-2'>
Access your account securely with your preferred method
</DialogDescription>
<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>
</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>
<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>
{/* 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>
</TabsList>
<TabsContent value='extension' className='space-y-4'>
<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>
)}
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'>
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' />
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
Login with one click using the browser extension
</p>
<Button
className='w-full rounded-full py-6'
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
</div>
</TabsContent>
<TabsContent value='key' className='space-y-4'>
<div className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='nsec' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Enter your nsec
<label htmlFor='nsec' className='text-sm font-medium'>
Secret Key (nsec)
</label>
<Input
id='nsec'
type="password"
value={nsec}
onChange={(e) => setNsec(e.target.value)}
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary'
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 && (
<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'
@@ -154,25 +319,21 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
/>
<Button
variant='outline'
className='w-full dark:border-gray-700 dark:bg-gray-800 dark:hover:bg-gray-700'
className='w-full'
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
>
<Upload className='w-4 h-4 mr-2' />
Upload Nsec File
{isFileLoading ? 'Reading File...' : 'Upload Your Key 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-4'>
<TabsContent value='bunker' className='space-y-3 bg-muted'>
<div className='space-y-2'>
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Bunker URI
@@ -180,40 +341,36 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
<Input
id='bunkerUri'
value={bunkerUri}
onChange={(e) => setBunkerUri(e.target.value)}
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary'
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"
/>
{bunkerUri && !bunkerUri.startsWith('bunker://') && (
<p className='text-red-500 text-xs'>URI must start with bunker://</p>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
)}
</div>
<Button
className='w-full rounded-full py-6'
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim() || !bunkerUri.startsWith('bunker://')}
>
{isLoading ? 'Connecting...' : 'Login with Bunker'}
</Button>
<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>
</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
@@ -0,0 +1,266 @@
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { useState, useEffect, useRef } from 'react';
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, CheckCircle, Upload, Globe } from 'lucide-react';
import { Button } from '@/components/ui/button.js';
import { Input } from '@/components/ui/input.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog.js";
import { Card, CardContent } from '@/components/ui/card.js';
import { toast } from '@/hooks/useToast.js';
import { useLoginActions } from '@/hooks/useLoginActions.js';
import { useNostrPublish } from '@/hooks/useNostrPublish.js';
import { useUploadFile } from '@/hooks/useUploadFile.js';
import { generateSecretKey, nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils.js';
const sanitizeFilename = (filename) => {
return filename.replace(/[^a-z0-9_.-]/gi, '_');
};
const SignupDialog = ({ isOpen, onClose, onComplete }) => {
const [step, setStep] = useState('welcome');
const [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [showSparkles, setShowSparkles] = useState(false);
const [keySecured, setKeySecured] = useState('none');
const [profileData, setProfileData] = useState({
name: '',
about: '',
picture: ''
});
const login = useLoginActions();
const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const avatarFileInputRef = useRef(null);
// Generate a proper nsec key using nostr-tools
const generateKey = () => {
setIsLoading(true);
setShowSparkles(true);
// Add a dramatic pause for the key generation effect
setTimeout(() => {
try {
// Generate a new secret key
const sk = generateSecretKey();
// Convert to nsec format
setNsec(nip19.nsecEncode(sk));
setStep('download');
toast({
title: 'Your Secret Key is Ready!',
description: 'A new secret key has been generated for you.',
});
}
catch {
toast({
title: 'Error',
description: 'Failed to generate key. Please try again.',
variant: 'destructive',
});
}
finally {
setIsLoading(false);
setShowSparkles(false);
}
}, 2000);
};
const downloadKey = () => {
try {
// Create a blob with the key text
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
// Sanitize filename
const filename = sanitizeFilename('nostr-nsec-key.txt');
// Create a temporary link element and trigger download
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
// Clean up immediately
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
// Mark as secured
setKeySecured('downloaded');
toast({
title: 'Secret Key Saved!',
description: 'Your key has been safely stored.',
});
}
catch {
toast({
title: 'Download failed',
description: 'Could not download the key file. Please copy it manually.',
variant: 'destructive',
});
}
};
const finishKeySetup = () => {
try {
login.nsec(nsec);
setStep('profile');
}
catch {
toast({
title: 'Login Failed',
description: 'Failed to login with the generated key. Please try again.',
variant: 'destructive',
});
}
};
const handleAvatarUpload = async (e) => {
const file = e.target.files?.[0];
if (!file)
return;
// Reset file input
e.target.value = '';
// Validate file type
if (!file.type.startsWith('image/')) {
toast({
title: 'Invalid file type',
description: 'Please select an image file for your avatar.',
variant: 'destructive',
});
return;
}
// Validate file size (max 5MB)
if (file.size > 5 * 1024 * 1024) {
toast({
title: 'File too large',
description: 'Avatar image must be smaller than 5MB.',
variant: 'destructive',
});
return;
}
try {
const tags = await uploadFile(file);
// Get the URL from the first tag
const url = tags[0]?.[1];
if (url) {
setProfileData(prev => ({ ...prev, picture: url }));
toast({
title: 'Avatar uploaded!',
description: 'Your avatar has been uploaded successfully.',
});
}
}
catch {
toast({
title: 'Upload failed',
description: 'Failed to upload avatar. Please try again.',
variant: 'destructive',
});
}
};
const finishSignup = async (skipProfile = false) => {
// Mark signup completion time for fallback welcome modal
localStorage.setItem('signup_completed', Date.now().toString());
try {
// Publish profile if user provided information
if (!skipProfile && (profileData.name || profileData.about || profileData.picture)) {
const metadata = {};
if (profileData.name)
metadata.name = profileData.name;
if (profileData.about)
metadata.about = profileData.about;
if (profileData.picture)
metadata.picture = profileData.picture;
await publishEvent({
kind: 0,
content: JSON.stringify(metadata),
});
toast({
title: 'Profile Created!',
description: 'Your profile has been set up.',
});
}
// Close signup and show welcome modal
onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
}
else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
}
}
catch {
toast({
title: 'Profile Setup Failed',
description: 'Your account was created but profile setup failed. You can update it later.',
variant: 'destructive',
});
// Still proceed to completion even if profile failed
onClose();
if (onComplete) {
// Add a longer delay to ensure login state has fully propagated
setTimeout(() => {
onComplete();
}, 600);
}
else {
// Fallback for when used without onComplete
setStep('done');
setTimeout(() => {
onClose();
toast({
title: 'Welcome!',
description: 'Your account is ready.',
});
}, 3000);
}
}
};
const getTitle = () => {
if (step === 'welcome')
return (_jsx("span", { className: "flex items-center justify-center gap-2", children: "Create Your Account" }));
if (step === 'generate')
return (_jsx("span", { className: "flex items-center justify-center gap-2", children: "Generating Your Key" }));
if (step === 'download')
return (_jsx("span", { className: "flex items-center justify-center gap-2", children: "Secret Key" }));
if (step === 'profile')
return (_jsx("span", { className: "flex items-center justify-center gap-2", children: "Create Your Profile" }));
return (_jsx("span", { className: "flex items-center justify-center gap-2", children: "Welcome!" }));
};
// Reset state when dialog opens
useEffect(() => {
if (isOpen) {
setStep('welcome');
setIsLoading(false);
setNsec('');
setShowSparkles(false);
setKeySecured('none');
setProfileData({ name: '', about: '', picture: '' });
}
}, [isOpen]);
// Add sparkle animation effect
useEffect(() => {
if (showSparkles) {
const interval = setInterval(() => {
// This will trigger re-renders for sparkle animation
}, 100);
return () => clearInterval(interval);
}
}, [showSparkles]);
return (_jsx(Dialog, { open: isOpen, onOpenChange: onClose, children: _jsxs(DialogContent, { className: cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl flex flex-col"), children: [_jsx(DialogHeader, { className: cn('px-6 pt-6 pb-1 relative flex-shrink-0'), children: _jsx(DialogTitle, { className: cn('font-semibold text-center text-lg'), children: getTitle() }) }), _jsxs("div", { className: 'px-6 pt-2 pb-4 space-y-4 overflow-y-scroll flex-1', children: [step === 'welcome' && (_jsxs("div", { className: 'text-center space-y-4', children: [_jsxs("div", { className: 'relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50', children: [_jsxs("div", { className: 'flex justify-center items-center space-x-4 mb-3', children: [_jsxs("div", { className: 'relative', children: [_jsx(UserPlus, { className: 'w-12 h-12 text-blue-600' }), _jsx(Sparkles, { className: 'w-4 h-4 text-yellow-500 absolute -top-1 -right-1 animate-pulse' })] }), _jsx(Globe, { className: 'w-16 h-16 text-blue-700 animate-spin-slow' }), _jsxs("div", { className: 'relative', children: [_jsx(FileText, { className: 'w-12 h-12 text-blue-600' }), _jsx(Sparkles, { className: 'w-4 h-4 text-yellow-500 absolute -top-1 -left-1 animate-pulse', style: { animationDelay: '0.3s' } })] })] }), _jsxs("div", { className: 'grid grid-cols-1 gap-2 text-sm', children: [_jsxs("div", { className: 'flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300', children: [_jsx(Shield, { className: 'w-4 h-4' }), "Decentralized and censorship-resistant"] }), _jsxs("div", { className: 'flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300', children: [_jsx(User, { className: 'w-4 h-4' }), "You are in control of your data"] }), _jsxs("div", { className: 'flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300', children: [_jsx(Globe, { className: 'w-4 h-4' }), "Join a global network"] })] })] }), _jsx("div", { className: 'space-y-3', children: _jsxs(Button, { className: 'w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg', onClick: () => setStep('generate'), children: [_jsx(LogIn, { className: 'w-5 h-5 mr-2' }), "Get Started"] }) })] })), step === 'generate' && (_jsxs("div", { className: 'text-center space-y-4', children: [_jsxs("div", { className: 'relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-purple-100 dark:from-blue-950/50 dark:to-purple-950/50 overflow-hidden', children: [showSparkles && (_jsx("div", { className: 'absolute inset-0', children: [...Array(12)].map((_, i) => (_jsx(Sparkles, { className: `absolute w-4 h-4 text-yellow-400 animate-ping`, style: {
left: `${Math.random() * 80 + 10}%`,
top: `${Math.random() * 80 + 10}%`,
animationDelay: `${Math.random() * 2}s`
} }, i))) })), _jsx("div", { className: 'relative z-10', children: isLoading ? (_jsxs("div", { className: 'space-y-3', children: [_jsxs("div", { className: 'relative', children: [_jsx(Key, { className: 'w-20 h-20 text-primary mx-auto animate-pulse' }), _jsx("div", { className: 'absolute inset-0 flex items-center justify-center', children: _jsx("div", { className: 'w-24 h-24 border-4 border-yellow-400 border-t-transparent rounded-full animate-spin' }) })] }), _jsxs("div", { className: 'space-y-2', children: [_jsxs("p", { className: 'text-lg font-semibold text-primary flex items-center justify-center gap-2', children: [_jsx(Sparkles, { className: 'w-5 h-5' }), "Generating your secret key..."] }), _jsx("p", { className: 'text-sm text-muted-foreground', children: "Creating your secure key" })] })] })) : (_jsxs("div", { className: 'space-y-3', children: [_jsx(Key, { className: 'w-20 h-20 text-primary mx-auto' }), _jsxs("div", { className: 'space-y-2', children: [_jsx("p", { className: 'text-lg font-semibold', children: "Ready to generate your secret key?" }), _jsx("p", { className: 'text-sm text-muted-foreground px-5', children: "This key will be your password to access applications within the Nostr network." })] })] })) })] }), !isLoading && (_jsxs(Button, { className: 'w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-purple-600 to-blue-600 hover:from-purple-700 hover:to-blue-700 transform transition-all duration-200 hover:scale-105 shadow-lg', onClick: generateKey, disabled: isLoading, children: [_jsx(Sparkles, { className: 'w-5 h-5 mr-2' }), "Generate My Secret Key"] }))] })), step === 'download' && (_jsxs("div", { className: 'text-center space-y-4', children: [_jsxs("div", { className: 'relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden', children: [_jsxs("div", { className: 'absolute inset-0 pointer-events-none', children: [_jsx(Sparkles, { className: 'absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse', style: { animationDelay: '0s' } }), _jsx(Sparkles, { className: 'absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse', style: { animationDelay: '0.5s' } }), _jsx(Sparkles, { className: 'absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse', style: { animationDelay: '1s' } }), _jsx(Sparkles, { className: 'absolute bottom-3 right-4 w-3 h-3 text-yellow-500 animate-pulse', style: { animationDelay: '1.5s' } })] }), _jsx("div", { className: 'relative z-10 flex justify-center items-center mb-3', children: _jsxs("div", { className: 'relative', children: [_jsx("div", { className: 'w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg animate-pulse', children: _jsx(Key, { className: 'w-8 h-8 text-indigo-800' }) }), _jsx("div", { className: 'absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce', children: _jsx(Sparkles, { className: 'w-3 h-3 text-white' }) })] }) }), _jsxs("div", { className: 'relative z-10 space-y-2', children: [_jsx("p", { className: 'text-base font-semibold', children: "Your secret key has been generated!" }), _jsx("div", { className: 'relative mx-auto max-w-sm', children: _jsxs("div", { className: 'p-3 bg-gradient-to-r from-amber-100 via-yellow-50 to-amber-100 dark:from-amber-950/40 dark:via-yellow-950/20 dark:to-amber-950/40 rounded-lg border-2 border-amber-300 dark:border-amber-700 shadow-md', children: [_jsxs("div", { className: 'flex items-center gap-2 mb-1', children: [_jsx(FileText, { className: 'w-3 h-3 text-amber-700' }), _jsx("span", { className: 'text-xs font-bold text-amber-800 dark:text-amber-200', children: "Important Warning" })] }), _jsx("p", { className: 'text-xs text-red-700 dark:text-amber-300 italic', children: "This key is your primary and only means of accessing your account. Store it safely and securely." })] }) })] })] }), _jsxs("div", { className: 'space-y-3', children: [_jsx("div", { className: 'grid grid-cols-1 gap-2', children: _jsx(Card, { className: `cursor-pointer transition-all duration-200 ${keySecured === 'downloaded'
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20'}`, children: _jsx(CardContent, { className: 'p-3', children: _jsx(Button, { variant: "ghost", className: 'w-full h-auto p-0 justify-start hover:bg-transparent', onClick: downloadKey, children: _jsxs("div", { className: 'flex items-center gap-3 w-full', children: [_jsx("div", { className: `p-1.5 rounded-lg ${keySecured === 'downloaded'
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'}`, children: keySecured === 'downloaded' ? (_jsx(CheckCircle, { className: 'w-4 h-4 text-green-600' })) : (_jsx(Download, { className: 'w-4 h-4 text-primary' })) }), _jsxs("div", { className: 'flex-1 text-left', children: [_jsx("div", { className: 'font-medium text-sm', children: "Download as File" }), _jsx("div", { className: 'text-xs text-muted-foreground', children: "Save as nostr-nsec-key.txt file" })] }), keySecured === 'downloaded' && (_jsx("div", { className: 'text-xs font-medium text-green-600', children: "\u2713 Downloaded" }))] }) }) }) }) }), _jsxs(Button, { className: `w-full rounded-full py-4 text-base font-semibold transform transition-all duration-200 shadow-lg ${keySecured === 'downloaded'
? 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 dark:from-blue-950/50 dark:to-purple-950/50 hover:scale-105'
: 'bg-gradient-to-r from-blue-600/60 to-indigo-600/60 text-muted cursor-not-allowed'}`, onClick: finishKeySetup, disabled: keySecured !== 'downloaded', children: [_jsx(LogIn, { className: 'w-4 h-4 mr-2 flex-shrink-0' }), _jsx("span", { className: "text-center leading-tight", children: keySecured === 'none' ? (_jsx(_Fragment, { children: "Please download your key first" })) : (_jsxs(_Fragment, { children: [_jsx("span", { className: "hidden sm:inline", children: "My Key is Safe - Continue" }), _jsx("span", { className: "sm:hidden", children: "Key Secured - Continue" })] })) })] })] })] })), step === 'profile' && (_jsxs("div", { className: 'text-center space-y-4', children: [_jsxs("div", { className: 'relative p-6 rounded-2xl bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-blue-950/50 dark:to-indigo-950/50 overflow-hidden', children: [_jsxs("div", { className: 'absolute inset-0 pointer-events-none', children: [_jsx(Sparkles, { className: 'absolute top-3 left-4 w-3 h-3 text-yellow-400 animate-pulse', style: { animationDelay: '0s' } }), _jsx(Sparkles, { className: 'absolute top-6 right-6 w-3 h-3 text-yellow-500 animate-pulse', style: { animationDelay: '0.5s' } }), _jsx(Sparkles, { className: 'absolute bottom-4 left-6 w-3 h-3 text-yellow-400 animate-pulse', style: { animationDelay: '1s' } })] }), _jsx("div", { className: 'relative z-10 flex justify-center items-center mb-3', children: _jsxs("div", { className: 'relative', children: [_jsx("div", { className: 'w-16 h-16 bg-gradient-to-br from-blue-200 to-indigo-300 rounded-full flex items-center justify-center shadow-lg', children: _jsx(User, { className: 'w-8 h-8 text-blue-800' }) }), _jsx("div", { className: 'absolute -top-1 -right-1 w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center animate-bounce', children: _jsx(Sparkles, { className: 'w-3 h-3 text-white' }) })] }) }), _jsxs("div", { className: 'relative z-10 space-y-2', children: [_jsx("p", { className: 'text-base font-semibold', children: "Almost there! Let's set up your profile" }), _jsx("p", { className: 'text-sm text-muted-foreground', children: "Your profile is your identity on Nostr." })] })] }), isPublishing && (_jsx("div", { className: 'relative p-4 rounded-xl bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-950/30 dark:to-indigo-950/30 border border-blue-200 dark:border-blue-800', children: _jsxs("div", { className: 'flex items-center justify-center gap-3', children: [_jsx("div", { className: 'w-5 h-5 border-2 border-blue-600 border-t-transparent rounded-full animate-spin' }), _jsx("span", { className: 'text-sm font-medium text-blue-700 dark:text-blue-300', children: "Publishing your profile..." })] }) })), _jsxs("div", { className: `space-y-4 text-left ${isPublishing ? 'opacity-50 pointer-events-none' : ''}`, children: [_jsxs("div", { className: 'space-y-2', children: [_jsx("label", { htmlFor: 'profile-name', className: 'text-sm font-medium', children: "Display Name" }), _jsx(Input, { id: 'profile-name', value: profileData.name, onChange: (e) => setProfileData(prev => ({ ...prev, name: e.target.value })), placeholder: 'Your name', className: 'rounded-lg', disabled: isPublishing })] }), _jsxs("div", { className: 'space-y-2', children: [_jsx("label", { htmlFor: 'profile-about', className: 'text-sm font-medium', children: "Bio" }), _jsx(Textarea, { id: 'profile-about', value: profileData.about, onChange: (e) => setProfileData(prev => ({ ...prev, about: e.target.value })), placeholder: 'Tell others about yourself...', className: 'rounded-lg resize-none', rows: 3, disabled: isPublishing })] }), _jsxs("div", { className: 'space-y-2', children: [_jsx("label", { htmlFor: 'profile-picture', className: 'text-sm font-medium', children: "Avatar" }), _jsxs("div", { className: 'flex gap-2', children: [_jsx(Input, { id: 'profile-picture', value: profileData.picture, onChange: (e) => setProfileData(prev => ({ ...prev, picture: e.target.value })), placeholder: 'https://example.com/your-avatar.jpg', className: 'rounded-lg flex-1', disabled: isPublishing }), _jsx("input", { type: 'file', accept: 'image/*', className: 'hidden', ref: avatarFileInputRef, onChange: handleAvatarUpload }), _jsx(Button, { type: 'button', variant: 'outline', size: 'icon', onClick: () => avatarFileInputRef.current?.click(), disabled: isUploading || isPublishing, className: 'rounded-lg shrink-0', title: 'Upload avatar image', children: isUploading ? (_jsx("div", { className: 'w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin' })) : (_jsx(Upload, { className: 'w-4 h-4' })) })] })] })] }), _jsxs("div", { className: 'space-y-3', children: [_jsx(Button, { className: 'w-full rounded-full py-4 text-base font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none', onClick Line truncated
};
export default SignupDialog;
+651 -110
View File
@@ -1,163 +1,704 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useState } from 'react';
import { Download, Key } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog.tsx';
import { toast } from '@/hooks/useToast.ts';
import { useLoginActions } from '@/hooks/useLoginActions';
import 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 { generateSecretKey, nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils.js';
interface SignupDialogProps {
isOpen: boolean;
onClose: () => void;
onComplete?: () => void;
}
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const [step, setStep] = useState<'generate' | 'download' | 'done'>('generate');
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 [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);
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);
}
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 = () => {
// Create a blob with the key text
const blob = new Blob([nsec], { type: 'text/plain' });
const url = globalThis.URL.createObjectURL(blob);
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 temporary link element and trigger download
const a = document.createElement('a');
a.href = url;
a.download = 'nsec.txt';
document.body.appendChild(a);
a.click();
// Sanitize filename
const filename = sanitizeFilename('nostr-nsec-key.txt');
// Clean up
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
// 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();
toast({
title: 'Key downloaded',
description: 'Your key has been downloaded. Keep it safe!',
});
// 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 finishSignup = () => {
login.nsec(nsec);
setStep('done');
onClose();
toast({
title: 'Account created',
description: 'You are now logged in.',
});
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: 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='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'}
<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()}
</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>
<div className='px-6 py-8 space-y-6'>
{step === 'generate' && (
<div className='text-center space-y-6'>
<div className='p-4 rounded-lg bg-gray-50 dark:bg-gray-800 flex items-center justify-center'>
<Key className='w-16 h-16 text-primary' />
{/* 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>
<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>
)}
{/* Generate Step - Enhanced with animations */}
{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>
{!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>
)}
</div>
)}
{/* Download Step - Whimsical and magical */}
{step === 'download' && (
<div className='space-y-6'>
<div className='p-4 rounded-lg border bg-gray-50 dark:bg-gray-800 overflow-auto'>
<code className='text-xs break-all'>{nsec}</code>
<div 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>
<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>
{/* 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>
<div className='flex flex-col space-y-3'>
{/* 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>
<Button
variant='outline'
className='w-full'
onClick={downloadKey}
className='w-full rounded-full py-3 disabled:opacity-50 disabled:cursor-not-allowed'
onClick={() => finishSignup(true)}
disabled={isPublishing || isUploading}
>
<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
{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'
)}
</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
@@ -0,0 +1,29 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor.js';
import { useComments } from '@/hooks/useComments.js';
import { CommentForm } from "./CommentForm.js";
import { NoteContent } from '@/components/NoteContent.js';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.js';
import { Button } from '@/components/ui/button.js';
import { Card, CardContent } from '@/components/ui/card.js';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible.js';
import { DropdownMenu, DropdownMenuTrigger } from '@/components/ui/dropdown-menu.js';
import { MessageSquare, ChevronDown, ChevronRight, MoreHorizontal } from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { genUserName } from '@/lib/genUserName.js';
export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }) {
const [showReplyForm, setShowReplyForm] = useState(false);
const [showReplies, setShowReplies] = useState(depth < 2); // Auto-expand first 2 levels
const author = useAuthor(comment.pubkey);
const { data: commentsData } = useComments(root, limit);
const metadata = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(comment.pubkey);
const timeAgo = formatDistanceToNow(new Date(comment.created_at * 1000), { addSuffix: true });
// Get direct replies to this comment
const replies = commentsData?.getDirectReplies(comment.id) || [];
const hasReplies = replies.length > 0;
return (_jsxs("div", { className: `space-y-3 ${depth > 0 ? 'ml-6 border-l-2 border-muted pl-4' : ''}`, children: [_jsx(Card, { className: "bg-card/50", children: _jsx(CardContent, { className: "p-4", children: _jsxs("div", { className: "space-y-3", children: [_jsx("div", { className: "flex items-start justify-between", children: _jsxs("div", { className: "flex items-center space-x-3", children: [_jsx(Link, { to: `/${nip19.npubEncode(comment.pubkey)}`, children: _jsxs(Avatar, { className: "h-8 w-8 hover:ring-2 hover:ring-primary/30 transition-all cursor-pointer", children: [_jsx(AvatarImage, { src: metadata?.picture }), _jsx(AvatarFallback, { className: "text-xs", children: displayName.charAt(0) })] }) }), _jsxs("div", { children: [_jsx(Link, { to: `/${nip19.npubEncode(comment.pubkey)}`, className: "font-medium text-sm hover:text-primary transition-colors", children: displayName }), _jsx("p", { className: "text-xs text-muted-foreground", children: timeAgo })] })] }) }), _jsx("div", { className: "text-sm", children: _jsx(NoteContent, { event: comment, className: "text-sm" }) }), _jsxs("div", { className: "flex items-center justify-between pt-2", children: [_jsxs("div", { className: "flex items-center space-x-2", children: [_jsxs(Button, { variant: "ghost", size: "sm", onClick: () => setShowReplyForm(!showReplyForm), className: "h-8 px-2 text-xs", children: [_jsx(MessageSquare, { className: "h-3 w-3 mr-1" }), "Reply"] }), hasReplies && (_jsx(Collapsible, { open: showReplies, onOpenChange: setShowReplies, children: _jsx(CollapsibleTrigger, { asChild: true, children: _jsxs(Button, { variant: "ghost", size: "sm", className: "h-8 px-2 text-xs", children: [showReplies ? (_jsx(ChevronDown, { className: "h-3 w-3 mr-1" })) : (_jsx(ChevronRight, { className: "h-3 w-3 mr-1" })), replies.length, " ", replies.length === 1 ? 'reply' : 'replies'] }) }) }))] }), _jsx(DropdownMenu, { children: _jsx(DropdownMenuTrigger, { asChild: true, children: _jsx(Button, { variant: "ghost", size: "sm", className: "h-8 px-2 text-xs", "aria-label": "Comment options", children: _jsx(MoreHorizontal, { className: "h-3 w-3" }) }) }) })] })] }) }) }), showReplyForm && (_jsx("div", { className: "ml-6", children: _jsx(CommentForm, { root: root, reply: comment, onSuccess: () => setShowReplyForm(false), placeholder: "Write a reply...", compact: true }) })), hasReplies && (_jsx(Collapsible, { open: showReplies, onOpenChange: setShowReplies, children: _jsx(CollapsibleContent, { className: "space-y-3", children: replies.map((reply) => (_jsx(Comment, { root: root, comment: reply, depth: depth + 1, maxDepth: maxDepth, limit: limit }, reply.id))) }) }))] }));
}
+153
View File
@@ -0,0 +1,153 @@
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
@@ -0,0 +1,29 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState } from 'react';
import { Button } from '@/components/ui/button.js';
import { Textarea } from '@/components/ui/textarea.js';
import { Card, CardContent } from '@/components/ui/card.js';
import { useCurrentUser } from '@/hooks/useCurrentUser.js';
import { usePostComment } from '@/hooks/usePostComment.js';
import { LoginArea } from '@/components/auth/LoginArea.js';
import { MessageSquare, Send } from 'lucide-react';
export function CommentForm({ root, reply, onSuccess, placeholder = "Write a comment...", compact = false }) {
const [content, setContent] = useState('');
const { user } = useCurrentUser();
const { mutate: postComment, isPending } = usePostComment();
const handleSubmit = (e) => {
e.preventDefault();
if (!content.trim() || !user)
return;
postComment({ content: content.trim(), root, reply }, {
onSuccess: () => {
setContent('');
onSuccess?.();
},
});
};
if (!user) {
return (_jsx(Card, { className: compact ? "border-dashed" : "", children: _jsx(CardContent, { className: compact ? "p-4" : "p-6", children: _jsxs("div", { className: "text-center space-y-4", children: [_jsxs("div", { className: "flex items-center justify-center space-x-2 text-muted-foreground", children: [_jsx(MessageSquare, { className: "h-5 w-5" }), _jsxs("span", { children: ["Sign in to ", reply ? 'reply' : 'comment'] })] }), _jsx(LoginArea, {})] }) }) }));
}
return (_jsx(Card, { className: compact ? "border-dashed" : "", children: _jsx(CardContent, { className: compact ? "p-4" : "p-6", children: _jsxs("form", { onSubmit: handleSubmit, className: "space-y-4", children: [_jsx(Textarea, { value: content, onChange: (e) => setContent(e.target.value), placeholder: placeholder, className: compact ? "min-h-[80px]" : "min-h-[100px]", disabled: isPending }), _jsxs("div", { className: "flex justify-between items-center", children: [_jsx("span", { className: "text-sm text-muted-foreground", children: reply ? 'Replying to comment' : 'Adding to the discussion' }), _jsxs(Button, { type: "submit", disabled: !content.trim() || isPending, size: compact ? "sm" : "default", children: [_jsx(Send, { className: "h-4 w-4 mr-2" }), isPending ? 'Posting...' : (reply ? 'Reply' : 'Comment')] })] })] }) }) }));
}
+90
View File
@@ -0,0 +1,90 @@
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>
);
}
@@ -0,0 +1,16 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useComments } from '@/hooks/useComments.js';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card.js';
import { Skeleton } from '@/components/ui/skeleton.js';
import { MessageSquare } from 'lucide-react';
import { cn } from '@/lib/utils.js';
import { CommentForm } from "./CommentForm.js";
import { Comment } from "./Comment.js";
export function CommentsSection({ root, title = "Comments", emptyStateMessage = "No comments yet", emptyStateSubtitle = "Be the first to share your thoughts!", className, limit = 500, }) {
const { data: commentsData, isLoading, error } = useComments(root, limit);
const comments = commentsData?.topLevelComments || [];
if (error) {
return (_jsx(Card, { className: "rounded-none sm:rounded-lg mx-0 sm:mx-0", children: _jsx(CardContent, { className: "px-2 py-6 sm:p-6", children: _jsxs("div", { className: "text-center text-muted-foreground", children: [_jsx(MessageSquare, { className: "h-8 w-8 mx-auto mb-2 opacity-50" }), _jsx("p", { children: "Failed to load comments" })] }) }) }));
}
return (_jsxs(Card, { className: cn("rounded-none sm:rounded-lg mx-0 sm:mx-0", className), children: [_jsx(CardHeader, { className: "px-2 pt-6 pb-4 sm:p-6", children: _jsxs(CardTitle, { className: "flex items-center space-x-2", children: [_jsx(MessageSquare, { className: "h-5 w-5" }), _jsx("span", { children: title }), !isLoading && (_jsxs("span", { className: "text-sm font-normal text-muted-foreground", children: ["(", comments.length, ")"] }))] }) }), _jsxs(CardContent, { className: "px-2 pb-6 pt-4 sm:p-6 sm:pt-0 space-y-6", children: [_jsx(CommentForm, { root: root }), isLoading ? (_jsx("div", { className: "space-y-4", children: [...Array(3)].map((_, i) => (_jsx(Card, { className: "bg-card/50", children: _jsx(CardContent, { className: "p-4", children: _jsxs("div", { className: "space-y-3", children: [_jsxs("div", { className: "flex items-center space-x-3", children: [_jsx(Skeleton, { className: "h-8 w-8 rounded-full" }), _jsxs("div", { className: "space-y-1", children: [_jsx(Skeleton, { className: "h-4 w-24" }), _jsx(Skeleton, { className: "h-3 w-16" })] })] }), _jsx(Skeleton, { className: "h-16 w-full" })] }) }) }, i))) })) : comments.length === 0 ? (_jsxs("div", { className: "text-center py-8 text-muted-foreground", children: [_jsx(MessageSquare, { className: "h-12 w-12 mx-auto mb-4 opacity-30" }), _jsx("p", { className: "text-lg font-medium mb-2", children: emptyStateMessage }), _jsx("p", { className: "text-sm", children: emptyStateSubtitle })] })) : (_jsx("div", { className: "space-y-4", children: comments.map((comment) => (_jsx(Comment, { root: root, comment: comment }, comment.id))) }))] })] }));
}
+100
View File
@@ -0,0 +1,100 @@
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
@@ -0,0 +1,13 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import * as AccordionPrimitive from "@radix-ui/react-accordion";
import { ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils.js";
const Accordion = AccordionPrimitive.Root;
const AccordionItem = React.forwardRef(({ className, ...props }, ref) => (_jsx(AccordionPrimitive.Item, { ref: ref, className: cn("border-b", className), ...props })));
AccordionItem.displayName = "AccordionItem";
const AccordionTrigger = React.forwardRef(({ className, children, ...props }, ref) => (_jsx(AccordionPrimitive.Header, { className: "flex", children: _jsxs(AccordionPrimitive.Trigger, { ref: ref, className: cn("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180", className), ...props, children: [children, _jsx(ChevronDown, { className: "h-4 w-4 shrink-0 transition-transform duration-200" })] }) })));
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;
const AccordionContent = React.forwardRef(({ className, children, ...props }, ref) => (_jsx(AccordionPrimitive.Content, { ref: ref, className: "overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down", ...props, children: _jsx("div", { className: cn("pb-4 pt-0", className), children: children }) })));
AccordionContent.displayName = AccordionPrimitive.Content.displayName;
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
+1 -1
View File
@@ -2,7 +2,7 @@ import * as React from "react"
import * as AccordionPrimitive from "@radix-ui/react-accordion"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const Accordion = AccordionPrimitive.Root
+26
View File
@@ -0,0 +1,26 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
import { cn } from "@/lib/utils.js";
import { buttonVariants } from "@/components/ui/button-variants.js";
const AlertDialog = AlertDialogPrimitive.Root;
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
const AlertDialogPortal = AlertDialogPrimitive.Portal;
const AlertDialogOverlay = React.forwardRef(({ className, ...props }, ref) => (_jsx(AlertDialogPrimitive.Overlay, { className: cn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", className), ...props, ref: ref })));
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
const AlertDialogContent = React.forwardRef(({ className, ...props }, ref) => (_jsxs(AlertDialogPortal, { children: [_jsx(AlertDialogOverlay, {}), _jsx(AlertDialogPrimitive.Content, { ref: ref, className: cn("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg", className), ...props })] })));
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
const AlertDialogHeader = ({ className, ...props }) => (_jsx("div", { className: cn("flex flex-col space-y-2 text-center sm:text-left", className), ...props }));
AlertDialogHeader.displayName = "AlertDialogHeader";
const AlertDialogFooter = ({ className, ...props }) => (_jsx("div", { className: cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className), ...props }));
AlertDialogFooter.displayName = "AlertDialogFooter";
const AlertDialogTitle = React.forwardRef(({ className, ...props }, ref) => (_jsx(AlertDialogPrimitive.Title, { ref: ref, className: cn("text-lg font-semibold", className), ...props })));
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
const AlertDialogDescription = React.forwardRef(({ className, ...props }, ref) => (_jsx(AlertDialogPrimitive.Description, { ref: ref, className: cn("text-sm text-muted-foreground", className), ...props })));
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName;
const AlertDialogAction = React.forwardRef(({ className, ...props }, ref) => (_jsx(AlertDialogPrimitive.Action, { ref: ref, className: cn(buttonVariants(), className), ...props })));
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
const AlertDialogCancel = React.forwardRef(({ className, ...props }, ref) => (_jsx(AlertDialogPrimitive.Cancel, { ref: ref, className: cn(buttonVariants({ variant: "outline" }), "mt-2 sm:mt-0", className), ...props })));
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
export { AlertDialog, AlertDialogPortal, AlertDialogOverlay, AlertDialogTrigger, AlertDialogContent, AlertDialogHeader, AlertDialogFooter, AlertDialogTitle, AlertDialogDescription, AlertDialogAction, AlertDialogCancel, };
+2 -2
View File
@@ -1,8 +1,8 @@
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button-variants"
import { cn } from "@/lib/utils.js"
import { buttonVariants } from "@/components/ui/button-variants.js"
const AlertDialog = AlertDialogPrimitive.Root
+22
View File
@@ -0,0 +1,22 @@
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from "react";
import { cva } from "class-variance-authority";
import { cn } from "@/lib/utils.js";
const alertVariants = cva("relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground", {
variants: {
variant: {
default: "bg-background text-foreground",
destructive: "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
});
const Alert = React.forwardRef(({ className, variant, ...props }, ref) => (_jsx("div", { ref: ref, role: "alert", className: cn(alertVariants({ variant }), className), ...props })));
Alert.displayName = "Alert";
const AlertTitle = React.forwardRef(({ className, ...props }, ref) => (_jsx("h5", { ref: ref, className: cn("mb-1 font-medium leading-none tracking-tight", className), ...props })));
AlertTitle.displayName = "AlertTitle";
const AlertDescription = React.forwardRef(({ className, ...props }, ref) => (_jsx("div", { ref: ref, className: cn("text-sm [&_p]:leading-relaxed", className), ...props })));
AlertDescription.displayName = "AlertDescription";
export { Alert, AlertTitle, AlertDescription };
+1 -1
View File
@@ -1,7 +1,7 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const alertVariants = cva(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
+3
View File
@@ -0,0 +1,3 @@
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio";
const AspectRatio = AspectRatioPrimitive.Root;
export { AspectRatio };
+11
View File
@@ -0,0 +1,11 @@
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from "react";
import * as AvatarPrimitive from "@radix-ui/react-avatar";
import { cn } from "@/lib/utils.js";
const Avatar = React.forwardRef(({ className, ...props }, ref) => (_jsx(AvatarPrimitive.Root, { ref: ref, className: cn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full", className), ...props })));
Avatar.displayName = AvatarPrimitive.Root.displayName;
const AvatarImage = React.forwardRef(({ className, ...props }, ref) => (_jsx(AvatarPrimitive.Image, { ref: ref, className: cn("aspect-square h-full w-full object-cover", className), ...props })));
AvatarImage.displayName = AvatarPrimitive.Image.displayName;
const AvatarFallback = React.forwardRef(({ className, ...props }, ref) => (_jsx(AvatarPrimitive.Fallback, { ref: ref, className: cn("flex h-full w-full items-center justify-center rounded-full bg-muted", className), ...props })));
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;
export { Avatar, AvatarImage, AvatarFallback };
+2 -2
View File
@@ -1,7 +1,7 @@
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
@@ -24,7 +24,7 @@ const AvatarImage = React.forwardRef<
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn("aspect-square h-full w-full", className)}
className={cn("aspect-square h-full w-full object-cover", className)}
{...props}
/>
))
+14
View File
@@ -0,0 +1,14 @@
import { cva } from "class-variance-authority";
export const badgeVariants = cva("inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", {
variants: {
variant: {
default: "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive: "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
});
+7
View File
@@ -0,0 +1,7 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { cn } from "@/lib/utils.js";
import { badgeVariants } from "./badge-variants.js";
function Badge({ className, variant, ...props }) {
return (_jsx("div", { className: cn(badgeVariants({ variant }), className), ...props }));
}
export { Badge };
+2 -2
View File
@@ -1,8 +1,8 @@
import * as React from "react"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { badgeVariants } from "./badge-variants"
import { cn } from "@/lib/utils.js"
import { badgeVariants } from "./badge-variants.js"
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
+23
View File
@@ -0,0 +1,23 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { ChevronRight, MoreHorizontal } from "lucide-react";
import { cn } from "@/lib/utils.js";
const Breadcrumb = React.forwardRef(({ ...props }, ref) => _jsx("nav", { ref: ref, "aria-label": "breadcrumb", ...props }));
Breadcrumb.displayName = "Breadcrumb";
const BreadcrumbList = React.forwardRef(({ className, ...props }, ref) => (_jsx("ol", { ref: ref, className: cn("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5", className), ...props })));
BreadcrumbList.displayName = "BreadcrumbList";
const BreadcrumbItem = React.forwardRef(({ className, ...props }, ref) => (_jsx("li", { ref: ref, className: cn("inline-flex items-center gap-1.5", className), ...props })));
BreadcrumbItem.displayName = "BreadcrumbItem";
const BreadcrumbLink = React.forwardRef(({ asChild, className, ...props }, ref) => {
const Comp = asChild ? Slot : "a";
return (_jsx(Comp, { ref: ref, className: cn("transition-colors hover:text-foreground", className), ...props }));
});
BreadcrumbLink.displayName = "BreadcrumbLink";
const BreadcrumbPage = React.forwardRef(({ className, ...props }, ref) => (_jsx("span", { ref: ref, role: "link", "aria-disabled": "true", "aria-current": "page", className: cn("font-normal text-foreground", className), ...props })));
BreadcrumbPage.displayName = "BreadcrumbPage";
const BreadcrumbSeparator = ({ children, className, ...props }) => (_jsx("li", { role: "presentation", "aria-hidden": "true", className: cn("[&>svg]:size-3.5", className), ...props, children: children ?? _jsx(ChevronRight, {}) }));
BreadcrumbSeparator.displayName = "BreadcrumbSeparator";
const BreadcrumbEllipsis = ({ className, ...props }) => (_jsxs("span", { role: "presentation", "aria-hidden": "true", className: cn("flex h-9 w-9 items-center justify-center", className), ...props, children: [_jsx(MoreHorizontal, { className: "h-4 w-4" }), _jsx("span", { className: "sr-only", children: "More" })] }));
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis";
export { Breadcrumb, BreadcrumbList, BreadcrumbItem, BreadcrumbLink, BreadcrumbPage, BreadcrumbSeparator, BreadcrumbEllipsis, };
+1 -1
View File
@@ -2,7 +2,7 @@ import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { ChevronRight, MoreHorizontal } from "lucide-react"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const Breadcrumb = React.forwardRef<
HTMLElement,
+23
View File
@@ -0,0 +1,23 @@
import { cva } from "class-variance-authority";
export const buttonVariants = cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", {
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
});
+11
View File
@@ -0,0 +1,11 @@
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cn } from "@/lib/utils.js";
import { buttonVariants } from "./button-variants.js";
const Button = React.forwardRef(({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (_jsx(Comp, { className: cn(buttonVariants({ variant, size, className })), ref: ref, ...props }));
});
Button.displayName = "Button";
export { Button };
+2 -2
View File
@@ -2,8 +2,8 @@ import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { buttonVariants } from "./button-variants"
import { cn } from "@/lib/utils.js"
import { buttonVariants } from "./button-variants.js"
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
+36
View File
@@ -0,0 +1,36 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { DayPicker } from "react-day-picker";
import { cn } from "@/lib/utils.js";
import { buttonVariants } from "@/components/ui/button-variants.js";
function Calendar({ className, classNames, showOutsideDays = true, ...props }) {
return (_jsx(DayPicker, { showOutsideDays: showOutsideDays, className: cn("p-3", className), classNames: {
months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
month: "space-y-4",
caption: "flex justify-center pt-1 relative items-center",
caption_label: "text-sm font-medium",
nav: "space-x-1 flex items-center",
nav_button: cn(buttonVariants({ variant: "outline" }), "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"),
nav_button_previous: "absolute left-1",
nav_button_next: "absolute right-1",
table: "w-full border-collapse space-y-1",
head_row: "flex",
head_cell: "text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]",
row: "flex w-full mt-2",
cell: "h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20",
day: cn(buttonVariants({ variant: "ghost" }), "h-9 w-9 p-0 font-normal aria-selected:opacity-100"),
day_range_end: "day-range-end",
day_selected: "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
day_today: "bg-accent text-accent-foreground",
day_outside: "day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",
day_disabled: "text-muted-foreground opacity-50",
day_range_middle: "aria-selected:bg-accent aria-selected:text-accent-foreground",
day_hidden: "invisible",
...classNames,
}, components: {
IconLeft: ({ ..._props }) => _jsx(ChevronLeft, { className: "h-4 w-4" }),
IconRight: ({ ..._props }) => _jsx(ChevronRight, { className: "h-4 w-4" }),
}, ...props }));
}
Calendar.displayName = "Calendar";
export { Calendar };
+2 -2
View File
@@ -2,8 +2,8 @@ import * as React from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { DayPicker } from "react-day-picker";
import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button-variants";
import { cn } from "@/lib/utils.js";
import { buttonVariants } from "@/components/ui/button-variants.js";
export type CalendarProps = React.ComponentProps<typeof DayPicker>;
+16
View File
@@ -0,0 +1,16 @@
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from "react";
import { cn } from "@/lib/utils.js";
const Card = React.forwardRef(({ className, ...props }, ref) => (_jsx("div", { ref: ref, className: cn("rounded-lg border bg-card text-card-foreground shadow-sm", className), ...props })));
Card.displayName = "Card";
const CardHeader = React.forwardRef(({ className, ...props }, ref) => (_jsx("div", { ref: ref, className: cn("flex flex-col space-y-1.5 p-6", className), ...props })));
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef(({ className, ...props }, ref) => (_jsx("h3", { ref: ref, className: cn("text-2xl font-semibold leading-none tracking-tight", className), ...props })));
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef(({ className, ...props }, ref) => (_jsx("p", { ref: ref, className: cn("text-sm text-muted-foreground", className), ...props })));
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef(({ className, ...props }, ref) => (_jsx("div", { ref: ref, className: cn("p-6 pt-0", className), ...props })));
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef(({ className, ...props }, ref) => (_jsx("div", { ref: ref, className: cn("flex items-center p-6 pt-0", className), ...props })));
CardFooter.displayName = "CardFooter";
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
+1 -1
View File
@@ -1,6 +1,6 @@
import * as React from "react"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const Card = React.forwardRef<
HTMLDivElement,
+98
View File
@@ -0,0 +1,98 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import useEmblaCarousel from "embla-carousel-react";
import { ArrowLeft, ArrowRight } from "lucide-react";
import { cn } from "@/lib/utils.js";
import { Button } from "@/components/ui/button.js";
const CarouselContext = React.createContext(null);
function useCarousel() {
const context = React.useContext(CarouselContext);
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />");
}
return context;
}
const Carousel = React.forwardRef(({ orientation = "horizontal", opts, setApi, plugins, className, children, ...props }, ref) => {
const [carouselRef, api] = useEmblaCarousel({
...opts,
axis: orientation === "horizontal" ? "x" : "y",
}, plugins);
const [canScrollPrev, setCanScrollPrev] = React.useState(false);
const [canScrollNext, setCanScrollNext] = React.useState(false);
const onSelect = React.useCallback((api) => {
if (!api) {
return;
}
setCanScrollPrev(api.canScrollPrev());
setCanScrollNext(api.canScrollNext());
}, []);
const scrollPrev = React.useCallback(() => {
api?.scrollPrev();
}, [api]);
const scrollNext = React.useCallback(() => {
api?.scrollNext();
}, [api]);
const handleKeyDown = React.useCallback((event) => {
if (event.key === "ArrowLeft") {
event.preventDefault();
scrollPrev();
}
else if (event.key === "ArrowRight") {
event.preventDefault();
scrollNext();
}
}, [scrollPrev, scrollNext]);
React.useEffect(() => {
if (!api || !setApi) {
return;
}
setApi(api);
}, [api, setApi]);
React.useEffect(() => {
if (!api) {
return;
}
onSelect(api);
api.on("reInit", onSelect);
api.on("select", onSelect);
return () => {
api?.off("select", onSelect);
};
}, [api, onSelect]);
return (_jsx(CarouselContext.Provider, { value: {
carouselRef,
api: api,
opts,
orientation: orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}, children: _jsx("div", { ref: ref, onKeyDownCapture: handleKeyDown, className: cn("relative", className), role: "region", "aria-roledescription": "carousel", ...props, children: children }) }));
});
Carousel.displayName = "Carousel";
const CarouselContent = React.forwardRef(({ className, ...props }, ref) => {
const { carouselRef, orientation } = useCarousel();
return (_jsx("div", { ref: carouselRef, className: "overflow-hidden", children: _jsx("div", { ref: ref, className: cn("flex", orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col", className), ...props }) }));
});
CarouselContent.displayName = "CarouselContent";
const CarouselItem = React.forwardRef(({ className, ...props }, ref) => {
const { orientation } = useCarousel();
return (_jsx("div", { ref: ref, role: "group", "aria-roledescription": "slide", className: cn("min-w-0 shrink-0 grow-0 basis-full", orientation === "horizontal" ? "pl-4" : "pt-4", className), ...props }));
});
CarouselItem.displayName = "CarouselItem";
const CarouselPrevious = React.forwardRef(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (_jsxs(Button, { ref: ref, variant: variant, size: size, className: cn("absolute h-8 w-8 rounded-full", orientation === "horizontal"
? "-left-12 top-1/2 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90", className), disabled: !canScrollPrev, onClick: scrollPrev, ...props, children: [_jsx(ArrowLeft, { className: "h-4 w-4" }), _jsx("span", { className: "sr-only", children: "Previous slide" })] }));
});
CarouselPrevious.displayName = "CarouselPrevious";
const CarouselNext = React.forwardRef(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (_jsxs(Button, { ref: ref, variant: variant, size: size, className: cn("absolute h-8 w-8 rounded-full", orientation === "horizontal"
? "-right-12 top-1/2 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90", className), disabled: !canScrollNext, onClick: scrollNext, ...props, children: [_jsx(ArrowRight, { className: "h-4 w-4" }), _jsx("span", { className: "sr-only", children: "Next slide" })] }));
});
CarouselNext.displayName = "CarouselNext";
export { Carousel, CarouselContent, CarouselItem, CarouselPrevious, CarouselNext, };
+2 -2
View File
@@ -4,8 +4,8 @@ import useEmblaCarousel, {
} from "embla-carousel-react"
import { ArrowLeft, ArrowRight } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils.js"
import { Button } from "@/components/ui/button.js"
type CarouselApi = UseEmblaCarouselType[1]
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
+130
View File
@@ -0,0 +1,130 @@
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import * as React from "react";
import * as RechartsPrimitive from "recharts";
import { cn } from "@/lib/utils.js";
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" };
const ChartContext = React.createContext(null);
function useChart() {
const context = React.useContext(ChartContext);
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />");
}
return context;
}
const ChartContainer = React.forwardRef(({ id, className, children, config, ...props }, ref) => {
const uniqueId = React.useId();
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`;
return (_jsx(ChartContext.Provider, { value: { config }, children: _jsxs("div", { "data-chart": chartId, ref: ref, className: cn("flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none", className), ...props, children: [_jsx(ChartStyle, { id: chartId, config: config }), _jsx(RechartsPrimitive.ResponsiveContainer, { children: children })] }) }));
});
ChartContainer.displayName = "Chart";
const ChartStyle = ({ id, config }) => {
const colorConfig = Object.entries(config).filter(([_, config]) => config.theme || config.color);
if (!colorConfig.length) {
return null;
}
return (_jsx("style", { dangerouslySetInnerHTML: {
__html: Object.entries(THEMES)
.map(([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color = itemConfig.theme?.[theme] ||
itemConfig.color;
return color ? ` --color-${key}: ${color};` : null;
})
.join("\n")}
}
`)
.join("\n"),
} }));
};
const ChartTooltip = RechartsPrimitive.Tooltip;
const ChartTooltipContent = React.forwardRef(({ active, payload, className, indicator = "dot", hideLabel = false, hideIndicator = false, label, labelFormatter, labelClassName, formatter, color, nameKey, labelKey, }, ref) => {
const { config } = useChart();
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null;
}
const [item] = payload;
const key = `${labelKey || item.dataKey || item.name || "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const value = !labelKey && typeof label === "string"
? config[label]?.label || label
: itemConfig?.label;
if (labelFormatter) {
return (_jsx("div", { className: cn("font-medium", labelClassName), children: labelFormatter(value, payload) }));
}
if (!value) {
return null;
}
return _jsx("div", { className: cn("font-medium", labelClassName), children: value });
}, [
label,
labelFormatter,
payload,
hideLabel,
labelClassName,
config,
labelKey,
]);
if (!active || !payload?.length) {
return null;
}
const nestLabel = payload.length === 1 && indicator !== "dot";
return (_jsxs("div", { ref: ref, className: cn("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl", className), children: [!nestLabel ? tooltipLabel : null, _jsx("div", { className: "grid gap-1.5", children: payload.map((item, index) => {
const key = `${nameKey || item.name || item.dataKey || "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const indicatorColor = color || item.payload.fill || item.color;
return (_jsx("div", { className: cn("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground", indicator === "dot" && "items-center"), children: formatter && item?.value !== undefined && item.name ? (formatter(item.value, item.name, item, index, item.payload)) : (_jsxs(_Fragment, { children: [itemConfig?.icon ? (_jsx(itemConfig.icon, {})) : (!hideIndicator && (_jsx("div", { className: cn("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]", {
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent": indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
}), style: {
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
} }))), _jsxs("div", { className: cn("flex flex-1 justify-between leading-none", nestLabel ? "items-end" : "items-center"), children: [_jsxs("div", { className: "grid gap-1.5", children: [nestLabel ? tooltipLabel : null, _jsx("span", { className: "text-muted-foreground", children: itemConfig?.label || item.name })] }), item.value && (_jsx("span", { className: "font-mono font-medium tabular-nums text-foreground", children: item.value.toLocaleString() }))] })] })) }, item.dataKey));
}) })] }));
});
ChartTooltipContent.displayName = "ChartTooltip";
const ChartLegend = RechartsPrimitive.Legend;
const ChartLegendContent = React.forwardRef(({ className, hideIcon = false, payload, verticalAlign = "bottom", nameKey }, ref) => {
const { config } = useChart();
if (!payload?.length) {
return null;
}
return (_jsx("div", { ref: ref, className: cn("flex items-center justify-center gap-4", verticalAlign === "top" ? "pb-3" : "pt-3", className), children: payload.map((item) => {
const key = `${nameKey || item.dataKey || "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
return (_jsxs("div", { className: cn("flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"), children: [itemConfig?.icon && !hideIcon ? (_jsx(itemConfig.icon, {})) : (_jsx("div", { className: "h-2 w-2 shrink-0 rounded-[2px]", style: {
backgroundColor: item.color,
} })), itemConfig?.label] }, item.value));
}) }));
});
ChartLegendContent.displayName = "ChartLegend";
// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(config, payload, key) {
if (typeof payload !== "object" || payload === null) {
return undefined;
}
const payloadPayload = "payload" in payload &&
typeof payload.payload === "object" &&
payload.payload !== null
? payload.payload
: undefined;
let configLabelKey = key;
if (key in payload &&
typeof payload[key] === "string") {
configLabelKey = payload[key];
}
else if (payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key] === "string") {
configLabelKey = payloadPayload[key];
}
return configLabelKey in config
? config[configLabelKey]
: config[key];
}
export { ChartContainer, ChartTooltip, ChartTooltipContent, ChartLegend, ChartLegendContent, ChartStyle, };
+1 -1
View File
@@ -1,7 +1,7 @@
import * as React from "react"
import * as RechartsPrimitive from "recharts"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const
+8
View File
@@ -0,0 +1,8 @@
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { Check } from "lucide-react";
import { cn } from "@/lib/utils.js";
const Checkbox = React.forwardRef(({ className, ...props }, ref) => (_jsx(CheckboxPrimitive.Root, { ref: ref, className: cn("peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground", className), ...props, children: _jsx(CheckboxPrimitive.Indicator, { className: cn("flex items-center justify-center text-current"), children: _jsx(Check, { className: "h-4 w-4" }) }) })));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };
+1 -1
View File
@@ -2,7 +2,7 @@ import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { Check } from "lucide-react"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
+5
View File
@@ -0,0 +1,5 @@
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible";
const Collapsible = CollapsiblePrimitive.Root;
const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger;
const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent;
export { Collapsible, CollapsibleTrigger, CollapsibleContent };
+28
View File
@@ -0,0 +1,28 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Command as CommandPrimitive } from "cmdk";
import { Search } from "lucide-react";
import { cn } from "@/lib/utils.js";
import { Dialog, DialogContent } from "@/components/ui/dialog.js";
const Command = React.forwardRef(({ className, ...props }, ref) => (_jsx(CommandPrimitive, { ref: ref, className: cn("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground", className), ...props })));
Command.displayName = CommandPrimitive.displayName;
const CommandDialog = ({ children, ...props }) => {
return (_jsx(Dialog, { ...props, children: _jsx(DialogContent, { className: "overflow-hidden p-0 shadow-lg", children: _jsx(Command, { className: "[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5", children: children }) }) }));
};
const CommandInput = React.forwardRef(({ className, ...props }, ref) => (_jsxs("div", { className: "flex items-center border-b px-3", "cmdk-input-wrapper": "", children: [_jsx(Search, { className: "mr-2 h-4 w-4 shrink-0 opacity-50" }), _jsx(CommandPrimitive.Input, { ref: ref, className: cn("flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50", className), ...props })] })));
CommandInput.displayName = CommandPrimitive.Input.displayName;
const CommandList = React.forwardRef(({ className, ...props }, ref) => (_jsx(CommandPrimitive.List, { ref: ref, className: cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className), ...props })));
CommandList.displayName = CommandPrimitive.List.displayName;
const CommandEmpty = React.forwardRef((props, ref) => (_jsx(CommandPrimitive.Empty, { ref: ref, className: "py-6 text-center text-sm", ...props })));
CommandEmpty.displayName = CommandPrimitive.Empty.displayName;
const CommandGroup = React.forwardRef(({ className, ...props }, ref) => (_jsx(CommandPrimitive.Group, { ref: ref, className: cn("overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground", className), ...props })));
CommandGroup.displayName = CommandPrimitive.Group.displayName;
const CommandSeparator = React.forwardRef(({ className, ...props }, ref) => (_jsx(CommandPrimitive.Separator, { ref: ref, className: cn("-mx-1 h-px bg-border", className), ...props })));
CommandSeparator.displayName = CommandPrimitive.Separator.displayName;
const CommandItem = React.forwardRef(({ className, ...props }, ref) => (_jsx(CommandPrimitive.Item, { ref: ref, className: cn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50", className), ...props })));
CommandItem.displayName = CommandPrimitive.Item.displayName;
const CommandShortcut = ({ className, ...props }) => {
return (_jsx("span", { className: cn("ml-auto text-xs tracking-widest text-muted-foreground", className), ...props }));
};
CommandShortcut.displayName = "CommandShortcut";
export { Command, CommandDialog, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandShortcut, CommandSeparator, };
+2 -2
View File
@@ -3,8 +3,8 @@ import { type DialogProps } from "@radix-ui/react-dialog"
import { Command as CommandPrimitive } from "cmdk"
import { Search } from "lucide-react"
import { cn } from "@/lib/utils"
import { Dialog, DialogContent } from "@/components/ui/dialog"
import { cn } from "@/lib/utils.js"
import { Dialog, DialogContent } from "@/components/ui/dialog.js"
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
+33
View File
@@ -0,0 +1,33 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu";
import { Check, ChevronRight, Circle } from "lucide-react";
import { cn } from "@/lib/utils.js";
const ContextMenu = ContextMenuPrimitive.Root;
const ContextMenuTrigger = ContextMenuPrimitive.Trigger;
const ContextMenuGroup = ContextMenuPrimitive.Group;
const ContextMenuPortal = ContextMenuPrimitive.Portal;
const ContextMenuSub = ContextMenuPrimitive.Sub;
const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup;
const ContextMenuSubTrigger = React.forwardRef(({ className, inset, children, ...props }, ref) => (_jsxs(ContextMenuPrimitive.SubTrigger, { ref: ref, className: cn("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground", inset && "pl-8", className), ...props, children: [children, _jsx(ChevronRight, { className: "ml-auto h-4 w-4" })] })));
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName;
const ContextMenuSubContent = React.forwardRef(({ className, ...props }, ref) => (_jsx(ContextMenuPrimitive.SubContent, { ref: ref, className: cn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className), ...props })));
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName;
const ContextMenuContent = React.forwardRef(({ className, ...props }, ref) => (_jsx(ContextMenuPrimitive.Portal, { children: _jsx(ContextMenuPrimitive.Content, { ref: ref, className: cn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", className), ...props }) })));
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName;
const ContextMenuItem = React.forwardRef(({ className, inset, ...props }, ref) => (_jsx(ContextMenuPrimitive.Item, { ref: ref, className: cn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", inset && "pl-8", className), ...props })));
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName;
const ContextMenuCheckboxItem = React.forwardRef(({ className, children, checked, ...props }, ref) => (_jsxs(ContextMenuPrimitive.CheckboxItem, { ref: ref, className: cn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className), checked: checked, ...props, children: [_jsx("span", { className: "absolute left-2 flex h-3.5 w-3.5 items-center justify-center", children: _jsx(ContextMenuPrimitive.ItemIndicator, { children: _jsx(Check, { className: "h-4 w-4" }) }) }), children] })));
ContextMenuCheckboxItem.displayName =
ContextMenuPrimitive.CheckboxItem.displayName;
const ContextMenuRadioItem = React.forwardRef(({ className, children, ...props }, ref) => (_jsxs(ContextMenuPrimitive.RadioItem, { ref: ref, className: cn("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", className), ...props, children: [_jsx("span", { className: "absolute left-2 flex h-3.5 w-3.5 items-center justify-center", children: _jsx(ContextMenuPrimitive.ItemIndicator, { children: _jsx(Circle, { className: "h-2 w-2 fill-current" }) }) }), children] })));
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName;
const ContextMenuLabel = React.forwardRef(({ className, inset, ...props }, ref) => (_jsx(ContextMenuPrimitive.Label, { ref: ref, className: cn("px-2 py-1.5 text-sm font-semibold text-foreground", inset && "pl-8", className), ...props })));
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName;
const ContextMenuSeparator = React.forwardRef(({ className, ...props }, ref) => (_jsx(ContextMenuPrimitive.Separator, { ref: ref, className: cn("-mx-1 my-1 h-px bg-border", className), ...props })));
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName;
const ContextMenuShortcut = ({ className, ...props }) => {
return (_jsx("span", { className: cn("ml-auto text-xs tracking-widest text-muted-foreground", className), ...props }));
};
ContextMenuShortcut.displayName = "ContextMenuShortcut";
export { ContextMenu, ContextMenuTrigger, ContextMenuContent, ContextMenuItem, ContextMenuCheckboxItem, ContextMenuRadioItem, ContextMenuLabel, ContextMenuSeparator, ContextMenuShortcut, ContextMenuGroup, ContextMenuPortal, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuRadioGroup, };
+1 -1
View File
@@ -2,7 +2,7 @@ import * as React from "react"
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const ContextMenu = ContextMenuPrimitive.Root
+22
View File
@@ -0,0 +1,22 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import { cn } from "@/lib/utils.js";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef(({ className, ...props }, ref) => (_jsx(DialogPrimitive.Overlay, { ref: ref, className: cn("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", className), ...props })));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef(({ className, children, ...props }, ref) => (_jsxs(DialogPortal, { children: [_jsx(DialogOverlay, {}), _jsxs(DialogPrimitive.Content, { ref: ref, className: cn("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg", className), ...props, children: [children, _jsxs(DialogPrimitive.Close, { className: "absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground", children: [_jsx(X, { className: "h-4 w-4" }), _jsx("span", { className: "sr-only", children: "Close" })] })] })] })));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({ className, ...props }) => (_jsx("div", { className: cn("flex flex-col space-y-1.5 text-center sm:text-left", className), ...props }));
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({ className, ...props }) => (_jsx("div", { className: cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className), ...props }));
DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef(({ className, ...props }, ref) => (_jsx(DialogPrimitive.Title, { ref: ref, className: cn("text-lg font-semibold leading-none tracking-tight", className), ...props })));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef(({ className, ...props }, ref) => (_jsx(DialogPrimitive.Description, { ref: ref, className: cn("text-sm text-muted-foreground", className), ...props })));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export { Dialog, DialogPortal, DialogOverlay, DialogClose, DialogTrigger, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription, };
+1 -1
View File
@@ -2,7 +2,7 @@ import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const Dialog = DialogPrimitive.Root
+22
View File
@@ -0,0 +1,22 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Drawer as DrawerPrimitive } from "vaul";
import { cn } from "@/lib/utils.js";
const Drawer = ({ shouldScaleBackground = true, ...props }) => (_jsx(DrawerPrimitive.Root, { shouldScaleBackground: shouldScaleBackground, ...props }));
Drawer.displayName = "Drawer";
const DrawerTrigger = DrawerPrimitive.Trigger;
const DrawerPortal = DrawerPrimitive.Portal;
const DrawerClose = DrawerPrimitive.Close;
const DrawerOverlay = React.forwardRef(({ className, ...props }, ref) => (_jsx(DrawerPrimitive.Overlay, { ref: ref, className: cn("fixed inset-0 z-50 bg-black/80", className), ...props })));
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName;
const DrawerContent = React.forwardRef(({ className, children, ...props }, ref) => (_jsxs(DrawerPortal, { children: [_jsx(DrawerOverlay, {}), _jsxs(DrawerPrimitive.Content, { ref: ref, className: cn("fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background", className), ...props, children: [_jsx("div", { className: "mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" }), children] })] })));
DrawerContent.displayName = "DrawerContent";
const DrawerHeader = ({ className, ...props }) => (_jsx("div", { className: cn("grid gap-1.5 p-4 text-center sm:text-left", className), ...props }));
DrawerHeader.displayName = "DrawerHeader";
const DrawerFooter = ({ className, ...props }) => (_jsx("div", { className: cn("mt-auto flex flex-col gap-2 p-4", className), ...props }));
DrawerFooter.displayName = "DrawerFooter";
const DrawerTitle = React.forwardRef(({ className, ...props }, ref) => (_jsx(DrawerPrimitive.Title, { ref: ref, className: cn("text-lg font-semibold leading-none tracking-tight", className), ...props })));
DrawerTitle.displayName = DrawerPrimitive.Title.displayName;
const DrawerDescription = React.forwardRef(({ className, ...props }, ref) => (_jsx(DrawerPrimitive.Description, { ref: ref, className: cn("text-sm text-muted-foreground", className), ...props })));
DrawerDescription.displayName = DrawerPrimitive.Description.displayName;
export { Drawer, DrawerPortal, DrawerOverlay, DrawerTrigger, DrawerClose, DrawerContent, DrawerHeader, DrawerFooter, DrawerTitle, DrawerDescription, };
+1 -1
View File
@@ -1,7 +1,7 @@
import * as React from "react"
import { Drawer as DrawerPrimitive } from "vaul"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const Drawer = ({
shouldScaleBackground = true,
+35
View File
@@ -0,0 +1,35 @@
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { Check, ChevronRight, Circle } from "lucide-react";
import { cn } from "@/lib/utils.js";
const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
const DropdownMenuSub = DropdownMenuPrimitive.Sub;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuSubTrigger = React.forwardRef(({ className, inset, children, ...props }, ref) => (_jsxs(DropdownMenuPrimitive.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 data-[state=open]:bg-accent", inset && "pl-8", className), ...props, children: [children, _jsx(ChevronRight, { className: "ml-auto h-4 w-4" })] })));
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef(({ className, ...props }, ref) => (_jsx(DropdownMenuPrimitive.SubContent, { ref: ref, className: cn("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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 })));
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef(({ className, sideOffset = 4, ...props }, ref) => (_jsx(DropdownMenuPrimitive.Portal, { children: _jsx(DropdownMenuPrimitive.Content, { ref: ref, sideOffset: sideOffset, 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 }) })));
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef(({ className, inset, ...props }, ref) => (_jsx(DropdownMenuPrimitive.Item, { ref: ref, className: cn("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", inset && "pl-8", className), ...props })));
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef(({ className, children, checked, ...props }, ref) => (_jsxs(DropdownMenuPrimitive.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 transition-colors 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(DropdownMenuPrimitive.ItemIndicator, { children: _jsx(Check, { className: "h-4 w-4" }) }) }), children] })));
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef(({ className, children, ...props }, ref) => (_jsxs(DropdownMenuPrimitive.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 transition-colors 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(DropdownMenuPrimitive.ItemIndicator, { children: _jsx(Circle, { className: "h-2 w-2 fill-current" }) }) }), children] })));
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef(({ className, inset, ...props }, ref) => (_jsx(DropdownMenuPrimitive.Label, { ref: ref, className: cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className), ...props })));
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef(({ className, ...props }, ref) => (_jsx(DropdownMenuPrimitive.Separator, { ref: ref, className: cn("-mx-1 my-1 h-px bg-muted", className), ...props })));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
const DropdownMenuShortcut = ({ className, ...props }) => {
return (_jsx("span", { className: cn("ml-auto text-xs tracking-widest opacity-60", className), ...props }));
};
DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuCheckboxItem, DropdownMenuRadioItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuGroup, DropdownMenuPortal, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuRadioGroup, };
+1 -1
View File
@@ -2,7 +2,7 @@ import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils.js"
const DropdownMenu = DropdownMenuPrimitive.Root
+22
View File
@@ -0,0 +1,22 @@
import * as React from "react";
import { useFormContext, } from "react-hook-form";
export const FormFieldContext = React.createContext({});
export const FormItemContext = React.createContext({});
export const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext);
const itemContext = React.useContext(FormItemContext);
const { getFieldState, formState } = useFormContext();
const fieldState = getFieldState(fieldContext.name, formState);
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>");
}
const { id } = itemContext;
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
};
};
+43
View File
@@ -0,0 +1,43 @@
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { Controller, FormProvider, } from "react-hook-form";
import { cn } from "@/lib/utils.js";
import { Label } from "@/components/ui/label.js";
import { FormFieldContext, FormItemContext, useFormField } from "./form-utils.js";
const Form = FormProvider;
const FormField = ({ ...props }) => {
return (_jsx(FormFieldContext.Provider, { value: { name: props.name }, children: _jsx(Controller, { ...props }) }));
};
const FormItem = React.forwardRef(({ className, ...props }, ref) => {
const id = React.useId();
return (_jsx(FormItemContext.Provider, { value: { id }, children: _jsx("div", { ref: ref, className: cn("space-y-2", className), ...props }) }));
});
FormItem.displayName = "FormItem";
const FormLabel = React.forwardRef(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField();
return (_jsx(Label, { ref: ref, className: cn(error && "text-destructive", className), htmlFor: formItemId, ...props }));
});
FormLabel.displayName = "FormLabel";
const FormControl = React.forwardRef(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField();
return (_jsx(Slot, { ref: ref, id: formItemId, "aria-describedby": !error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`, "aria-invalid": !!error, ...props }));
});
FormControl.displayName = "FormControl";
const FormDescription = React.forwardRef(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField();
return (_jsx("p", { ref: ref, id: formDescriptionId, className: cn("text-sm text-muted-foreground", className), ...props }));
});
FormDescription.displayName = "FormDescription";
const FormMessage = React.forwardRef(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message) : children;
if (!body) {
return null;
}
return (_jsx("p", { ref: ref, id: formMessageId, className: cn("text-sm font-medium text-destructive", className), ...props, children: body }));
});
FormMessage.displayName = "FormMessage";
export { Form, FormItem, FormLabel, FormControl, FormDescription, FormMessage, FormField, };
Loaded 100 of 209 files, more files were not shown because too many files have changed in this diff. Show more