mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 08:07:21 +00:00
Compare commits
231
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0dca78709 | ||
|
|
d1744b7d71 | ||
|
|
6458b24305 | ||
|
|
9114c7db86 | ||
|
|
b2cc0aef79 | ||
|
|
363b2e3ebb | ||
|
|
37ff1d6957 | ||
|
|
2baccf1ea0 | ||
|
|
dddeb7fc61 | ||
|
|
cf64f2ca83 | ||
|
|
0d327372fe | ||
|
|
b4a1a46430 | ||
|
|
d5c37a13c7 | ||
|
|
1879cd18f5 | ||
|
|
8ff4046308 | ||
|
|
be0f74543c | ||
|
|
c0f822a4f4 | ||
|
|
480d5905d7 | ||
|
|
31d2aa4761 | ||
|
|
b52374f0db | ||
|
|
5c1cff5618 | ||
|
|
e335e787ff | ||
|
|
241a235ce1 | ||
|
|
df80653a83 | ||
|
|
a862d30e8e | ||
|
|
5eeb424d43 | ||
|
|
b6d31cdd9d | ||
|
|
7473c794cc | ||
|
|
0c039bfbcf | ||
|
|
36237fd5b6 | ||
|
|
1de668785f | ||
|
|
c231ee40ac | ||
|
|
fbbf7f8c39 | ||
|
|
23508f361b | ||
|
|
612aacb00b | ||
|
|
23f01f7dda | ||
|
|
68959e0e77 | ||
|
|
d17fc5ddd7 | ||
|
|
c5dabfdb3a | ||
|
|
2cb807a4eb | ||
|
|
58bd5b1a4e | ||
|
|
2543c9c806 | ||
|
|
94e29c2f45 | ||
|
|
6491300bc6 | ||
|
|
d393975ccb | ||
|
|
3f25629923 | ||
|
|
c7cfc0fe99 | ||
|
|
04912496be | ||
|
|
21540d251f | ||
|
|
97a493c218 | ||
|
|
6845e6cf7c | ||
|
|
3101532a2b | ||
|
|
7c9f3cb797 | ||
|
|
a76c292fec | ||
|
|
4c129251c7 | ||
|
|
0484b10a96 | ||
|
|
230183bd0c | ||
|
|
a92f80b6e3 | ||
|
|
a51094e157 | ||
|
|
ab54efba47 | ||
|
|
0a2474d2f5 | ||
|
|
62add9ec26 | ||
|
|
661a5e1eac | ||
|
|
9d8b5a3f43 | ||
|
|
8f51db5a49 | ||
|
|
c98a6bbf64 | ||
|
|
9ed8676d17 | ||
|
|
8183e3cc5a | ||
|
|
0bc03017bb | ||
|
|
f75ddb6654 | ||
|
|
ebdd4dcb84 | ||
|
|
3b48df1093 | ||
|
|
7eecec7506 | ||
|
|
8c34dbc8d5 | ||
|
|
45ff37e752 | ||
|
|
11ac73776c | ||
|
|
14eccbcb6f | ||
|
|
55bf545646 | ||
|
|
ec1a9777de | ||
|
|
5a5c05c1d4 | ||
|
|
f7736ddfb1 | ||
|
|
7fdcb658b3 | ||
|
|
c37df875b9 | ||
|
|
d68f2d8486 | ||
|
|
b11e843196 | ||
|
|
414e0bf029 | ||
|
|
7b49400951 | ||
|
|
e226ec42a5 | ||
|
|
baaf7e6ab4 | ||
|
|
39afb03570 | ||
|
|
83db2fd539 | ||
|
|
a2eab78ae3 | ||
|
|
65b974fb41 | ||
|
|
cadbc02947 | ||
|
|
37aaadbd70 | ||
|
|
0cda9cb7fc | ||
|
|
49952a10bf | ||
|
|
fce2a3da23 | ||
|
|
15dbc6df85 | ||
|
|
508fa84466 | ||
|
|
b7ff219e6e | ||
|
|
b9750b3759 | ||
|
|
ad1c8b123c | ||
|
|
4e1c43ee13 | ||
|
|
1e179b4396 | ||
|
|
cd5376ff49 | ||
|
|
561975cded | ||
|
|
7a5fce4933 | ||
|
|
8559a004e8 | ||
|
|
df40d30f15 | ||
|
|
062545d061 | ||
|
|
9625533ed4 | ||
|
|
db09c45a54 | ||
|
|
ed143157bf | ||
|
|
9646620a46 | ||
|
|
830c10fe8d | ||
|
|
927010c0d0 | ||
|
|
e70b3640e8 | ||
|
|
1983126de9 | ||
|
|
87d3cfb2eb | ||
|
|
98aa853716 | ||
|
|
5d4a19eb9c | ||
|
|
10386c2c38 | ||
|
|
034b5eab33 | ||
|
|
fddd1d20f3 | ||
|
|
aa1088499f | ||
|
|
c07a53e727 | ||
|
|
68202d655e | ||
|
|
641f570329 | ||
|
|
c2d5187efb | ||
|
|
9ad31aa674 | ||
|
|
d1a4e26f79 | ||
|
|
b3bc9d45e0 | ||
|
|
1b74dc38fd | ||
|
|
7a7d91dbed | ||
|
|
2d325f7343 | ||
|
|
d2854f917c | ||
|
|
28cda6d365 | ||
|
|
da87f2c7b1 | ||
|
|
61508020ae | ||
|
|
f146bf58d7 | ||
|
|
cd87b6e430 | ||
|
|
696c5ba963 | ||
|
|
36e49106a6 | ||
|
|
048bf4cc69 | ||
|
|
3ad83cd114 | ||
|
|
c3310ab485 | ||
|
|
bce7af2e76 | ||
|
|
f762136f14 | ||
|
|
5b90ebe482 | ||
|
|
c2ff2a990f | ||
|
|
0481cd024e | ||
|
|
1617d80ece | ||
|
|
a8163d7a6c | ||
|
|
190f0cd791 | ||
|
|
aa4110e6b3 | ||
|
|
94d1688f43 | ||
|
|
9f12c58dc0 | ||
|
|
0ee653f631 | ||
|
|
3672a13ac8 | ||
|
|
ac46749fad | ||
|
|
1fc548c7e9 | ||
|
|
8bdff8da6d | ||
|
|
3a34db8320 | ||
|
|
065f3cfe02 | ||
|
|
ed2d3798ea | ||
|
|
03f804ed90 | ||
|
|
aa1e2145d0 | ||
|
|
130300f1c1 | ||
|
|
9cb2795496 | ||
|
|
34770a3145 | ||
|
|
37bee859b6 | ||
|
|
139e6696db | ||
|
|
738b512d9c | ||
|
|
7c5fe75572 | ||
|
|
865ca7039f | ||
|
|
acbe053c97 | ||
|
|
830d806933 | ||
|
|
ee42c84171 | ||
|
|
98f3305aa1 | ||
|
|
2d326ca5e9 | ||
|
|
dbd28373a5 | ||
|
|
ed3080d34e | ||
|
|
79ed87e67c | ||
|
|
9221693edb | ||
|
|
1b8dab92b9 | ||
|
|
95de9fde27 | ||
|
|
81f90b9985 | ||
|
|
0e8a141490 | ||
|
|
a6eeb05d6e | ||
|
|
e0d94fae71 | ||
|
|
be2d2d63fa | ||
|
|
f633f4b423 | ||
|
|
2c5d38013f | ||
|
|
d14652559e | ||
|
|
4254b9eb0b | ||
|
|
e099d8b467 | ||
|
|
ef7667501b | ||
|
|
7edfde7e9f | ||
|
|
69faf49454 | ||
|
|
aa2468b656 | ||
|
|
7ee419bc6d | ||
|
|
73e7e818b2 | ||
|
|
ebc399776d | ||
|
|
56df17b56e | ||
|
|
856d333c30 | ||
|
|
b24578f0db | ||
|
|
cc3d87192c | ||
|
|
70eceef6ae | ||
|
|
601b3ce370 | ||
|
|
f77a6a4af3 | ||
|
|
d05a78880a | ||
|
|
750c165c05 | ||
|
|
aa91528de8 | ||
|
|
95eb9634b5 | ||
|
|
69060820f8 | ||
|
|
1a431c9d8a | ||
|
|
246ffb2181 | ||
|
|
db13869675 | ||
|
|
b8137d0751 | ||
|
|
16ca716db2 | ||
|
|
70dec2fc9a | ||
|
|
cac4ae6b93 | ||
|
|
a7fcaaf1f3 | ||
|
|
3052ce66f1 | ||
|
|
87a0846bbe | ||
|
|
e4d081d3da | ||
|
|
d623f11653 | ||
|
|
2ac30c4f29 | ||
|
|
b8603ff80e | ||
|
|
3cc2fe6d64 |
No files matched your search
@@ -1 +0,0 @@
|
||||
CONTEXT.md
|
||||
@@ -0,0 +1,7 @@
|
||||
# Admin Configuration
|
||||
# Set this to the npub of the site administrator
|
||||
# Only this user will have access to the admin dashboard at /admin
|
||||
VITE_ADMIN_NPUB=npub1abc123def456ghi789...
|
||||
|
||||
# Example:
|
||||
# VITE_ADMIN_NPUB=npub1sg6plzptd64u62a878hep2kev88swjh3tw00gjsfl8f237lmu63q0uf63m
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../.mcp.json
|
||||
@@ -1 +0,0 @@
|
||||
../CONTEXT.md
|
||||
@@ -0,0 +1,56 @@
|
||||
name: Deploy to GitHub Pages
|
||||
|
||||
on:
|
||||
# Runs on pushes targeting the default branch
|
||||
push:
|
||||
branches: ["main"]
|
||||
|
||||
# Allows you to run this workflow manually from the Actions tab
|
||||
workflow_dispatch:
|
||||
|
||||
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
|
||||
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
|
||||
concurrency:
|
||||
group: "pages"
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
# Single deploy job
|
||||
deploy:
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies and build
|
||||
run: |
|
||||
npm install
|
||||
npm run build
|
||||
cp dist/index.html dist/404.html
|
||||
|
||||
- name: Setup Pages
|
||||
uses: actions/configure-pages@v5
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-pages-artifact@v3
|
||||
with:
|
||||
path: dist
|
||||
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
uses: actions/deploy-pages@v4
|
||||
@@ -0,0 +1,30 @@
|
||||
name: Test
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
# Allows you to run this workflow manually from the Actions tab
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
|
||||
- name: Clean install dependencies
|
||||
run: |
|
||||
rm -rf node_modules package-lock.json
|
||||
npm install
|
||||
|
||||
- name: Run tests
|
||||
run: npm run test
|
||||
@@ -11,6 +11,7 @@ node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
.ai/
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
@@ -20,3 +21,11 @@ dist-ssr
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
# Vercel
|
||||
.vercel
|
||||
|
||||
# Secrets
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
@@ -0,0 +1,27 @@
|
||||
image: node:22
|
||||
|
||||
default:
|
||||
interruptible: true
|
||||
timeout: 1 minute
|
||||
|
||||
stages:
|
||||
- test
|
||||
- deploy
|
||||
|
||||
test:
|
||||
stage: test
|
||||
script:
|
||||
- npm run test
|
||||
|
||||
pages:
|
||||
stage: deploy
|
||||
script:
|
||||
- npm run build
|
||||
- rm -rf public
|
||||
- mv dist public
|
||||
artifacts:
|
||||
paths:
|
||||
- public
|
||||
only:
|
||||
variables:
|
||||
- $CI_DEFAULT_BRANCH == $CI_COMMIT_REF_NAME
|
||||
@@ -1 +0,0 @@
|
||||
CONTEXT.md
|
||||
@@ -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
|
||||
@@ -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"]
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+6
-1
@@ -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"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
# Site Administration Dashboard
|
||||
|
||||
The MKStack template includes a comprehensive site administration dashboard for content moderation and site management.
|
||||
|
||||
## Access
|
||||
|
||||
The admin dashboard is accessible at `/admin` and requires environment variable configuration.
|
||||
|
||||
**Authentication Required**: Only the site administrator (configured via `VITE_ADMIN_NPUB` environment variable) can access the admin dashboard. Other users will see an access denied message with a login prompt.
|
||||
|
||||
## Configuration
|
||||
|
||||
Set the `VITE_ADMIN_NPUB` environment variable to the npub of the site administrator:
|
||||
|
||||
```bash
|
||||
VITE_ADMIN_NPUB=npub1abc123def456ghi789...
|
||||
```
|
||||
|
||||
See `.env.example` for configuration details.
|
||||
|
||||
## Features
|
||||
|
||||
### Content Moderation Tab
|
||||
- **Recent Content Review**: View and moderate recent posts and articles
|
||||
- **Hide/Show Content**: Quickly hide inappropriate content or restore hidden content
|
||||
- **Content Types**: Distinguishes between notes, articles, and other event kinds
|
||||
- **Author Information**: Shows poster details with avatars and names
|
||||
- **Timestamps**: Recent activity tracking for moderation decisions
|
||||
|
||||
### User Management Tab
|
||||
- **Allow List**: Explicitly allowed users who can post content
|
||||
- **Deny List**: Blocked users who cannot post content
|
||||
- **Add Users**: Add users to allow/deny lists by npub
|
||||
- **User Profiles**: View user avatars, names, and npub identifiers
|
||||
- **Cross-List Management**: Adding to one list removes from the other
|
||||
|
||||
### Blocked Words Tab
|
||||
- **Word Filtering**: Add words and phrases to automatically filter content
|
||||
- **Case Sensitivity**: Toggle case-sensitive matching
|
||||
- **Whole Words**: Option to match whole words only vs partial matches
|
||||
- **Bulk Management**: Add/remove multiple blocked terms
|
||||
- **Real-time Filtering**: Immediate effect on content display
|
||||
|
||||
### Site Analytics Tab
|
||||
- **Content Statistics**: Total events, notes, articles on the site
|
||||
- **User Activity**: Unique authors and active users
|
||||
- **Time-based Metrics**: Activity in last 24 hours and 7 days
|
||||
- **Content Breakdown**: Distribution of different content types
|
||||
- **Growth Tracking**: Monitor site activity trends
|
||||
|
||||
### Site Settings Tab
|
||||
- **Site Information**: Configure site name and description
|
||||
- **Moderation Controls**: Enable/disable content moderation features
|
||||
- **Auto-hide Settings**: Automatically hide content matching blocked words
|
||||
- **Approval Workflow**: Require manual approval for all content
|
||||
- **Environment Status**: View current configuration settings
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### Route Configuration
|
||||
The admin route is configured in `AppRouter.tsx` as `/admin` and takes precedence over the generic NIP-19 route.
|
||||
|
||||
### Authentication Flow
|
||||
1. Environment variable `VITE_ADMIN_NPUB` is decoded using `nip19.decode()`
|
||||
2. Current user's pubkey is compared with the admin pubkey
|
||||
3. Unauthorized users see an access denied screen with login options
|
||||
4. Authorized users see the full dashboard interface
|
||||
|
||||
### Data Fetching
|
||||
- Uses TanStack Query for efficient data fetching and caching
|
||||
- Implements proper loading states with skeleton components
|
||||
- Includes error handling and timeout management
|
||||
- Queries recent site content for moderation review
|
||||
- Fetches site-wide analytics and statistics
|
||||
|
||||
### Nostr-Based Storage
|
||||
- Uses custom event kind `39767` for persistent admin policies
|
||||
- Stores all settings as addressable Nostr events
|
||||
- Syncs across devices and browsers automatically
|
||||
- Provides backup and recovery of admin settings
|
||||
- Maintains audit trail of policy changes
|
||||
|
||||
### Components Used
|
||||
- **Tabs**: Organized dashboard sections using shadcn/ui tabs
|
||||
- **Cards**: Statistical displays and content sections
|
||||
- **Badges**: Event type indicators and verification status
|
||||
- **Avatars**: User profile images with fallbacks
|
||||
- **Skeletons**: Loading states that match content structure
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Adding Admin Dashboard Link
|
||||
Use the `AdminDashboardLink` component to add a dashboard link for logged-in users:
|
||||
|
||||
```tsx
|
||||
import { AdminDashboardLink } from '@/components/AdminDashboardLink';
|
||||
|
||||
function Header() {
|
||||
return (
|
||||
<header className="flex items-center justify-between p-4">
|
||||
<h1>My App</h1>
|
||||
<AdminDashboardLink />
|
||||
</header>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Direct Access
|
||||
Site administrators can access the dashboard directly by visiting:
|
||||
```
|
||||
/admin
|
||||
```
|
||||
|
||||
### Setting Up Admin Access
|
||||
To configure admin dashboard access:
|
||||
1. Set `VITE_ADMIN_NPUB` environment variable to your npub
|
||||
2. Log in with the corresponding Nostr account
|
||||
3. Navigate to `/admin`
|
||||
4. The `AdminDashboardLink` component will automatically appear for admin users
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- **Environment-based Authentication**: Admin access controlled via environment variable
|
||||
- **Single Admin Model**: Only one designated admin per site instance
|
||||
- **Nostr Event Storage**: Admin policies stored as signed Nostr events (kind 39767)
|
||||
- **Cross-Device Sync**: Settings automatically sync across all admin devices
|
||||
- **Content Filtering**: Blocked words and user lists affect content display
|
||||
- **Timeout Protection**: All queries include timeout limits to prevent hanging requests
|
||||
- **No Private Key Access**: Uses existing authentication without requiring private keys
|
||||
- **Event Integrity**: All admin policies are cryptographically signed and verifiable
|
||||
|
||||
## Customization
|
||||
|
||||
The admin dashboard is designed to be easily extensible:
|
||||
|
||||
### Adding New Tabs
|
||||
1. Add a new `TabsTrigger` in the main dashboard component
|
||||
2. Create a corresponding `TabsContent` section
|
||||
3. Implement the tab's functionality as a separate component
|
||||
|
||||
### Extending Content Moderation
|
||||
- **Automated Rules**: Add automatic content filtering based on patterns
|
||||
- **Approval Queues**: Implement content approval workflows
|
||||
- **Bulk Actions**: Add bulk moderation operations
|
||||
- **Moderation History**: Track moderation actions and decisions
|
||||
|
||||
### Advanced User Management
|
||||
- **Role-based Access**: Implement different user permission levels
|
||||
- **Temporary Restrictions**: Time-limited bans or restrictions
|
||||
- **User Reporting**: Allow community reporting of problematic users
|
||||
- **Whitelist/Blacklist Import**: Bulk import of user lists
|
||||
|
||||
### Enhanced Analytics
|
||||
- **Engagement Metrics**: Track user interaction patterns
|
||||
- **Content Performance**: Analyze popular content types
|
||||
- **Moderation Statistics**: Track moderation actions and effectiveness
|
||||
- **Growth Trends**: Monitor site growth and user retention
|
||||
|
||||
## Technical Notes
|
||||
|
||||
- **React Hooks**: Follows React hooks rules with proper conditional rendering
|
||||
- **TypeScript**: Fully typed with proper error handling (with type assertions for nostr-tools)
|
||||
- **Responsive**: Works on mobile and desktop devices
|
||||
- **Accessible**: Uses semantic HTML and ARIA attributes via Radix UI
|
||||
- **Performance**: Implements query caching and loading optimization
|
||||
- **Custom Storage Hook**: `useAdminStorage` for Nostr-based persistence
|
||||
- **Environment Variables**: Requires Vite environment variable configuration
|
||||
- **Icon Library**: Uses Lucide React icons throughout the interface
|
||||
- **Custom NIP**: Implements event kind 39767 for admin storage (see `NIP.md`)
|
||||
- **Content Filtering**: `useContentFilter` hook for policy enforcement
|
||||
-198
@@ -1,198 +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
|
||||
- **TanStack Query**: For data fetching, caching, and state management
|
||||
- **TypeScript**: For type-safe JavaScript development
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/hooks/`: Custom hooks including `useNostr` and `useNostrQuery`
|
||||
- `/src/pages/`: Page components used by React Router
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/public/`: Static assets
|
||||
|
||||
## UI Components
|
||||
|
||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||
|
||||
- **Accordion**: Vertically collapsing content panels
|
||||
- **Alert**: Displays important messages to users
|
||||
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
|
||||
- **AspectRatio**: Maintains consistent width-to-height ratio
|
||||
- **Avatar**: User profile pictures with fallback support
|
||||
- **Badge**: Small status descriptors for UI elements
|
||||
- **Breadcrumb**: Navigation aid showing current location in hierarchy
|
||||
- **Button**: Customizable button with multiple variants and sizes
|
||||
- **Calendar**: Date picker component
|
||||
- **Card**: Container with header, content, and footer sections
|
||||
- **Carousel**: Slideshow for cycling through elements
|
||||
- **Chart**: Data visualization component
|
||||
- **Checkbox**: Selectable input element
|
||||
- **Collapsible**: Toggle for showing/hiding content
|
||||
- **Command**: Command palette for keyboard-first interfaces
|
||||
- **ContextMenu**: Right-click menu component
|
||||
- **Dialog**: Modal window overlay
|
||||
- **Drawer**: Side-sliding panel
|
||||
- **DropdownMenu**: Menu that appears from a trigger element
|
||||
- **Form**: Form validation and submission handling
|
||||
- **HoverCard**: Card that appears when hovering over an element
|
||||
- **InputOTP**: One-time password input field
|
||||
- **Input**: Text input field
|
||||
- **Label**: Accessible form labels
|
||||
- **Menubar**: Horizontal menu with dropdowns
|
||||
- **NavigationMenu**: Accessible navigation component
|
||||
- **Pagination**: Controls for navigating between pages
|
||||
- **Popover**: Floating content triggered by a button
|
||||
- **Progress**: Progress indicator
|
||||
- **RadioGroup**: Group of radio inputs
|
||||
- **Resizable**: Resizable panels and interfaces
|
||||
- **ScrollArea**: Scrollable container with custom scrollbars
|
||||
- **Select**: Dropdown selection component
|
||||
- **Separator**: Visual divider between content
|
||||
- **Sheet**: Side-anchored dialog component
|
||||
- **Sidebar**: Navigation sidebar component
|
||||
- **Skeleton**: Loading placeholder
|
||||
- **Slider**: Input for selecting a value from a range
|
||||
- **Sonner**: Toast notification manager
|
||||
- **Switch**: Toggle switch control
|
||||
- **Table**: Data table with headers and rows
|
||||
- **Tabs**: Tabbed interface component
|
||||
- **Textarea**: Multi-line text input
|
||||
- **Toast**: Toast notification component
|
||||
- **ToggleGroup**: Group of toggle buttons
|
||||
- **Toggle**: Two-state button
|
||||
- **Tooltip**: Informational text that appears on hover
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||
|
||||
### The `useNostr` Hook
|
||||
|
||||
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
function useCustomHook() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
### Query Nostr Data with `useNostr` and Tanstack Query
|
||||
|
||||
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/query';
|
||||
|
||||
function usePosts() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['posts'],
|
||||
queryFn: async (c) => {
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
|
||||
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
|
||||
return events; // these events could be transformed into another format
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
### The `useNostrPublish` Hook
|
||||
|
||||
To publish events, use the `useNostrPublish` hook in this project.
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
|
||||
export function MyComponent() {
|
||||
const [ data, setData] = useState<Record<string, string>>({});
|
||||
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: createEvent } = useNostrPublish();
|
||||
|
||||
const handleSubmit = () => {
|
||||
createEvent({ kind: 1, content: data.content });
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return <span>You must be logged in to use this form.</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} disabled={!user}>
|
||||
{/* ...some input fields */}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
|
||||
|
||||
### Nostr Login
|
||||
|
||||
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
|
||||
|
||||
```tsx
|
||||
import { LoginArea } from "@/components/auth/LoginArea";
|
||||
|
||||
function MyComponent() {
|
||||
return (
|
||||
<div>
|
||||
{/* other components ... */}
|
||||
|
||||
<LoginArea />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
The `LoginArea` component displays a "Log in" button when the user is logged out, and changes to an account switcher once the user is logged in. It handles all the login-related UI and interactions internally, including displaying login dialogs and switching between accounts.
|
||||
|
||||
## Development Practices
|
||||
|
||||
- Uses React Query for data fetching and caching
|
||||
- Follows shadcn/ui component patterns
|
||||
- Implements Path Aliases with `@/` prefix for cleaner imports
|
||||
- Uses Vite for fast development and production builds
|
||||
- Component-based architecture with React hooks
|
||||
- Default connection to multiple Nostr relays for network redundancy
|
||||
|
||||
## Build & Deployment
|
||||
|
||||
- Build for production: `npm run build`
|
||||
- Development build: `npm run build:dev`
|
||||
|
||||
## Testing Your Changes
|
||||
|
||||
Whenever you modify code, you should test your changes after you're finished by running:
|
||||
|
||||
```bash
|
||||
npm run ci
|
||||
```
|
||||
|
||||
This command will typecheck the code and attempt to build it.
|
||||
|
||||
Your task is not considered finished until this test passes without errors.
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
AGENTS.md
|
||||
@@ -0,0 +1,179 @@
|
||||
# NIP-XX: Site Administration Events
|
||||
|
||||
## Abstract
|
||||
|
||||
This NIP defines a custom event kind for storing site administration policies and configurations in Nostr applications. It allows site administrators to persist content moderation settings, user access controls, and site configuration across devices and sessions.
|
||||
|
||||
## Specification
|
||||
|
||||
### Event Kind
|
||||
|
||||
This NIP introduces event kind `39767` for site administration data.
|
||||
|
||||
### Event Structure
|
||||
|
||||
Site administration events are **addressable events** that use the `d` tag to identify different configuration categories.
|
||||
|
||||
```json
|
||||
{
|
||||
"kind": 39767,
|
||||
"content": "<JSON-encoded administration data>",
|
||||
"tags": [
|
||||
["d", "admin-config"],
|
||||
["alt", "Site administration configuration and policies"]
|
||||
],
|
||||
"created_at": <unix timestamp>,
|
||||
"pubkey": "<site administrator's pubkey>"
|
||||
}
|
||||
```
|
||||
|
||||
### Content Schema
|
||||
|
||||
The `content` field contains a JSON object with the following structure:
|
||||
|
||||
```json
|
||||
{
|
||||
"hiddenEvents": ["<event_id>", "..."],
|
||||
"allowList": ["<pubkey>", "..."],
|
||||
"denyList": ["<pubkey>", "..."],
|
||||
"blockedWords": ["word1", "phrase2", "..."],
|
||||
"caseSensitive": false,
|
||||
"wholeWordsOnly": true,
|
||||
"enableModeration": true,
|
||||
"autoHideBlocked": true,
|
||||
"requireApproval": false,
|
||||
"siteName": "My Nostr Site",
|
||||
"siteDescription": "A description of the site"
|
||||
}
|
||||
```
|
||||
|
||||
#### Field Descriptions
|
||||
|
||||
- **`hiddenEvents`**: Array of event IDs that have been manually hidden by the administrator
|
||||
- **`allowList`**: Array of pubkeys explicitly allowed to post content (if not empty, only these users can post)
|
||||
- **`denyList`**: Array of pubkeys blocked from posting content
|
||||
- **`blockedWords`**: Array of words or phrases that trigger content filtering
|
||||
- **`caseSensitive`**: Boolean indicating whether word filtering is case-sensitive
|
||||
- **`wholeWordsOnly`**: Boolean indicating whether to match whole words only (vs partial matches)
|
||||
- **`enableModeration`**: Boolean to enable/disable all moderation features
|
||||
- **`autoHideBlocked`**: Boolean to automatically hide content matching blocked words
|
||||
- **`requireApproval`**: Boolean to require manual approval for all content
|
||||
- **`siteName`**: String containing the site's display name
|
||||
- **`siteDescription`**: String containing the site's description
|
||||
|
||||
### Usage
|
||||
|
||||
#### Publishing Administration Events
|
||||
|
||||
Site administrators publish these events to store their moderation policies:
|
||||
|
||||
```javascript
|
||||
const adminEvent = {
|
||||
kind: 39767,
|
||||
content: JSON.stringify({
|
||||
hiddenEvents: [],
|
||||
allowList: [],
|
||||
denyList: ["banned_user_pubkey"],
|
||||
blockedWords: ["spam", "inappropriate"],
|
||||
caseSensitive: false,
|
||||
wholeWordsOnly: true,
|
||||
enableModeration: true,
|
||||
autoHideBlocked: true,
|
||||
requireApproval: false,
|
||||
siteName: "My Community",
|
||||
siteDescription: "A moderated Nostr community"
|
||||
}),
|
||||
tags: [
|
||||
["d", "admin-config"],
|
||||
["alt", "Site administration configuration and policies"]
|
||||
]
|
||||
};
|
||||
```
|
||||
|
||||
#### Querying Administration Events
|
||||
|
||||
Clients query for the latest administration configuration:
|
||||
|
||||
```javascript
|
||||
const adminConfig = await relay.query([{
|
||||
kinds: [39767],
|
||||
authors: [adminPubkey],
|
||||
"#d": ["admin-config"],
|
||||
limit: 1
|
||||
}]);
|
||||
```
|
||||
|
||||
### Implementation Guidelines
|
||||
|
||||
#### Authentication
|
||||
- Only events signed by the designated site administrator's private key are valid
|
||||
- The administrator's pubkey should be configured in the application (e.g., environment variable)
|
||||
- Clients should verify the event signature before applying policies
|
||||
|
||||
#### Content Filtering
|
||||
- **Allow List**: If not empty, only users on this list can post content
|
||||
- **Deny List**: Users on this list are blocked regardless of allow list status
|
||||
- **Blocked Words**: Content containing these words/phrases is filtered according to settings
|
||||
- **Case Sensitivity**: Controls whether word matching is case-sensitive
|
||||
- **Whole Words**: Controls whether to match complete words vs partial strings
|
||||
|
||||
#### Precedence Rules
|
||||
1. Deny list takes precedence over allow list
|
||||
2. Manual hiding (hiddenEvents) takes precedence over automatic filtering
|
||||
3. If moderation is disabled, no filtering is applied
|
||||
|
||||
#### Client Behavior
|
||||
- Clients should cache the latest administration event for performance
|
||||
- Updates to administration policies should be reflected immediately in the UI
|
||||
- Clients may choose to implement additional local filtering beyond these policies
|
||||
|
||||
### Security Considerations
|
||||
|
||||
- Administration events contain sensitive moderation data and should only be published by authorized administrators
|
||||
- The `alt` tag provides human-readable context for the event purpose
|
||||
- Clients should validate the JSON content structure before applying policies
|
||||
- Consider implementing rate limiting for administration event updates
|
||||
|
||||
### Rationale
|
||||
|
||||
This NIP addresses the need for persistent, cross-device site administration in decentralized Nostr applications. By storing policies as Nostr events, administrators can:
|
||||
|
||||
- Maintain consistent moderation across multiple devices
|
||||
- Backup and restore moderation settings
|
||||
- Share administrative responsibilities (with proper key management)
|
||||
- Maintain audit trails of policy changes
|
||||
|
||||
The addressable event structure allows for future expansion with additional configuration categories using different `d` tag values.
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Moderation Setup
|
||||
|
||||
```json
|
||||
{
|
||||
"kind": 39767,
|
||||
"content": "{\"hiddenEvents\":[],\"allowList\":[],\"denyList\":[\"spam_user_pubkey\"],\"blockedWords\":[\"spam\",\"scam\"],\"caseSensitive\":false,\"wholeWordsOnly\":true,\"enableModeration\":true,\"autoHideBlocked\":true,\"requireApproval\":false,\"siteName\":\"Family-Friendly Community\",\"siteDescription\":\"A safe space for family discussions\"}",
|
||||
"tags": [
|
||||
["d", "admin-config"],
|
||||
["alt", "Site administration configuration and policies"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Allowlist-Only Community
|
||||
|
||||
```json
|
||||
{
|
||||
"kind": 39767,
|
||||
"content": "{\"hiddenEvents\":[],\"allowList\":[\"trusted_user1\",\"trusted_user2\"],\"denyList\":[],\"blockedWords\":[],\"caseSensitive\":false,\"wholeWordsOnly\":true,\"enableModeration\":true,\"autoHideBlocked\":false,\"requireApproval\":true,\"siteName\":\"Private Community\",\"siteDescription\":\"Invitation-only community\"}",
|
||||
"tags": [
|
||||
["d", "admin-config"],
|
||||
["alt", "Site administration configuration and policies"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- [NIP-01: Basic protocol flow description](https://github.com/nostr-protocol/nips/blob/master/01.md)
|
||||
- [NIP-31: Dealing with Unknown Events](https://github.com/nostr-protocol/nips/blob/master/31.md)
|
||||
@@ -1,7 +1,12 @@
|
||||
# mkstack
|
||||
# MKStack
|
||||
|
||||
> NOTE: This README is from a template and should be replaced with your project description.
|
||||
Template for building Nostr client application with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
|
||||
|
||||
## Created with mkstack
|
||||
## Features
|
||||
|
||||
mkstack is a starter template for building Nostr web clients in TypeScript, using React, Tailwind, shadcn/ui, Vite, and Nostrify.
|
||||
- **Site Administration**: Content moderation and site management dashboard at `/admin` (see [ADMIN_DASHBOARD.md](ADMIN_DASHBOARD.md))
|
||||
- **Nostr Protocol Integration**: Full NIP support with custom hooks for querying and publishing
|
||||
- **Authentication**: Secure login with NIP-07 browser extensions, bunker connections, and secret keys
|
||||
- **UI Components**: 48+ accessible components from shadcn/ui
|
||||
- **Responsive Design**: Mobile-first approach with Tailwind CSS
|
||||
- **Type Safety**: Full TypeScript support with proper error handling
|
||||
@@ -0,0 +1,146 @@
|
||||
# Custom ESLint Rules
|
||||
|
||||
This directory contains custom ESLint rules for the project.
|
||||
|
||||
## no-inline-script
|
||||
|
||||
This rule prevents the use of inline script tags in HTML files. Inline scripts can pose security risks and violate Content Security Policy (CSP) directives.
|
||||
|
||||
### Examples
|
||||
|
||||
❌ **Bad** - These will trigger the rule:
|
||||
```html
|
||||
<!-- Inline JavaScript code -->
|
||||
<script>
|
||||
console.log("This is inline JavaScript");
|
||||
</script>
|
||||
|
||||
<!-- Inline JSON-LD structured data -->
|
||||
<script type="application/ld+json">
|
||||
{"@context": "https://schema.org", "@type": "Organization"}
|
||||
</script>
|
||||
```
|
||||
|
||||
✅ **Good** - These are fine:
|
||||
```html
|
||||
<!-- External script files -->
|
||||
<script src="/js/app.js"></script>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
|
||||
<!-- Empty script tags (no content) -->
|
||||
<script id="data-container"></script>
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
The rule is configured in `eslint.config.js` as:
|
||||
```javascript
|
||||
"custom/no-inline-script": "error"
|
||||
```
|
||||
|
||||
### Purpose
|
||||
|
||||
This rule helps maintain security best practices by:
|
||||
- Preventing XSS vulnerabilities from inline scripts
|
||||
- Enforcing Content Security Policy compliance
|
||||
- Encouraging separation of concerns (HTML structure vs JavaScript logic)
|
||||
- Making code easier to maintain and debug
|
||||
|
||||
## no-placeholder-comments
|
||||
|
||||
This rule detects and flags comments that start with "// In a real" (case-insensitive). These comments typically indicate placeholder implementations that should be replaced with real code.
|
||||
|
||||
### Examples
|
||||
|
||||
❌ **Bad** - These will trigger the rule:
|
||||
```javascript
|
||||
// In a real application, this would connect to a database
|
||||
const data = [];
|
||||
|
||||
// in a real world scenario, this would be different
|
||||
const config = {};
|
||||
|
||||
/* In a real implementation, we would handle errors */
|
||||
const handleError = () => {};
|
||||
```
|
||||
|
||||
✅ **Good** - These are fine:
|
||||
```javascript
|
||||
// This is a regular comment
|
||||
const data = [];
|
||||
|
||||
// TODO: Implement database connection
|
||||
const config = {};
|
||||
|
||||
// Note: In a real application, consider using a database
|
||||
const handleError = () => {};
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
The rule is configured in `eslint.config.js` as:
|
||||
```javascript
|
||||
"custom/no-placeholder-comments": "error"
|
||||
```
|
||||
|
||||
You can change the severity level to:
|
||||
- `"off"` - Disable the rule
|
||||
- `"warn"` - Show as warning
|
||||
- `"error"` - Show as error (current setting)
|
||||
|
||||
### Purpose
|
||||
|
||||
This rule helps ensure that placeholder comments used during development are replaced with actual implementations before code is committed or deployed to production.
|
||||
|
||||
## require-webmanifest
|
||||
|
||||
This rule ensures that HTML files include a proper web manifest link tag and that the referenced manifest file exists. Web manifests are essential for Progressive Web Apps (PWAs) and provide metadata about the application.
|
||||
|
||||
### Examples
|
||||
|
||||
❌ **Bad** - These will trigger the rule:
|
||||
```html
|
||||
<!-- Missing manifest link entirely -->
|
||||
<head>
|
||||
<title>My App</title>
|
||||
</head>
|
||||
|
||||
<!-- Manifest file doesn't exist -->
|
||||
<head>
|
||||
<link rel="manifest" href="/nonexistent-manifest.json">
|
||||
</head>
|
||||
|
||||
<!-- Invalid manifest link (missing rel or href) -->
|
||||
<head>
|
||||
<link href="/manifest.json">
|
||||
</head>
|
||||
```
|
||||
|
||||
✅ **Good** - These are fine:
|
||||
```html
|
||||
<!-- Proper manifest link with existing file -->
|
||||
<head>
|
||||
<link rel="manifest" href="/manifest.json">
|
||||
</head>
|
||||
|
||||
<!-- Alternative valid manifest link -->
|
||||
<head>
|
||||
<link rel="manifest" href="/public/site.webmanifest">
|
||||
</head>
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
The rule is configured in `eslint.config.js` as:
|
||||
```javascript
|
||||
"custom/require-webmanifest": "error"
|
||||
```
|
||||
|
||||
### Purpose
|
||||
|
||||
This rule helps ensure:
|
||||
- PWA compliance by requiring a web manifest
|
||||
- Proper manifest file structure and accessibility
|
||||
- Better user experience on mobile devices
|
||||
- App installation capabilities
|
||||
- Consistent branding and metadata across platforms
|
||||
@@ -0,0 +1,11 @@
|
||||
import noInlineScript from './no-inline-script.js';
|
||||
import noPlaceholderComments from './no-placeholder-comments.js';
|
||||
import requireWebmanifest from './require-webmanifest.js';
|
||||
|
||||
export default {
|
||||
rules: {
|
||||
'no-inline-script': noInlineScript,
|
||||
'no-placeholder-comments': noPlaceholderComments,
|
||||
'require-webmanifest': requireWebmanifest,
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Rule to prevent inline script tags in HTML files
|
||||
*/
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Prevent inline script tags in HTML files',
|
||||
category: 'Security',
|
||||
recommended: true,
|
||||
},
|
||||
fixable: null,
|
||||
schema: [],
|
||||
messages: {
|
||||
noInlineScript: 'Inline script tags are not allowed. Move script content to external files.',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
return {
|
||||
// For HTML files, we need to check script tags
|
||||
'ScriptTag'(node) {
|
||||
// Check if this is an inline script (has content but no src attribute)
|
||||
const hasContent = node.value && node.value.value && node.value.value.trim().length > 0;
|
||||
const hasSrc = node.attributes && node.attributes.some(attr =>
|
||||
attr.key && attr.key.value === 'src'
|
||||
);
|
||||
|
||||
// If the script has content but no src attribute, it's an inline script
|
||||
if (hasContent && !hasSrc) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'noInlineScript',
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Custom ESLint rule to detect placeholder comments starting with "// In a real"
|
||||
* These comments indicate incomplete implementations that should be replaced with real code.
|
||||
*/
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
type: "problem",
|
||||
docs: {
|
||||
description: "Disallow placeholder comments starting with '// In a real'",
|
||||
category: "Best Practices",
|
||||
recommended: true,
|
||||
},
|
||||
fixable: null,
|
||||
schema: [],
|
||||
messages: {
|
||||
placeholderComment: "Placeholder comment detected: '{{comment}}'. This should be replaced with a real implementation.",
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const sourceCode = context.getSourceCode();
|
||||
|
||||
return {
|
||||
Program() {
|
||||
const comments = sourceCode.getAllComments();
|
||||
|
||||
comments.forEach((comment) => {
|
||||
const commentText = comment.value.trim();
|
||||
|
||||
// Check if comment starts with "In a real" (case-insensitive)
|
||||
if (commentText.toLowerCase().startsWith("in a real")) {
|
||||
context.report({
|
||||
node: comment,
|
||||
messageId: "placeholderComment",
|
||||
data: {
|
||||
comment: `// ${commentText}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description: 'Require web manifest file and proper HTML link tag',
|
||||
category: 'Best Practices',
|
||||
},
|
||||
fixable: null,
|
||||
schema: [],
|
||||
messages: {
|
||||
missingManifestFile: 'Web manifest file not found. Expected {{expectedPath}}',
|
||||
missingManifestLink: 'Missing web manifest link tag in HTML head',
|
||||
invalidManifestLink: 'Web manifest link tag has incorrect rel or href attribute',
|
||||
},
|
||||
},
|
||||
|
||||
create(context) {
|
||||
const filename = context.getFilename();
|
||||
|
||||
// Only run this rule on HTML files
|
||||
if (!filename.endsWith('.html')) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
Program(node) {
|
||||
const sourceCode = context.getSourceCode();
|
||||
const htmlContent = sourceCode.getText();
|
||||
|
||||
// Check for manifest link tag in HTML
|
||||
const manifestLinkRegex = /<link[^>]*rel=["']manifest["'][^>]*>/i;
|
||||
const manifestMatch = htmlContent.match(manifestLinkRegex);
|
||||
|
||||
if (!manifestMatch) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'missingManifestLink',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract href from the manifest link
|
||||
const hrefMatch = manifestMatch[0].match(/href=["']([^"']+)["']/i);
|
||||
if (!hrefMatch) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'invalidManifestLink',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const manifestPath = hrefMatch[1];
|
||||
|
||||
// Resolve the manifest file path relative to the project root
|
||||
const htmlDir = path.dirname(filename);
|
||||
let resolvedManifestPath;
|
||||
|
||||
if (manifestPath.startsWith('/')) {
|
||||
// Absolute path - check in public directory first, then project root
|
||||
const publicPath = path.resolve(htmlDir, 'public' + manifestPath);
|
||||
const rootPath = path.resolve(htmlDir, '.' + manifestPath);
|
||||
resolvedManifestPath = fs.existsSync(publicPath) ? publicPath : rootPath;
|
||||
} else {
|
||||
// Relative path
|
||||
resolvedManifestPath = path.resolve(htmlDir, manifestPath);
|
||||
}
|
||||
|
||||
// Check if the manifest file exists
|
||||
if (!fs.existsSync(resolvedManifestPath)) {
|
||||
context.report({
|
||||
node,
|
||||
messageId: 'missingManifestFile',
|
||||
data: {
|
||||
expectedPath: manifestPath,
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
+47
-1
@@ -3,6 +3,9 @@ import globals from "globals";
|
||||
import reactHooks from "eslint-plugin-react-hooks";
|
||||
import reactRefresh from "eslint-plugin-react-refresh";
|
||||
import tseslint from "typescript-eslint";
|
||||
import htmlEslint from "@html-eslint/eslint-plugin";
|
||||
import htmlParser from "@html-eslint/parser";
|
||||
import customRules from "./eslint-rules/index.js";
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ["dist"] },
|
||||
@@ -13,9 +16,14 @@ export default tseslint.config(
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
linterOptions: {
|
||||
noInlineConfig: true, // Prevents all eslint-disable comments
|
||||
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
|
||||
},
|
||||
plugins: {
|
||||
"react-hooks": reactHooks,
|
||||
"react-refresh": reactRefresh,
|
||||
"custom": customRules,
|
||||
},
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
@@ -23,7 +31,45 @@ export default tseslint.config(
|
||||
"warn",
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
"@typescript-eslint/no-unused-vars": "off",
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
"argsIgnorePattern": "^_",
|
||||
"varsIgnorePattern": "^_",
|
||||
"ignoreRestSiblings": true,
|
||||
},
|
||||
],
|
||||
"custom/no-placeholder-comments": "error",
|
||||
"no-warning-comments": [
|
||||
"error",
|
||||
{ terms: ["fixme"] },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ["**/*.html"],
|
||||
plugins: {
|
||||
"@html-eslint": htmlEslint,
|
||||
"custom": customRules,
|
||||
},
|
||||
languageOptions: {
|
||||
parser: htmlParser,
|
||||
},
|
||||
rules: {
|
||||
"@html-eslint/require-title": "error",
|
||||
"@html-eslint/require-meta-charset": "error",
|
||||
"@html-eslint/require-meta-description": "error",
|
||||
"@html-eslint/require-meta-viewport": "error",
|
||||
"@html-eslint/require-open-graph-protocol": [
|
||||
"error",
|
||||
[
|
||||
"og:type",
|
||||
"og:title",
|
||||
"og:description",
|
||||
],
|
||||
],
|
||||
"custom/no-inline-script": "error",
|
||||
"custom/require-webmanifest": "error",
|
||||
},
|
||||
}
|
||||
);
|
||||
+2
-1
@@ -3,7 +3,8 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>mkstack</title>
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<link rel="manifest" href="/manifest.webmanifest">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
Generated
+4144
-3176
File diff suppressed because it is too large.
Load diff
+23
-12
@@ -5,16 +5,16 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "npm i && vite",
|
||||
"build": "npm i && vite build",
|
||||
"build:dev": "npm i && vite build --mode development",
|
||||
"ci": "npm i && tsc --noEmit && vite build",
|
||||
"lint": "npm i && eslint .",
|
||||
"preview": "npm i && vite preview"
|
||||
"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",
|
||||
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource-variable/inter": "^5.2.6",
|
||||
"@getalby/sdk": "^5.1.1",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.44.0",
|
||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.1",
|
||||
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
|
||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
||||
@@ -43,31 +43,40 @@
|
||||
"@radix-ui/react-toggle-group": "^1.1.0",
|
||||
"@radix-ui/react-tooltip": "^1.1.4",
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
"@unhead/react": "^2.0.10",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.0.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"input-otp": "^1.2.4",
|
||||
"lucide-react": "^0.462.0",
|
||||
"next-themes": "^0.3.0",
|
||||
"lucide-react": "^0.542.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",
|
||||
"@html-eslint/eslint-plugin": "^0.41.0",
|
||||
"@html-eslint/parser": "^0.41.0",
|
||||
"@tailwindcss/typography": "^0.5.15",
|
||||
"@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",
|
||||
@@ -76,10 +85,12 @@
|
||||
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.9",
|
||||
"globals": "^15.9.0",
|
||||
"jsdom": "^26.1.0",
|
||||
"postcss": "^8.4.47",
|
||||
"tailwindcss": "^3.4.11",
|
||||
"typescript": "^5.5.3",
|
||||
"typescript-eslint": "^8.0.1",
|
||||
"vite": "^5.4.1"
|
||||
"vite": "^6.3.5",
|
||||
"vitest": "^3.1.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/* /index.html 200
|
||||
-32
@@ -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
@@ -1,42 +0,0 @@
|
||||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { test } from 'vitest';
|
||||
|
||||
import App from './App';
|
||||
|
||||
test('App', () => {
|
||||
render(<App />);
|
||||
})
|
||||
+44
-21
@@ -1,17 +1,24 @@
|
||||
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";
|
||||
// NOTE: This file should normally not be modified unless you are adding a new provider.
|
||||
// To add new routes, edit the AppRouter.tsx file.
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { createHead, UnheadProvider } from '@unhead/react/client';
|
||||
import { InferSeoMetaPlugin } from '@unhead/addons';
|
||||
import { Suspense } from 'react';
|
||||
import NostrProvider from '@/components/NostrProvider';
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { NostrLoginProvider } from '@nostrify/react/login';
|
||||
import { AppProvider } from '@/components/AppProvider';
|
||||
import { NWCProvider } from '@/contexts/NWCContext';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
// AI: do not modify this relay list
|
||||
const defaultRelays = [
|
||||
'wss://relay.damus.io',
|
||||
'wss://relay.nostr.band',
|
||||
'wss://ditto.pub/relay',
|
||||
];
|
||||
const head = createHead({
|
||||
plugins: [
|
||||
InferSeoMetaPlugin(),
|
||||
],
|
||||
});
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
@@ -23,22 +30,38 @@ const queryClient = new QueryClient({
|
||||
},
|
||||
});
|
||||
|
||||
// NOTE: This file should normally not be modified unless you are adding a new provider.
|
||||
// To add new routes, edit the AppRouter.tsx file.
|
||||
const defaultConfig: AppConfig = {
|
||||
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 (
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider relays={defaultRelays}>
|
||||
<UnheadProvider head={head}>
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Sonner />
|
||||
<AppRouter />
|
||||
</TooltipProvider>
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<NWCProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</NWCProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</QueryClientProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</AppProvider>
|
||||
</UnheadProvider>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
import { BrowserRouter, Route, Routes } from "react-router-dom";
|
||||
import { ScrollToTop } from "./components/ScrollToTop";
|
||||
|
||||
import Index from "./pages/Index";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import { AdminDashboard } from "./pages/AdminDashboard";
|
||||
import NotFound from "./pages/NotFound";
|
||||
|
||||
export function AppRouter() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<ScrollToTop />
|
||||
<Routes>
|
||||
<Route path="/" element={<Index />} />
|
||||
{/* Admin dashboard route - must come before NIP-19 route */}
|
||||
<Route path="/admin" element={<AdminDashboard />} />
|
||||
{/* 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>
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { Shield } from 'lucide-react';
|
||||
|
||||
// Get admin npub from environment variable
|
||||
const ADMIN_NPUB = import.meta.env.VITE_ADMIN_NPUB;
|
||||
|
||||
export function AdminDashboardLink() {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Only show admin link if user is the configured admin
|
||||
if (!user || !ADMIN_NPUB) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let adminPubkey: string = '';
|
||||
try {
|
||||
const decoded = nip19.decode(ADMIN_NPUB);
|
||||
// @ts-expect-error - TypeScript has issues with nostr-tools type inference
|
||||
if (decoded.type === 'npub') {
|
||||
adminPubkey = decoded.data as unknown as string;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Only show if current user is the admin
|
||||
if (user.pubkey !== adminPubkey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<a href="/admin" className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4" />
|
||||
Site Admin
|
||||
</a>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { ReactNode, useEffect } from 'react';
|
||||
import { z } from 'zod';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
|
||||
|
||||
interface AppProviderProps {
|
||||
children: ReactNode;
|
||||
/** Application storage key */
|
||||
storageKey: string;
|
||||
/** Default app configuration */
|
||||
defaultConfig: AppConfig;
|
||||
/** Optional list of preset relays to display in the RelaySelector */
|
||||
presetRelays?: { name: string; url: string }[];
|
||||
}
|
||||
|
||||
// Zod schema for AppConfig validation
|
||||
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
|
||||
theme: z.enum(['dark', 'light', 'system']),
|
||||
relayUrl: z.string().url(),
|
||||
});
|
||||
|
||||
export function AppProvider(props: AppProviderProps) {
|
||||
const {
|
||||
children,
|
||||
storageKey,
|
||||
defaultConfig,
|
||||
presetRelays,
|
||||
} = props;
|
||||
|
||||
// App configuration state with localStorage persistence
|
||||
const [config, setConfig] = useLocalStorage<AppConfig>(
|
||||
storageKey,
|
||||
defaultConfig,
|
||||
{
|
||||
serialize: JSON.stringify,
|
||||
deserialize: (value: string) => {
|
||||
const parsed = JSON.parse(value);
|
||||
return AppConfigSchema.parse(parsed);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Generic config updater with callback pattern
|
||||
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
|
||||
setConfig(updater);
|
||||
};
|
||||
|
||||
const appContextValue: AppContextType = {
|
||||
config,
|
||||
updateConfig,
|
||||
presetRelays,
|
||||
};
|
||||
|
||||
// Apply theme effects to document
|
||||
useApplyTheme(config.theme);
|
||||
|
||||
return (
|
||||
<AppContext.Provider value={appContextValue}>
|
||||
{children}
|
||||
</AppContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to apply theme changes to the document root
|
||||
*/
|
||||
function useApplyTheme(theme: Theme) {
|
||||
useEffect(() => {
|
||||
const root = window.document.documentElement;
|
||||
|
||||
root.classList.remove('light', 'dark');
|
||||
|
||||
if (theme === 'system') {
|
||||
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
.matches
|
||||
? 'dark'
|
||||
: 'light';
|
||||
|
||||
root.classList.add(systemTheme);
|
||||
return;
|
||||
}
|
||||
|
||||
root.classList.add(theme);
|
||||
}, [theme]);
|
||||
|
||||
// Handle system theme changes when theme is set to "system"
|
||||
useEffect(() => {
|
||||
if (theme !== 'system') return;
|
||||
|
||||
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
|
||||
const handleChange = () => {
|
||||
const root = window.document.documentElement;
|
||||
root.classList.remove('light', 'dark');
|
||||
|
||||
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
|
||||
root.classList.add(systemTheme);
|
||||
};
|
||||
|
||||
mediaQuery.addEventListener('change', handleChange);
|
||||
return () => mediaQuery.removeEventListener('change', handleChange);
|
||||
}, [theme]);
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Loader2, Upload } from 'lucide-react';
|
||||
import { NSchema as n, type NostrMetadata } from '@nostrify/nostrify';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useUploadFile } from '@/hooks/useUploadFile';
|
||||
|
||||
export const EditProfileForm: React.FC = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { user, metadata } = useCurrentUser();
|
||||
const { mutateAsync: publishEvent, isPending } = useNostrPublish();
|
||||
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||
const { toast } = useToast();
|
||||
|
||||
// Initialize the form with default values
|
||||
const form = useForm<NostrMetadata>({
|
||||
resolver: zodResolver(n.metadata()),
|
||||
defaultValues: {
|
||||
name: '',
|
||||
about: '',
|
||||
picture: '',
|
||||
banner: '',
|
||||
website: '',
|
||||
nip05: '',
|
||||
bot: false,
|
||||
},
|
||||
});
|
||||
|
||||
// Update form values when user data is loaded
|
||||
useEffect(() => {
|
||||
if (metadata) {
|
||||
form.reset({
|
||||
name: metadata.name || '',
|
||||
about: metadata.about || '',
|
||||
picture: metadata.picture || '',
|
||||
banner: metadata.banner || '',
|
||||
website: metadata.website || '',
|
||||
nip05: metadata.nip05 || '',
|
||||
bot: metadata.bot || false,
|
||||
});
|
||||
}
|
||||
}, [metadata, form]);
|
||||
|
||||
// Handle file uploads for profile picture and banner
|
||||
const uploadPicture = async (file: File, field: 'picture' | 'banner') => {
|
||||
try {
|
||||
// The first tuple in the array contains the URL
|
||||
const [[_, url]] = await uploadFile(file);
|
||||
form.setValue(field, url);
|
||||
toast({
|
||||
title: 'Success',
|
||||
description: `${field === 'picture' ? 'Profile picture' : 'Banner'} uploaded successfully`,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(`Failed to upload ${field}:`, error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: `Failed to upload ${field === 'picture' ? 'profile picture' : 'banner'}. Please try again.`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const onSubmit = async (values: NostrMetadata) => {
|
||||
if (!user) {
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'You must be logged in to update your profile',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Combine existing metadata with new values
|
||||
const data = { ...metadata, ...values };
|
||||
|
||||
// Clean up empty values
|
||||
for (const key in data) {
|
||||
if (data[key] === '') {
|
||||
delete data[key];
|
||||
}
|
||||
}
|
||||
|
||||
// Publish the metadata event (kind 0)
|
||||
await publishEvent({
|
||||
kind: 0,
|
||||
content: JSON.stringify(data),
|
||||
});
|
||||
|
||||
// Invalidate queries to refresh the data
|
||||
queryClient.invalidateQueries({ queryKey: ['logins'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['author', user.pubkey] });
|
||||
|
||||
toast({
|
||||
title: 'Success',
|
||||
description: 'Your profile has been updated',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to update profile:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to update your profile. Please try again.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Your name" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
This is your display name that will be displayed to others.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="about"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Bio</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
placeholder="Tell others about yourself"
|
||||
className="resize-none"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
A short description about yourself.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="picture"
|
||||
render={({ field }) => (
|
||||
<ImageUploadField
|
||||
field={field}
|
||||
label="Profile Picture"
|
||||
placeholder="https://example.com/profile.jpg"
|
||||
description="URL to your profile picture. You can upload an image or provide a URL."
|
||||
previewType="square"
|
||||
onUpload={(file) => uploadPicture(file, 'picture')}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="banner"
|
||||
render={({ field }) => (
|
||||
<ImageUploadField
|
||||
field={field}
|
||||
label="Banner Image"
|
||||
placeholder="https://example.com/banner.jpg"
|
||||
description="URL to a wide banner image for your profile. You can upload an image or provide a URL."
|
||||
previewType="wide"
|
||||
onUpload={(file) => uploadPicture(file, 'banner')}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="website"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Website</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="https://yourwebsite.com" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Your personal website or social media link.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="nip05"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>NIP-05 Identifier</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="[email protected]" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Your verified Nostr identifier.
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="bot"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<FormLabel className="text-base">Bot Account</FormLabel>
|
||||
<FormDescription>
|
||||
Mark this account as automated or a bot.
|
||||
</FormDescription>
|
||||
</div>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full md:w-auto"
|
||||
disabled={isPending || isUploading}
|
||||
>
|
||||
{(isPending || isUploading) && (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
Save Profile
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
// Reusable component for image upload fields
|
||||
interface ImageUploadFieldProps {
|
||||
field: {
|
||||
value: string | undefined;
|
||||
onChange: (value: string) => void;
|
||||
name: string;
|
||||
onBlur: () => void;
|
||||
};
|
||||
label: string;
|
||||
placeholder: string;
|
||||
description: string;
|
||||
previewType: 'square' | 'wide';
|
||||
onUpload: (file: File) => void;
|
||||
}
|
||||
|
||||
const ImageUploadField: React.FC<ImageUploadFieldProps> = ({
|
||||
field,
|
||||
label,
|
||||
placeholder,
|
||||
description,
|
||||
previewType,
|
||||
onUpload,
|
||||
}) => {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
return (
|
||||
<FormItem>
|
||||
<FormLabel>{label}</FormLabel>
|
||||
<div className="flex flex-col gap-2">
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder={placeholder}
|
||||
name={field.name}
|
||||
value={field.value ?? ''}
|
||||
onChange={e => field.onChange(e.target.value)}
|
||||
onBlur={field.onBlur}
|
||||
/>
|
||||
</FormControl>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="file"
|
||||
ref={fileInputRef}
|
||||
accept="image/*"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
onUpload(file);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload className="h-4 w-4 mr-2" />
|
||||
Upload Image
|
||||
</Button>
|
||||
{field.value && (
|
||||
<div className={`h-10 ${previewType === 'square' ? 'w-10' : 'w-24'} rounded overflow-hidden`}>
|
||||
<img
|
||||
src={field.value}
|
||||
alt={`${label} preview`}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<FormDescription>
|
||||
{description}
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
);
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,54 @@
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify';
|
||||
import { NostrContext } from '@nostrify/react';
|
||||
import React, { useRef } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
|
||||
interface NostrProviderProps {
|
||||
children: React.ReactNode;
|
||||
relays: string[];
|
||||
}
|
||||
|
||||
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
const { children, relays } = props;
|
||||
const { children } = props;
|
||||
const { config, presetRelays } = useAppContext();
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Create NPool instance only once
|
||||
const pool = useRef<NPool | undefined>(undefined);
|
||||
|
||||
// Use refs so the pool always has the latest data
|
||||
const relayUrl = useRef<string>(config.relayUrl);
|
||||
|
||||
// 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: string) {
|
||||
return new NRelay1(url);
|
||||
},
|
||||
reqRouter(filters) {
|
||||
return new Map(relays.map((url) => [url, filters]));
|
||||
return new Map([[relayUrl.current, filters]]);
|
||||
},
|
||||
eventRouter(_event: NostrEvent) {
|
||||
return relays;
|
||||
// Publish to the selected relay
|
||||
const allRelays = new Set<string>([relayUrl.current]);
|
||||
|
||||
// Also publish to the preset relays, capped to 5
|
||||
for (const { url } of (presetRelays ?? [])) {
|
||||
allRelays.add(url);
|
||||
|
||||
if (allRelays.size >= 5) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return [...allRelays];
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { NoteContent } from './NoteContent';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
describe('NoteContent', () => {
|
||||
it('linkifies URLs in kind 1 events', () => {
|
||||
const event: NostrEvent = {
|
||||
id: 'test-id',
|
||||
pubkey: 'test-pubkey',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 1,
|
||||
tags: [],
|
||||
content: 'Check out this link: https://example.com',
|
||||
sig: 'test-sig',
|
||||
};
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<NoteContent event={event} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const link = screen.getByRole('link', { name: 'https://example.com' });
|
||||
expect(link).toBeInTheDocument();
|
||||
expect(link).toHaveAttribute('href', 'https://example.com');
|
||||
expect(link).toHaveAttribute('target', '_blank');
|
||||
});
|
||||
|
||||
it('linkifies URLs in kind 1111 events (comments)', () => {
|
||||
const event: NostrEvent = {
|
||||
id: 'test-comment-id',
|
||||
pubkey: 'test-pubkey',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 1111,
|
||||
tags: [
|
||||
['a', '30040:pubkey:identifier'],
|
||||
['k', '30040'],
|
||||
['p', 'pubkey'],
|
||||
],
|
||||
content: 'I think the log events should be different kind numbers instead of having a `log-type` tag. That way you can use normal Nostr filters to filter the log types. Also, the `note` type should just b a kind 1111: https://nostrbook.dev/kinds/1111',
|
||||
sig: 'test-sig',
|
||||
};
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<NoteContent event={event} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const link = screen.getByRole('link', { name: 'https://nostrbook.dev/kinds/1111' });
|
||||
expect(link).toBeInTheDocument();
|
||||
expect(link).toHaveAttribute('href', 'https://nostrbook.dev/kinds/1111');
|
||||
expect(link).toHaveAttribute('target', '_blank');
|
||||
});
|
||||
|
||||
it('handles text without URLs correctly', () => {
|
||||
const event: NostrEvent = {
|
||||
id: 'test-id',
|
||||
pubkey: 'test-pubkey',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 1111,
|
||||
tags: [],
|
||||
content: 'This is just plain text without any links.',
|
||||
sig: 'test-sig',
|
||||
};
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<NoteContent event={event} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('This is just plain text without any links.')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('link')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders hashtags as links', () => {
|
||||
const event: NostrEvent = {
|
||||
id: 'test-id',
|
||||
pubkey: 'test-pubkey',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 1,
|
||||
tags: [],
|
||||
content: 'This is a post about #nostr and #bitcoin development.',
|
||||
sig: 'test-sig',
|
||||
};
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<NoteContent event={event} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const nostrHashtag = screen.getByRole('link', { name: '#nostr' });
|
||||
const bitcoinHashtag = screen.getByRole('link', { name: '#bitcoin' });
|
||||
|
||||
expect(nostrHashtag).toBeInTheDocument();
|
||||
expect(bitcoinHashtag).toBeInTheDocument();
|
||||
expect(nostrHashtag).toHaveAttribute('href', '/t/nostr');
|
||||
expect(bitcoinHashtag).toHaveAttribute('href', '/t/bitcoin');
|
||||
});
|
||||
|
||||
it('generates deterministic names for users without metadata and styles them differently', () => {
|
||||
// Use a valid npub for testing
|
||||
const event: NostrEvent = {
|
||||
id: 'test-id',
|
||||
pubkey: 'test-pubkey',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 1,
|
||||
tags: [],
|
||||
content: `Mentioning nostr:npub1zg69v7ys40x77y352eufp27daufrg4ncjz4ummcjx3t83y9tehhsqepuh0`,
|
||||
sig: 'test-sig',
|
||||
};
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<NoteContent event={event} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// The mention should be rendered with a deterministic name
|
||||
const mention = screen.getByRole('link');
|
||||
expect(mention).toBeInTheDocument();
|
||||
|
||||
// Should have muted styling for generated names (gray instead of blue)
|
||||
expect(mention).toHaveClass('text-gray-500');
|
||||
expect(mention).not.toHaveClass('text-blue-500');
|
||||
|
||||
// The text should start with @ and contain a generated name (not a truncated npub)
|
||||
const linkText = mention.textContent;
|
||||
expect(linkText).not.toMatch(/^@npub1/); // Should not be a truncated npub
|
||||
expect(linkText).toEqual("@Swift Falcon");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import { useMemo } from 'react';
|
||||
import { type NostrEvent } from '@nostrify/nostrify';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface NoteContentProps {
|
||||
event: NostrEvent;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** Parses content of text note events so that URLs and hashtags are linkified. */
|
||||
export function NoteContent({
|
||||
event,
|
||||
className,
|
||||
}: NoteContentProps) {
|
||||
// Process the content to render mentions, links, etc.
|
||||
const content = useMemo(() => {
|
||||
const text = event.content;
|
||||
|
||||
// Regex to find URLs, Nostr references, and hashtags
|
||||
const regex = /(https?:\/\/[^\s]+)|nostr:(npub1|note1|nprofile1|nevent1)([023456789acdefghjklmnpqrstuvwxyz]+)|(#\w+)/g;
|
||||
|
||||
const parts: React.ReactNode[] = [];
|
||||
let lastIndex = 0;
|
||||
let match: RegExpExecArray | null;
|
||||
let keyCounter = 0;
|
||||
|
||||
while ((match = regex.exec(text)) !== null) {
|
||||
const [fullMatch, url, nostrPrefix, nostrData, hashtag] = match;
|
||||
const index = match.index;
|
||||
|
||||
// Add text before this match
|
||||
if (index > lastIndex) {
|
||||
parts.push(text.substring(lastIndex, index));
|
||||
}
|
||||
|
||||
if (url) {
|
||||
// Handle URLs
|
||||
parts.push(
|
||||
<a
|
||||
key={`url-${keyCounter++}`}
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-500 hover:underline"
|
||||
>
|
||||
{url}
|
||||
</a>
|
||||
);
|
||||
} else if (nostrPrefix && nostrData) {
|
||||
// Handle Nostr references
|
||||
try {
|
||||
const nostrId = `${nostrPrefix}${nostrData}`;
|
||||
const decoded = nip19.decode(nostrId);
|
||||
|
||||
if (decoded.type === 'npub') {
|
||||
const pubkey = decoded.data;
|
||||
parts.push(
|
||||
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
|
||||
);
|
||||
} else {
|
||||
// For other types, just show as a link
|
||||
parts.push(
|
||||
<Link
|
||||
key={`nostr-${keyCounter++}`}
|
||||
to={`/${nostrId}`}
|
||||
className="text-blue-500 hover:underline"
|
||||
>
|
||||
{fullMatch}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
// If decoding fails, just render as text
|
||||
parts.push(fullMatch);
|
||||
}
|
||||
} else if (hashtag) {
|
||||
// Handle hashtags
|
||||
const tag = hashtag.slice(1); // Remove the #
|
||||
parts.push(
|
||||
<Link
|
||||
key={`hashtag-${keyCounter++}`}
|
||||
to={`/t/${tag}`}
|
||||
className="text-blue-500 hover:underline"
|
||||
>
|
||||
{hashtag}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
lastIndex = index + fullMatch.length;
|
||||
}
|
||||
|
||||
// Add any remaining text
|
||||
if (lastIndex < text.length) {
|
||||
parts.push(text.substring(lastIndex));
|
||||
}
|
||||
|
||||
// If no special content was found, just use the plain text
|
||||
if (parts.length === 0) {
|
||||
parts.push(text);
|
||||
}
|
||||
|
||||
return parts;
|
||||
}, [event]);
|
||||
|
||||
return (
|
||||
<div className={cn("whitespace-pre-wrap break-words", className)}>
|
||||
{content.length > 0 ? content : event.content}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Helper component to display user mentions
|
||||
function NostrMention({ pubkey }: { pubkey: string }) {
|
||||
const author = useAuthor(pubkey);
|
||||
const npub = nip19.npubEncode(pubkey);
|
||||
const hasRealName = !!author.data?.metadata?.name;
|
||||
const displayName = author.data?.metadata?.name ?? genUserName(pubkey);
|
||||
|
||||
return (
|
||||
<Link
|
||||
to={`/${npub}`}
|
||||
className={cn(
|
||||
"font-medium hover:underline",
|
||||
hasRealName
|
||||
? "text-blue-500"
|
||||
: "text-gray-500 hover:text-gray-700"
|
||||
)}
|
||||
>
|
||||
@{displayName}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@/components/ui/command";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { useState } from "react";
|
||||
import { useAppContext } from "@/hooks/useAppContext";
|
||||
|
||||
interface RelaySelectorProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function RelaySelector(props: RelaySelectorProps) {
|
||||
const { className } = props;
|
||||
const { config, updateConfig, presetRelays = [] } = useAppContext();
|
||||
|
||||
const selectedRelay = config.relayUrl;
|
||||
const setSelectedRelay = (relay: string) => {
|
||||
updateConfig((current) => ({ ...current, relayUrl: relay }));
|
||||
};
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const [inputValue, setInputValue] = useState("");
|
||||
|
||||
const selectedOption = presetRelays.find((option) => option.url === selectedRelay);
|
||||
|
||||
// Function to normalize relay URL by adding wss:// if no protocol is present
|
||||
const normalizeRelayUrl = (url: string): string => {
|
||||
const trimmed = url.trim();
|
||||
if (!trimmed) return trimmed;
|
||||
|
||||
// Check if it already has a protocol
|
||||
if (trimmed.includes('://')) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
// Add wss:// prefix
|
||||
return `wss://${trimmed}`;
|
||||
};
|
||||
|
||||
// Handle adding a custom relay
|
||||
const handleAddCustomRelay = (url: string) => {
|
||||
setSelectedRelay?.(normalizeRelayUrl(url));
|
||||
setOpen(false);
|
||||
setInputValue("");
|
||||
};
|
||||
|
||||
// Check if input value looks like a valid relay URL
|
||||
const isValidRelayInput = (value: string): boolean => {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return false;
|
||||
|
||||
// Basic validation - should contain at least a domain-like structure
|
||||
const normalized = normalizeRelayUrl(trimmed);
|
||||
try {
|
||||
new URL(normalized);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
className={cn("justify-between", className)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Wifi className="h-4 w-4" />
|
||||
<span className="truncate">
|
||||
{selectedOption
|
||||
? selectedOption.name
|
||||
: selectedRelay
|
||||
? selectedRelay.replace(/^wss?:\/\//, '')
|
||||
: "Select relay..."
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[300px] p-0">
|
||||
<Command>
|
||||
<CommandInput
|
||||
placeholder="Search relays or type URL..."
|
||||
value={inputValue}
|
||||
onValueChange={setInputValue}
|
||||
/>
|
||||
<CommandList>
|
||||
<CommandEmpty>
|
||||
{inputValue && isValidRelayInput(inputValue) ? (
|
||||
<CommandItem
|
||||
onSelect={() => handleAddCustomRelay(inputValue)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">Add custom relay</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{normalizeRelayUrl(inputValue)}
|
||||
</span>
|
||||
</div>
|
||||
</CommandItem>
|
||||
) : (
|
||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
||||
{inputValue ? "Invalid relay URL" : "No relay found."}
|
||||
</div>
|
||||
)}
|
||||
</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{presetRelays
|
||||
.filter((option) =>
|
||||
!inputValue ||
|
||||
option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
|
||||
option.url.toLowerCase().includes(inputValue.toLowerCase())
|
||||
)
|
||||
.map((option) => (
|
||||
<CommandItem
|
||||
key={option.url}
|
||||
value={option.url}
|
||||
onSelect={(currentValue) => {
|
||||
setSelectedRelay(normalizeRelayUrl(currentValue));
|
||||
setOpen(false);
|
||||
setInputValue("");
|
||||
}}
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
selectedRelay === option.url ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">{option.name}</span>
|
||||
<span className="text-xs text-muted-foreground">{option.url}</span>
|
||||
</div>
|
||||
</CommandItem>
|
||||
))}
|
||||
{inputValue && isValidRelayInput(inputValue) && (
|
||||
<CommandItem
|
||||
onSelect={() => handleAddCustomRelay(inputValue)}
|
||||
className="cursor-pointer border-t"
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">Add custom relay</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{normalizeRelayUrl(inputValue)}
|
||||
</span>
|
||||
</div>
|
||||
</CommandItem>
|
||||
)}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
|
||||
export function ScrollToTop() {
|
||||
const { pathname } = useLocation();
|
||||
|
||||
useEffect(() => {
|
||||
window.scrollTo(0, 0);
|
||||
}, [pathname]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -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';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
DrawerTrigger,
|
||||
DrawerClose,
|
||||
} from '@/components/ui/drawer';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
|
||||
|
||||
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}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { ZapDialog } from '@/components/ZapDialog';
|
||||
import { useZaps } from '@/hooks/useZaps';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -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';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
Drawer,
|
||||
DrawerContent,
|
||||
DrawerDescription,
|
||||
DrawerHeader,
|
||||
DrawerTitle,
|
||||
DrawerTrigger,
|
||||
DrawerClose,
|
||||
} from '@/components/ui/drawer';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useZaps } from '@/hooks/useZaps';
|
||||
import { useWallet } from '@/hooks/useWallet';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
// 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 from 'react';
|
||||
import { ChevronDown, LogOut, UserPlus } from 'lucide-react';
|
||||
import { ChevronDown, LogOut, UserIcon, UserPlus, Wallet } from 'lucide-react';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -11,7 +10,10 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu.tsx';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
|
||||
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
import { WalletModal } from '@/components/WalletModal';
|
||||
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
interface AccountSwitcherProps {
|
||||
onAddAccountClick: () => void;
|
||||
@@ -22,21 +24,28 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
|
||||
|
||||
if (!currentUser) return null;
|
||||
|
||||
const getDisplayName = (account: Account): string => {
|
||||
return account.metadata.name ?? genUserName(account.pubkey);
|
||||
}
|
||||
|
||||
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'>
|
||||
<AvatarImage src={currentUser.metadata.picture} alt={currentUser.metadata.name} />
|
||||
<AvatarFallback>{currentUser.metadata.name?.charAt(0)}</AvatarFallback>
|
||||
<AvatarImage src={currentUser.metadata.picture} alt={getDisplayName(currentUser)} />
|
||||
<AvatarFallback>{getDisplayName(currentUser).charAt(0)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className='flex-1 text-left hidden md:block'>
|
||||
<p className='font-medium text-sm'>{currentUser.metadata.name}</p>
|
||||
<div className='flex-1 text-left hidden md:block truncate'>
|
||||
<p className='font-medium text-sm truncate'>{getDisplayName(currentUser)}</p>
|
||||
</div>
|
||||
<ChevronDown className='w-4 h-4 text-muted-foreground' />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
|
||||
<div className='font-medium text-sm px-2 py-1.5'>Switch Relay</div>
|
||||
<RelaySelector className="w-full" />
|
||||
<DropdownMenuSeparator />
|
||||
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
|
||||
{otherUsers.map((user) => (
|
||||
<DropdownMenuItem
|
||||
@@ -45,16 +54,25 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
|
||||
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
|
||||
>
|
||||
<Avatar className='w-8 h-8'>
|
||||
<AvatarImage src={user.metadata.picture} alt={user.metadata.name} />
|
||||
<AvatarFallback>{user.metadata.name?.charAt(0)}</AvatarFallback>
|
||||
<AvatarImage src={user.metadata.picture} alt={getDisplayName(user)} />
|
||||
<AvatarFallback>{getDisplayName(user)?.charAt(0) || <UserIcon />}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className='flex-1'>
|
||||
<p className='text-sm font-medium'>{user.metadata.name}</p>
|
||||
<div className='flex-1 truncate'>
|
||||
<p className='text-sm font-medium'>{getDisplayName(user)}</p>
|
||||
</div>
|
||||
{user.id === currentUser.id && <div className='w-2 h-2 rounded-full bg-primary'></div>}
|
||||
</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'
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
// 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 { User } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { User, UserPlus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button.tsx';
|
||||
import LoginDialog from './LoginDialog';
|
||||
import SignupDialog from './SignupDialog';
|
||||
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
|
||||
import { AccountSwitcher } from './AccountSwitcher';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export function LoginArea() {
|
||||
export interface LoginAreaProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function LoginArea({ className }: LoginAreaProps) {
|
||||
const { currentUser } = useLoggedInAccounts();
|
||||
const [loginDialogOpen, setLoginDialogOpen] = useState(false);
|
||||
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
|
||||
@@ -20,22 +25,31 @@ export function LoginArea() {
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={cn("inline-flex items-center justify-center", className)}>
|
||||
{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>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)}
|
||||
/>
|
||||
@@ -44,6 +58,6 @@ export function LoginArea() {
|
||||
isOpen={signupDialogOpen}
|
||||
onClose={() => setSignupDialogOpen(false)}
|
||||
/>
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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, { useEffect, useRef, useState } from 'react';
|
||||
import { Shield, Upload } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button.tsx';
|
||||
import { Input } from '@/components/ui/input.tsx';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog.tsx';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs.tsx';
|
||||
import React, { useRef, useState, useEffect } from 'react';
|
||||
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
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;
|
||||
@@ -1,160 +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 React, { useState, useEffect, useRef } from 'react';
|
||||
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, Lock, CheckCircle, Upload, Globe, FileSignature, Wand2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useUploadFile } from '@/hooks/useUploadFile';
|
||||
import { generateSecretKey, nip19 } from 'nostr-tools';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
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 [nsecKey, setNsecKey] = useState('');
|
||||
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 private key
|
||||
const privateKey = generateSecretKey();
|
||||
|
||||
// Convert to nsec format
|
||||
const nsec = nip19.nsecEncode(privateKey);
|
||||
setNsecKey(nsec);
|
||||
setStep('download');
|
||||
} catch (error) {
|
||||
console.error('Failed to generate key:', error);
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Failed to generate key. Please try again.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
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([nsecKey], { 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 = () => {
|
||||
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'>{nsecKey}</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>
|
||||
|
||||
@@ -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';
|
||||
import { useComments } from '@/hooks/useComments';
|
||||
import { CommentForm } from './CommentForm';
|
||||
import { NoteContent } from '@/components/NoteContent';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import { DropdownMenu, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import { MessageSquare, ChevronDown, ChevronRight, MoreHorizontal } from 'lucide-react';
|
||||
import { formatDistanceToNow } from 'date-fns';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
|
||||
interface CommentProps {
|
||||
root: NostrEvent | URL;
|
||||
comment: NostrEvent;
|
||||
depth?: number;
|
||||
maxDepth?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: CommentProps) {
|
||||
const [showReplyForm, setShowReplyForm] = useState(false);
|
||||
const [showReplies, setShowReplies] = useState(depth < 2); // Auto-expand first 2 levels
|
||||
|
||||
const author = useAuthor(comment.pubkey);
|
||||
const { data: commentsData } = useComments(root, limit);
|
||||
|
||||
const metadata = author.data?.metadata;
|
||||
const displayName = metadata?.name ?? genUserName(comment.pubkey)
|
||||
const timeAgo = formatDistanceToNow(new Date(comment.created_at * 1000), { addSuffix: true });
|
||||
|
||||
// Get direct replies to this comment
|
||||
const replies = commentsData?.getDirectReplies(comment.id) || [];
|
||||
const hasReplies = replies.length > 0;
|
||||
|
||||
return (
|
||||
<div className={`space-y-3 ${depth > 0 ? 'ml-6 border-l-2 border-muted pl-4' : ''}`}>
|
||||
<Card className="bg-card/50">
|
||||
<CardContent className="p-4">
|
||||
<div className="space-y-3">
|
||||
{/* Comment Header */}
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center space-x-3">
|
||||
<Link to={`/${nip19.npubEncode(comment.pubkey)}`}>
|
||||
<Avatar className="h-8 w-8 hover:ring-2 hover:ring-primary/30 transition-all cursor-pointer">
|
||||
<AvatarImage src={metadata?.picture} />
|
||||
<AvatarFallback className="text-xs">
|
||||
{displayName.charAt(0)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
</Link>
|
||||
<div>
|
||||
<Link
|
||||
to={`/${nip19.npubEncode(comment.pubkey)}`}
|
||||
className="font-medium text-sm hover:text-primary transition-colors"
|
||||
>
|
||||
{displayName}
|
||||
</Link>
|
||||
<p className="text-xs text-muted-foreground">{timeAgo}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Comment Content */}
|
||||
<div className="text-sm">
|
||||
<NoteContent event={comment} className="text-sm" />
|
||||
</div>
|
||||
|
||||
{/* Comment Actions */}
|
||||
<div className="flex items-center justify-between pt-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setShowReplyForm(!showReplyForm)}
|
||||
className="h-8 px-2 text-xs"
|
||||
>
|
||||
<MessageSquare className="h-3 w-3 mr-1" />
|
||||
Reply
|
||||
</Button>
|
||||
|
||||
{hasReplies && (
|
||||
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 px-2 text-xs">
|
||||
{showReplies ? (
|
||||
<ChevronDown className="h-3 w-3 mr-1" />
|
||||
) : (
|
||||
<ChevronRight className="h-3 w-3 mr-1" />
|
||||
)}
|
||||
{replies.length} {replies.length === 1 ? 'reply' : 'replies'}
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
</Collapsible>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Comment menu */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2 text-xs"
|
||||
aria-label="Comment options"
|
||||
>
|
||||
<MoreHorizontal className="h-3 w-3" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Reply Form */}
|
||||
{showReplyForm && (
|
||||
<div className="ml-6">
|
||||
<CommentForm
|
||||
root={root}
|
||||
reply={comment}
|
||||
onSuccess={() => setShowReplyForm(false)}
|
||||
placeholder="Write a reply..."
|
||||
compact
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Replies */}
|
||||
{hasReplies && (
|
||||
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
|
||||
<CollapsibleContent className="space-y-3">
|
||||
{replies.map((reply) => (
|
||||
<Comment
|
||||
key={reply.id}
|
||||
root={root}
|
||||
comment={reply}
|
||||
depth={depth + 1}
|
||||
maxDepth={maxDepth}
|
||||
limit={limit}
|
||||
/>
|
||||
))}
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { usePostComment } from '@/hooks/usePostComment';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { NostrEvent } from '@nostrify/nostrify';
|
||||
import { MessageSquare, Send } from 'lucide-react';
|
||||
|
||||
interface CommentFormProps {
|
||||
root: NostrEvent | URL;
|
||||
reply?: NostrEvent | URL;
|
||||
onSuccess?: () => void;
|
||||
placeholder?: string;
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
export function CommentForm({
|
||||
root,
|
||||
reply,
|
||||
onSuccess,
|
||||
placeholder = "Write a comment...",
|
||||
compact = false
|
||||
}: CommentFormProps) {
|
||||
const [content, setContent] = useState('');
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: postComment, isPending } = usePostComment();
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!content.trim() || !user) return;
|
||||
|
||||
postComment(
|
||||
{ content: content.trim(), root, reply },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setContent('');
|
||||
onSuccess?.();
|
||||
},
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<Card className={compact ? "border-dashed" : ""}>
|
||||
<CardContent className={compact ? "p-4" : "p-6"}>
|
||||
<div className="text-center space-y-4">
|
||||
<div className="flex items-center justify-center space-x-2 text-muted-foreground">
|
||||
<MessageSquare className="h-5 w-5" />
|
||||
<span>Sign in to {reply ? 'reply' : 'comment'}</span>
|
||||
</div>
|
||||
<LoginArea />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className={compact ? "border-dashed" : ""}>
|
||||
<CardContent className={compact ? "p-4" : "p-6"}>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<Textarea
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
placeholder={placeholder}
|
||||
className={compact ? "min-h-[80px]" : "min-h-[100px]"}
|
||||
disabled={isPending}
|
||||
/>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{reply ? 'Replying to comment' : 'Adding to the discussion'}
|
||||
</span>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!content.trim() || isPending}
|
||||
size={compact ? "sm" : "default"}
|
||||
>
|
||||
<Send className="h-4 w-4 mr-2" />
|
||||
{isPending ? 'Posting...' : (reply ? 'Reply' : 'Comment')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useComments } from '@/hooks/useComments';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { MessageSquare } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { CommentForm } from './CommentForm';
|
||||
import { Comment } from './Comment';
|
||||
|
||||
interface CommentsSectionProps {
|
||||
root: NostrEvent | URL;
|
||||
title?: string;
|
||||
emptyStateMessage?: string;
|
||||
emptyStateSubtitle?: string;
|
||||
className?: string;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export function CommentsSection({
|
||||
root,
|
||||
title = "Comments",
|
||||
emptyStateMessage = "No comments yet",
|
||||
emptyStateSubtitle = "Be the first to share your thoughts!",
|
||||
className,
|
||||
limit = 500,
|
||||
}: CommentsSectionProps) {
|
||||
const { data: commentsData, isLoading, error } = useComments(root, limit);
|
||||
const comments = commentsData?.topLevelComments || [];
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Card className="rounded-none sm:rounded-lg mx-0 sm:mx-0">
|
||||
<CardContent className="px-2 py-6 sm:p-6">
|
||||
<div className="text-center text-muted-foreground">
|
||||
<MessageSquare className="h-8 w-8 mx-auto mb-2 opacity-50" />
|
||||
<p>Failed to load comments</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className={cn("rounded-none sm:rounded-lg mx-0 sm:mx-0", className)}>
|
||||
<CardHeader className="px-2 pt-6 pb-4 sm:p-6">
|
||||
<CardTitle className="flex items-center space-x-2">
|
||||
<MessageSquare className="h-5 w-5" />
|
||||
<span>{title}</span>
|
||||
{!isLoading && (
|
||||
<span className="text-sm font-normal text-muted-foreground">
|
||||
({comments.length})
|
||||
</span>
|
||||
)}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="px-2 pb-6 pt-4 sm:p-6 sm:pt-0 space-y-6">
|
||||
{/* Comment Form */}
|
||||
<CommentForm root={root} />
|
||||
|
||||
{/* Comments List */}
|
||||
{isLoading ? (
|
||||
<div className="space-y-4">
|
||||
{[...Array(3)].map((_, i) => (
|
||||
<Card key={i} className="bg-card/50">
|
||||
<CardContent className="p-4">
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center space-x-3">
|
||||
<Skeleton className="h-8 w-8 rounded-full" />
|
||||
<div className="space-y-1">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-3 w-16" />
|
||||
</div>
|
||||
</div>
|
||||
<Skeleton className="h-16 w-full" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
) : comments.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<MessageSquare className="h-12 w-12 mx-auto mb-4 opacity-30" />
|
||||
<p className="text-lg font-medium mb-2">{emptyStateMessage}</p>
|
||||
<p className="text-sm">{emptyStateSubtitle}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{comments.map((comment) => (
|
||||
<Comment
|
||||
key={comment.id}
|
||||
root={root}
|
||||
comment={comment}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import * as React from "react"
|
||||
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { buttonVariants } from "@/components/ui/button"
|
||||
import { buttonVariants } from "@/components/ui/button-variants"
|
||||
|
||||
const AlertDialog = AlertDialogPrimitive.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}
|
||||
/>
|
||||
))
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
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",
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -1,27 +1,8 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
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",
|
||||
},
|
||||
}
|
||||
)
|
||||
import { badgeVariants } from "./badge-variants"
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
@@ -33,4 +14,4 @@ function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
export { Badge }
|
||||
@@ -0,0 +1,30 @@
|
||||
import { cva } from "class-variance-authority"
|
||||
|
||||
export const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline:
|
||||
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-4 py-2",
|
||||
sm: "h-9 rounded-md px-3",
|
||||
lg: "h-11 rounded-md px-8",
|
||||
icon: "h-10 w-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -1,37 +1,9 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
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",
|
||||
},
|
||||
}
|
||||
)
|
||||
import { buttonVariants } from "./button-variants"
|
||||
|
||||
export interface ButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
|
||||
@@ -53,4 +25,4 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
||||
)
|
||||
Button.displayName = "Button"
|
||||
|
||||
export { Button, buttonVariants }
|
||||
export { Button }
|
||||
@@ -3,7 +3,7 @@ import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { DayPicker } from "react-day-picker";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { buttonVariants } from "@/components/ui/button-variants";
|
||||
|
||||
export type CalendarProps = React.ComponentProps<typeof DayPicker>;
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ const Command = React.forwardRef<
|
||||
))
|
||||
Command.displayName = CommandPrimitive.displayName
|
||||
|
||||
interface CommandDialogProps extends DialogProps {}
|
||||
type CommandDialogProps = DialogProps
|
||||
|
||||
const CommandDialog = ({ children, ...props }: CommandDialogProps) => {
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import * as React from "react"
|
||||
import {
|
||||
FieldPath,
|
||||
FieldValues,
|
||||
useFormContext,
|
||||
} from "react-hook-form"
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
|
||||
> = {
|
||||
name: TName
|
||||
}
|
||||
|
||||
export const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||
{} as FormFieldContextValue
|
||||
)
|
||||
|
||||
type FormItemContextValue = {
|
||||
id: string
|
||||
}
|
||||
|
||||
export const FormItemContext = React.createContext<FormItemContextValue>(
|
||||
{} as FormItemContextValue
|
||||
)
|
||||
|
||||
export const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext)
|
||||
const itemContext = React.useContext(FormItemContext)
|
||||
const { getFieldState, formState } = useFormContext()
|
||||
|
||||
const fieldState = getFieldState(fieldContext.name, formState)
|
||||
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>")
|
||||
}
|
||||
|
||||
const { id } = itemContext
|
||||
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
}
|
||||
}
|
||||
@@ -7,25 +7,14 @@ import {
|
||||
FieldPath,
|
||||
FieldValues,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
} from "react-hook-form"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { FormFieldContext, FormItemContext, useFormField } from "./form-utils"
|
||||
|
||||
const Form = FormProvider
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
|
||||
> = {
|
||||
name: TName
|
||||
}
|
||||
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||
{} as FormFieldContextValue
|
||||
)
|
||||
|
||||
const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
|
||||
@@ -39,37 +28,6 @@ const FormField = <
|
||||
)
|
||||
}
|
||||
|
||||
const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext)
|
||||
const itemContext = React.useContext(FormItemContext)
|
||||
const { getFieldState, formState } = useFormContext()
|
||||
|
||||
const fieldState = getFieldState(fieldContext.name, formState)
|
||||
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>")
|
||||
}
|
||||
|
||||
const { id } = itemContext
|
||||
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
}
|
||||
}
|
||||
|
||||
type FormItemContextValue = {
|
||||
id: string
|
||||
}
|
||||
|
||||
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||
{} as FormItemContextValue
|
||||
)
|
||||
|
||||
const FormItem = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
@@ -165,7 +123,6 @@ const FormMessage = React.forwardRef<
|
||||
FormMessage.displayName = "FormMessage"
|
||||
|
||||
export {
|
||||
useFormField,
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { cva } from "class-variance-authority"
|
||||
|
||||
export const navigationMenuTriggerStyle = cva(
|
||||
"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"
|
||||
)
|
||||
@@ -1,9 +1,9 @@
|
||||
import * as React from "react"
|
||||
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
|
||||
import { cva } from "class-variance-authority"
|
||||
import { ChevronDown } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { navigationMenuTriggerStyle } from "./navigation-menu-variants"
|
||||
|
||||
const NavigationMenu = React.forwardRef<
|
||||
React.ElementRef<typeof NavigationMenuPrimitive.Root>,
|
||||
@@ -40,10 +40,6 @@ NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName
|
||||
|
||||
const NavigationMenuItem = NavigationMenuPrimitive.Item
|
||||
|
||||
const navigationMenuTriggerStyle = cva(
|
||||
"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"
|
||||
)
|
||||
|
||||
const NavigationMenuTrigger = React.forwardRef<
|
||||
React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
|
||||
@@ -116,7 +112,6 @@ NavigationMenuIndicator.displayName =
|
||||
NavigationMenuPrimitive.Indicator.displayName
|
||||
|
||||
export {
|
||||
navigationMenuTriggerStyle,
|
||||
NavigationMenu,
|
||||
NavigationMenuList,
|
||||
NavigationMenuItem,
|
||||
|
||||
@@ -2,7 +2,8 @@ import * as React from "react"
|
||||
import { ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { ButtonProps, buttonVariants } from "@/components/ui/button"
|
||||
import { ButtonProps } from "@/components/ui/button"
|
||||
import { buttonVariants } from "@/components/ui/button-variants"
|
||||
|
||||
const Pagination = ({ className, ...props }: React.ComponentProps<"nav">) => (
|
||||
<nav
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import * as React from "react"
|
||||
import { cva } from "class-variance-authority"
|
||||
|
||||
export const SIDEBAR_COOKIE_NAME = "sidebar:state"
|
||||
export const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
|
||||
export const SIDEBAR_WIDTH = "16rem"
|
||||
export const SIDEBAR_WIDTH_MOBILE = "18rem"
|
||||
export const SIDEBAR_WIDTH_ICON = "3rem"
|
||||
export const SIDEBAR_KEYBOARD_SHORTCUT = "b"
|
||||
|
||||
export type SidebarContext = {
|
||||
state: "expanded" | "collapsed"
|
||||
open: boolean
|
||||
setOpen: (open: boolean) => void
|
||||
openMobile: boolean
|
||||
setOpenMobile: (open: boolean) => void
|
||||
isMobile: boolean
|
||||
toggleSidebar: () => void
|
||||
}
|
||||
|
||||
export const SidebarContext = React.createContext<SidebarContext | null>(null)
|
||||
|
||||
export function useSidebar() {
|
||||
const context = React.useContext(SidebarContext)
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
export const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
sm: "h-7 text-xs",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { VariantProps, cva } from "class-variance-authority"
|
||||
import { VariantProps } from "class-variance-authority"
|
||||
import { PanelLeft } from "lucide-react"
|
||||
|
||||
import { useIsMobile } from "@/hooks/useIsMobile"
|
||||
@@ -16,34 +16,18 @@ import {
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip"
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar:state"
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
|
||||
const SIDEBAR_WIDTH = "16rem"
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem"
|
||||
const SIDEBAR_WIDTH_ICON = "3rem"
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
|
||||
|
||||
type SidebarContext = {
|
||||
state: "expanded" | "collapsed"
|
||||
open: boolean
|
||||
setOpen: (open: boolean) => void
|
||||
openMobile: boolean
|
||||
setOpenMobile: (open: boolean) => void
|
||||
isMobile: boolean
|
||||
toggleSidebar: () => void
|
||||
}
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContext | null>(null)
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext)
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
import {
|
||||
SIDEBAR_COOKIE_NAME,
|
||||
SIDEBAR_COOKIE_MAX_AGE,
|
||||
SIDEBAR_WIDTH,
|
||||
SIDEBAR_WIDTH_MOBILE,
|
||||
SIDEBAR_WIDTH_ICON,
|
||||
SIDEBAR_KEYBOARD_SHORTCUT,
|
||||
SidebarContext,
|
||||
useSidebar,
|
||||
sidebarMenuButtonVariants,
|
||||
type SidebarContext as SidebarContextType,
|
||||
} from "./sidebar-utils"
|
||||
|
||||
const SidebarProvider = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
@@ -114,7 +98,7 @@ const SidebarProvider = React.forwardRef<
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed"
|
||||
|
||||
const contextValue = React.useMemo<SidebarContext>(
|
||||
const contextValue = React.useMemo<SidebarContextType>(
|
||||
() => ({
|
||||
state,
|
||||
open,
|
||||
@@ -509,27 +493,7 @@ const SidebarMenuItem = React.forwardRef<
|
||||
))
|
||||
SidebarMenuItem.displayName = "SidebarMenuItem"
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
|
||||
outline:
|
||||
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 text-sm",
|
||||
sm: "h-7 text-xs",
|
||||
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
const SidebarMenuButton = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
@@ -757,5 +721,4 @@ export {
|
||||
SidebarRail,
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner } from "sonner"
|
||||
|
||||
type ToasterProps = React.ComponentProps<typeof Sonner>
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
toastOptions={{
|
||||
classNames: {
|
||||
toast:
|
||||
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
|
||||
description: "group-[.toast]:text-muted-foreground",
|
||||
actionButton:
|
||||
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
|
||||
cancelButton:
|
||||
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
|
||||
},
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
@@ -2,8 +2,7 @@ import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
export interface TextareaProps
|
||||
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
|
||||
export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>
|
||||
|
||||
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
|
||||
({ className, ...props }, ref) => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"
|
||||
import { type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { toggleVariants } from "@/components/ui/toggle"
|
||||
import { toggleVariants } from "@/components/ui/toggle-variants"
|
||||
|
||||
const ToggleGroupContext = React.createContext<
|
||||
VariantProps<typeof toggleVariants>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { cva } from "class-variance-authority"
|
||||
|
||||
export const toggleVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
outline:
|
||||
"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-3",
|
||||
sm: "h-9 px-2.5",
|
||||
lg: "h-11 px-5",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -1,30 +1,9 @@
|
||||
import * as React from "react"
|
||||
import * as TogglePrimitive from "@radix-ui/react-toggle"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const toggleVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
outline:
|
||||
"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
|
||||
},
|
||||
size: {
|
||||
default: "h-10 px-3",
|
||||
sm: "h-9 px-2.5",
|
||||
lg: "h-11 px-5",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
import { toggleVariants } from "./toggle-variants"
|
||||
|
||||
const Toggle = React.forwardRef<
|
||||
React.ElementRef<typeof TogglePrimitive.Root>,
|
||||
@@ -40,4 +19,4 @@ const Toggle = React.forwardRef<
|
||||
|
||||
Toggle.displayName = TogglePrimitive.Root.displayName
|
||||
|
||||
export { Toggle, toggleVariants }
|
||||
export { Toggle }
|
||||
@@ -0,0 +1,21 @@
|
||||
import { createContext } from "react";
|
||||
|
||||
export type Theme = "dark" | "light" | "system";
|
||||
|
||||
export interface AppConfig {
|
||||
/** Current theme */
|
||||
theme: Theme;
|
||||
/** Selected relay URL */
|
||||
relayUrl: string;
|
||||
}
|
||||
|
||||
export interface AppContextType {
|
||||
/** Current application configuration */
|
||||
config: AppConfig;
|
||||
/** Update configuration using a callback that receives current config and returns new config */
|
||||
updateConfig: (updater: (currentConfig: AppConfig) => AppConfig) => void;
|
||||
/** Optional list of preset relays to display in the RelaySelector */
|
||||
presetRelays?: { name: string; url: string }[];
|
||||
}
|
||||
|
||||
export const AppContext = createContext<AppContextType | undefined>(undefined);
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { useNWCInternal as useNWCHook } from '@/hooks/useNWC';
|
||||
import { NWCContext } from '@/hooks/useNWCContext';
|
||||
|
||||
export function NWCProvider({ children }: { children: ReactNode }) {
|
||||
const nwc = useNWCHook();
|
||||
return <NWCContext.Provider value={nwc}>{children}</NWCContext.Provider>;
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import { useNostrPublish } from './useNostrPublish';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Custom kind for admin storage
|
||||
const ADMIN_STORAGE_KIND = 39767;
|
||||
|
||||
// Get admin npub from environment variable
|
||||
const ADMIN_NPUB = import.meta.env.VITE_ADMIN_NPUB;
|
||||
|
||||
export interface AdminStorageData {
|
||||
hiddenEvents: string[];
|
||||
allowList: string[];
|
||||
denyList: string[];
|
||||
blockedWords: string[];
|
||||
caseSensitive: boolean;
|
||||
wholeWordsOnly: boolean;
|
||||
enableModeration: boolean;
|
||||
autoHideBlocked: boolean;
|
||||
requireApproval: boolean;
|
||||
siteName: string;
|
||||
siteDescription: string;
|
||||
}
|
||||
|
||||
const defaultAdminData: AdminStorageData = {
|
||||
hiddenEvents: [],
|
||||
allowList: [],
|
||||
denyList: [],
|
||||
blockedWords: [],
|
||||
caseSensitive: false,
|
||||
wholeWordsOnly: true,
|
||||
enableModeration: true,
|
||||
autoHideBlocked: true,
|
||||
requireApproval: false,
|
||||
siteName: '',
|
||||
siteDescription: '',
|
||||
};
|
||||
|
||||
export function useAdminStorage() {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Get admin pubkey
|
||||
let adminPubkey: string = '';
|
||||
try {
|
||||
if (ADMIN_NPUB) {
|
||||
const decoded = nip19.decode(ADMIN_NPUB);
|
||||
// @ts-expect-error - TypeScript has issues with nostr-tools type inference
|
||||
if (decoded.type === 'npub') {
|
||||
adminPubkey = decoded.data as unknown as string;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Invalid admin npub
|
||||
}
|
||||
|
||||
// Check if current user is admin
|
||||
const isAdmin = user?.pubkey === adminPubkey && !!adminPubkey;
|
||||
|
||||
// Query for admin storage events
|
||||
const adminDataQuery = useQuery({
|
||||
queryKey: ['admin-storage', adminPubkey],
|
||||
queryFn: async ({ signal }) => {
|
||||
if (!adminPubkey) return defaultAdminData;
|
||||
|
||||
const timeoutSignal = AbortSignal.timeout(1500);
|
||||
const combinedSignal = AbortSignal.any([signal, timeoutSignal]);
|
||||
|
||||
// Query for admin storage events
|
||||
const events = await nostr.query([{
|
||||
kinds: [ADMIN_STORAGE_KIND],
|
||||
authors: [adminPubkey],
|
||||
'#d': ['admin-config'],
|
||||
limit: 1
|
||||
}], { signal: combinedSignal });
|
||||
|
||||
if (events.length === 0) {
|
||||
return defaultAdminData;
|
||||
}
|
||||
|
||||
// Get the most recent event
|
||||
const latestEvent = events.sort((a, b) => b.created_at - a.created_at)[0];
|
||||
|
||||
try {
|
||||
const data = JSON.parse(latestEvent.content) as AdminStorageData;
|
||||
// Merge with defaults to handle missing fields
|
||||
return { ...defaultAdminData, ...data };
|
||||
} catch {
|
||||
return defaultAdminData;
|
||||
}
|
||||
},
|
||||
enabled: !!adminPubkey,
|
||||
});
|
||||
|
||||
// Mutation to save admin data
|
||||
const saveAdminData = useMutation({
|
||||
mutationFn: async (data: Partial<AdminStorageData>) => {
|
||||
if (!isAdmin) {
|
||||
throw new Error('Only admin can save admin data');
|
||||
}
|
||||
|
||||
const currentData = adminDataQuery.data || defaultAdminData;
|
||||
const updatedData = { ...currentData, ...data };
|
||||
|
||||
await publishEvent({
|
||||
kind: ADMIN_STORAGE_KIND,
|
||||
content: JSON.stringify(updatedData),
|
||||
tags: [
|
||||
['d', 'admin-config'],
|
||||
['alt', 'Site administration configuration and policies'],
|
||||
],
|
||||
});
|
||||
|
||||
return updatedData;
|
||||
},
|
||||
onSuccess: (updatedData) => {
|
||||
// Update the cache with new data
|
||||
queryClient.setQueryData(['admin-storage', adminPubkey], updatedData);
|
||||
},
|
||||
});
|
||||
|
||||
// Helper functions for specific data updates
|
||||
const updateHiddenEvents = (hiddenEvents: string[]) =>
|
||||
saveAdminData.mutateAsync({ hiddenEvents });
|
||||
|
||||
const updateAllowList = (allowList: string[]) =>
|
||||
saveAdminData.mutateAsync({ allowList });
|
||||
|
||||
const updateDenyList = (denyList: string[]) =>
|
||||
saveAdminData.mutateAsync({ denyList });
|
||||
|
||||
const updateBlockedWords = (blockedWords: string[]) =>
|
||||
saveAdminData.mutateAsync({ blockedWords });
|
||||
|
||||
const updateModerationSettings = (settings: {
|
||||
caseSensitive?: boolean;
|
||||
wholeWordsOnly?: boolean;
|
||||
enableModeration?: boolean;
|
||||
autoHideBlocked?: boolean;
|
||||
requireApproval?: boolean;
|
||||
}) => saveAdminData.mutateAsync(settings);
|
||||
|
||||
const updateSiteSettings = (settings: {
|
||||
siteName?: string;
|
||||
siteDescription?: string;
|
||||
}) => saveAdminData.mutateAsync(settings);
|
||||
|
||||
return {
|
||||
// Data
|
||||
data: adminDataQuery.data || defaultAdminData,
|
||||
isLoading: adminDataQuery.isLoading,
|
||||
error: adminDataQuery.error,
|
||||
|
||||
// Auth
|
||||
isAdmin,
|
||||
adminPubkey,
|
||||
|
||||
// Mutations
|
||||
saveAdminData: saveAdminData.mutateAsync,
|
||||
isSaving: saveAdminData.isPending,
|
||||
|
||||
// Helper functions
|
||||
updateHiddenEvents,
|
||||
updateAllowList,
|
||||
updateDenyList,
|
||||
updateBlockedWords,
|
||||
updateModerationSettings,
|
||||
updateSiteSettings,
|
||||
};
|
||||
}
|
||||
|
||||
// Hook for checking if content should be hidden based on admin policies
|
||||
export function useContentFilter() {
|
||||
const { data: adminData } = useAdminStorage();
|
||||
|
||||
const isContentHidden = (eventId: string): boolean => {
|
||||
return adminData.hiddenEvents.includes(eventId);
|
||||
};
|
||||
|
||||
const isUserBlocked = (pubkey: string): boolean => {
|
||||
// If allow list exists and user is not on it, they're blocked
|
||||
if (adminData.allowList.length > 0 && !adminData.allowList.includes(pubkey)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If user is on deny list, they're blocked
|
||||
return adminData.denyList.includes(pubkey);
|
||||
};
|
||||
|
||||
const isContentBlocked = (content: string): boolean => {
|
||||
if (!adminData.enableModeration || adminData.blockedWords.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const text = adminData.caseSensitive ? content : content.toLowerCase();
|
||||
|
||||
return adminData.blockedWords.some(word => {
|
||||
const searchWord = adminData.caseSensitive ? word : word.toLowerCase();
|
||||
|
||||
if (adminData.wholeWordsOnly) {
|
||||
// Match whole words only
|
||||
const regex = new RegExp(`\\b${searchWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
|
||||
return regex.test(text);
|
||||
} else {
|
||||
// Match partial words
|
||||
return text.includes(searchWord);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const shouldHideContent = (eventId: string, pubkey: string, content: string): boolean => {
|
||||
if (!adminData.enableModeration) return false;
|
||||
|
||||
// Check if manually hidden
|
||||
if (isContentHidden(eventId)) return true;
|
||||
|
||||
// Check if user is blocked
|
||||
if (isUserBlocked(pubkey)) return true;
|
||||
|
||||
// Check if content contains blocked words and auto-hide is enabled
|
||||
if (adminData.autoHideBlocked && isContentBlocked(content)) return true;
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
return {
|
||||
isContentHidden,
|
||||
isUserBlocked,
|
||||
isContentBlocked,
|
||||
shouldHideContent,
|
||||
adminData,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useContext } from "react";
|
||||
import { AppContext, type AppContextType } from "@/contexts/AppContext";
|
||||
|
||||
/**
|
||||
* Hook to access and update application configuration
|
||||
* @returns Application context with config and update methods
|
||||
*/
|
||||
export function useAppContext(): AppContextType {
|
||||
const context = useContext(AppContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useAppContext must be used within an AppProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { NKinds, NostrEvent, NostrFilter } from '@nostrify/nostrify';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
export function useComments(root: NostrEvent | URL, limit?: number) {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['comments', root instanceof URL ? root.toString() : root.id, limit],
|
||||
queryFn: async (c) => {
|
||||
const filter: NostrFilter = { kinds: [1111] };
|
||||
|
||||
if (root instanceof URL) {
|
||||
filter['#I'] = [root.toString()];
|
||||
} else if (NKinds.addressable(root.kind)) {
|
||||
const d = root.tags.find(([name]) => name === 'd')?.[1] ?? '';
|
||||
filter['#A'] = [`${root.kind}:${root.pubkey}:${d}`];
|
||||
} else if (NKinds.replaceable(root.kind)) {
|
||||
filter['#A'] = [`${root.kind}:${root.pubkey}:`];
|
||||
} else {
|
||||
filter['#E'] = [root.id];
|
||||
}
|
||||
|
||||
if (typeof limit === 'number') {
|
||||
filter.limit = limit;
|
||||
}
|
||||
|
||||
// Query for all kind 1111 comments that reference this addressable event regardless of depth
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
|
||||
const events = await nostr.query([filter], { signal });
|
||||
|
||||
// Helper function to get tag value
|
||||
const getTagValue = (event: NostrEvent, tagName: string): string | undefined => {
|
||||
const tag = event.tags.find(([name]) => name === tagName);
|
||||
return tag?.[1];
|
||||
};
|
||||
|
||||
// Filter top-level comments (those with lowercase tag matching the root)
|
||||
const topLevelComments = events.filter(comment => {
|
||||
if (root instanceof URL) {
|
||||
return getTagValue(comment, 'i') === root.toString();
|
||||
} else if (NKinds.addressable(root.kind)) {
|
||||
const d = getTagValue(root, 'd') ?? '';
|
||||
return getTagValue(comment, 'a') === `${root.kind}:${root.pubkey}:${d}`;
|
||||
} else if (NKinds.replaceable(root.kind)) {
|
||||
return getTagValue(comment, 'a') === `${root.kind}:${root.pubkey}:`;
|
||||
} else {
|
||||
return getTagValue(comment, 'e') === root.id;
|
||||
}
|
||||
});
|
||||
|
||||
// Helper function to get all descendants of a comment
|
||||
const getDescendants = (parentId: string): NostrEvent[] => {
|
||||
const directReplies = events.filter(comment => {
|
||||
const eTag = getTagValue(comment, 'e');
|
||||
return eTag === parentId;
|
||||
});
|
||||
|
||||
const allDescendants = [...directReplies];
|
||||
|
||||
// Recursively get descendants of each direct reply
|
||||
for (const reply of directReplies) {
|
||||
allDescendants.push(...getDescendants(reply.id));
|
||||
}
|
||||
|
||||
return allDescendants;
|
||||
};
|
||||
|
||||
// Create a map of comment ID to its descendants
|
||||
const commentDescendants = new Map<string, NostrEvent[]>();
|
||||
for (const comment of events) {
|
||||
commentDescendants.set(comment.id, getDescendants(comment.id));
|
||||
}
|
||||
|
||||
// Sort top-level comments by creation time (newest first)
|
||||
const sortedTopLevel = topLevelComments.sort((a, b) => b.created_at - a.created_at);
|
||||
|
||||
return {
|
||||
allComments: events,
|
||||
topLevelComments: sortedTopLevel,
|
||||
getDescendants: (commentId: string) => {
|
||||
const descendants = commentDescendants.get(commentId) || [];
|
||||
// Sort descendants by creation time (oldest first for threaded display)
|
||||
return descendants.sort((a, b) => a.created_at - b.created_at);
|
||||
},
|
||||
getDirectReplies: (commentId: string) => {
|
||||
const directReplies = events.filter(comment => {
|
||||
const eTag = getTagValue(comment, 'e');
|
||||
return eTag === commentId;
|
||||
});
|
||||
// Sort direct replies by creation time (oldest first for threaded display)
|
||||
return directReplies.sort((a, b) => a.created_at - b.created_at);
|
||||
}
|
||||
};
|
||||
},
|
||||
enabled: !!root,
|
||||
});
|
||||
}
|
||||
@@ -38,11 +38,11 @@ export function useCurrentUser() {
|
||||
}, [logins, loginToUser]);
|
||||
|
||||
const user = users[0] as NUser | undefined;
|
||||
const data = useAuthor(user?.pubkey);
|
||||
const author = useAuthor(user?.pubkey);
|
||||
|
||||
return {
|
||||
user,
|
||||
data,
|
||||
users,
|
||||
...author.data,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
/**
|
||||
* Generic hook for managing localStorage state
|
||||
*/
|
||||
export function useLocalStorage<T>(
|
||||
key: string,
|
||||
defaultValue: T,
|
||||
serializer?: {
|
||||
serialize: (value: T) => string;
|
||||
deserialize: (value: string) => T;
|
||||
}
|
||||
) {
|
||||
const serialize = serializer?.serialize || JSON.stringify;
|
||||
const deserialize = serializer?.deserialize || JSON.parse;
|
||||
|
||||
const [state, setState] = useState<T>(() => {
|
||||
try {
|
||||
const item = localStorage.getItem(key);
|
||||
return item ? deserialize(item) : defaultValue;
|
||||
} catch (error) {
|
||||
console.warn(`Failed to load ${key} from localStorage:`, error);
|
||||
return defaultValue;
|
||||
}
|
||||
});
|
||||
|
||||
const setValue = (value: T | ((prev: T) => T)) => {
|
||||
try {
|
||||
const valueToStore = value instanceof Function ? value(state) : value;
|
||||
setState(valueToStore);
|
||||
localStorage.setItem(key, serialize(valueToStore));
|
||||
} catch (error) {
|
||||
console.warn(`Failed to save ${key} to localStorage:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
// Sync with localStorage changes from other tabs
|
||||
useEffect(() => {
|
||||
const handleStorageChange = (e: StorageEvent) => {
|
||||
if (e.key === key && e.newValue !== null) {
|
||||
try {
|
||||
setState(deserialize(e.newValue));
|
||||
} catch (error) {
|
||||
console.warn(`Failed to sync ${key} from localStorage:`, error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('storage', handleStorageChange);
|
||||
return () => window.removeEventListener('storage', handleStorageChange);
|
||||
}, [key, deserialize]);
|
||||
|
||||
return [state, setValue] as const;
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { LN } from '@getalby/sdk';
|
||||
|
||||
export interface NWCConnection {
|
||||
connectionString: string;
|
||||
alias?: string;
|
||||
isConnected: boolean;
|
||||
client?: LN;
|
||||
}
|
||||
|
||||
export interface NWCInfo {
|
||||
alias?: string;
|
||||
color?: string;
|
||||
pubkey?: string;
|
||||
network?: string;
|
||||
methods?: string[];
|
||||
notifications?: string[];
|
||||
}
|
||||
|
||||
export function useNWCInternal() {
|
||||
const { toast } = useToast();
|
||||
const [connections, setConnections] = useLocalStorage<NWCConnection[]>('nwc-connections', []);
|
||||
const [activeConnection, setActiveConnection] = useLocalStorage<string | null>('nwc-active-connection', null);
|
||||
const [connectionInfo, setConnectionInfo] = useState<Record<string, NWCInfo>>({});
|
||||
|
||||
// Add new connection
|
||||
const addConnection = async (uri: string, alias?: string): Promise<boolean> => {
|
||||
const parseNWCUri = (uri: string): { connectionString: string } | null => {
|
||||
try {
|
||||
if (!uri.startsWith('nostr+walletconnect://') && !uri.startsWith('nostrwalletconnect://')) {
|
||||
console.error('Invalid NWC URI protocol:', { protocol: uri.split('://')[0] });
|
||||
return null;
|
||||
}
|
||||
return { connectionString: uri };
|
||||
} catch (error) {
|
||||
console.error('Failed to parse NWC URI:', error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const parsed = parseNWCUri(uri);
|
||||
if (!parsed) {
|
||||
toast({
|
||||
title: 'Invalid NWC URI',
|
||||
description: 'Please check the connection string and try again.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
const existingConnection = connections.find(c => c.connectionString === parsed.connectionString);
|
||||
if (existingConnection) {
|
||||
toast({
|
||||
title: 'Connection already exists',
|
||||
description: 'This wallet is already connected.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
let timeoutId: NodeJS.Timeout | undefined;
|
||||
const testPromise = new Promise((resolve, reject) => {
|
||||
try {
|
||||
const client = new LN(parsed.connectionString);
|
||||
resolve(client);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
timeoutId = setTimeout(() => reject(new Error('Connection test timeout')), 10000);
|
||||
});
|
||||
|
||||
try {
|
||||
await Promise.race([testPromise, timeoutPromise]) as LN;
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
} catch (error) {
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const connection: NWCConnection = {
|
||||
connectionString: parsed.connectionString,
|
||||
alias: alias || 'NWC Wallet',
|
||||
isConnected: true,
|
||||
};
|
||||
|
||||
setConnectionInfo(prev => ({
|
||||
...prev,
|
||||
[parsed.connectionString]: {
|
||||
alias: connection.alias,
|
||||
methods: ['pay_invoice'],
|
||||
},
|
||||
}));
|
||||
|
||||
const newConnections = [...connections, connection];
|
||||
setConnections(newConnections);
|
||||
|
||||
if (connections.length === 0 || !activeConnection)
|
||||
setActiveConnection(parsed.connectionString);
|
||||
|
||||
toast({
|
||||
title: 'Wallet connected',
|
||||
description: `Successfully connected to ${connection.alias}.`,
|
||||
});
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('NWC connection failed:', error);
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
|
||||
toast({
|
||||
title: 'Connection failed',
|
||||
description: `Could not connect to the wallet: ${errorMessage}`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Remove connection
|
||||
const removeConnection = (connectionString: string) => {
|
||||
const filtered = connections.filter(c => c.connectionString !== connectionString);
|
||||
setConnections(filtered);
|
||||
|
||||
if (activeConnection === connectionString) {
|
||||
const newActive = filtered.length > 0 ? filtered[0].connectionString : null;
|
||||
setActiveConnection(newActive);
|
||||
}
|
||||
|
||||
setConnectionInfo(prev => {
|
||||
const newInfo = { ...prev };
|
||||
delete newInfo[connectionString];
|
||||
return newInfo;
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Wallet disconnected',
|
||||
description: 'The wallet connection has been removed.',
|
||||
});
|
||||
};
|
||||
|
||||
// Get active connection
|
||||
const getActiveConnection = useCallback((): NWCConnection | null => {
|
||||
if (!activeConnection && connections.length > 0) {
|
||||
setActiveConnection(connections[0].connectionString);
|
||||
return connections[0];
|
||||
}
|
||||
|
||||
if (!activeConnection) return null;
|
||||
|
||||
const found = connections.find(c => c.connectionString === activeConnection);
|
||||
return found || null;
|
||||
}, [activeConnection, connections, setActiveConnection]);
|
||||
|
||||
// Send payment using the SDK
|
||||
const sendPayment = useCallback(async (
|
||||
connection: NWCConnection,
|
||||
invoice: string
|
||||
): Promise<{ preimage: string }> => {
|
||||
if (!connection.connectionString) {
|
||||
throw new Error('Invalid connection: missing connection string');
|
||||
}
|
||||
|
||||
let client: LN;
|
||||
try {
|
||||
client = new LN(connection.connectionString);
|
||||
} catch (error) {
|
||||
console.error('Failed to create NWC client:', error);
|
||||
throw new Error(`Failed to create NWC client: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
|
||||
try {
|
||||
let timeoutId: NodeJS.Timeout | undefined;
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
timeoutId = setTimeout(() => reject(new Error('Payment timeout after 15 seconds')), 15000);
|
||||
});
|
||||
|
||||
const paymentPromise = client.pay(invoice);
|
||||
|
||||
try {
|
||||
const response = await Promise.race([paymentPromise, timeoutPromise]) as { preimage: string };
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
return response;
|
||||
} catch (error) {
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('NWC payment failed:', error);
|
||||
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('timeout')) {
|
||||
throw new Error('Payment timed out. Please try again.');
|
||||
} else if (error.message.includes('insufficient')) {
|
||||
throw new Error('Insufficient balance in connected wallet.');
|
||||
} else if (error.message.includes('invalid')) {
|
||||
throw new Error('Invalid invoice or connection. Please check your wallet.');
|
||||
} else {
|
||||
throw new Error(`Payment failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error('Payment failed with unknown error');
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
connections,
|
||||
activeConnection,
|
||||
connectionInfo,
|
||||
addConnection,
|
||||
removeConnection,
|
||||
setActiveConnection,
|
||||
getActiveConnection,
|
||||
sendPayment,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useContext } from 'react';
|
||||
import { createContext } from 'react';
|
||||
import { useNWCInternal } from '@/hooks/useNWC';
|
||||
|
||||
type NWCContextType = ReturnType<typeof useNWCInternal>;
|
||||
|
||||
export const NWCContext = createContext<NWCContextType | null>(null);
|
||||
|
||||
export function useNWC(): NWCContextType {
|
||||
const context = useContext(NWCContext);
|
||||
if (!context) {
|
||||
throw new Error('useNWC must be used within a NWCProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// This file exists because LLMs get confused and try to create this file if it doesn't exist.
|
||||
// The `useNostr` hook should be imported directly from `@nostrify/react`, not from this file.
|
||||
|
||||
// This file SHOULD NOT be edited or removed.
|
||||
|
||||
export { useNostr } from "@nostrify/react";
|
||||
@@ -1,29 +1,33 @@
|
||||
import { useNostr } from "@nostrify/react";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { useMutation, type UseMutationResult } from "@tanstack/react-query";
|
||||
|
||||
import { useCurrentUser } from "./useCurrentUser";
|
||||
|
||||
interface EventTemplate {
|
||||
kind: number;
|
||||
content?: string;
|
||||
tags?: string[][];
|
||||
created_at?: number;
|
||||
}
|
||||
import type { NostrEvent } from "@nostrify/nostrify";
|
||||
|
||||
export function useNostrPublish() {
|
||||
export function useNostrPublish(): UseMutationResult<NostrEvent> {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (t: EventTemplate) => {
|
||||
mutationFn: async (t: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>) => {
|
||||
if (user) {
|
||||
const tags = t.tags ?? [];
|
||||
|
||||
// Add the client tag if it doesn't exist
|
||||
if (location.protocol === "https:" && !tags.some(([name]) => name === "client")) {
|
||||
tags.push(["client", location.hostname]);
|
||||
}
|
||||
|
||||
const event = await user.signer.signEvent({
|
||||
kind: t.kind,
|
||||
content: t.content ?? "",
|
||||
tags: t.tags ?? [],
|
||||
tags,
|
||||
created_at: t.created_at ?? Math.floor(Date.now() / 1000),
|
||||
});
|
||||
|
||||
await nostr.event(event, { signal: AbortSignal.timeout(5000) });
|
||||
return event;
|
||||
} else {
|
||||
throw new Error("User is not logged in");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { NKinds, type NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
interface PostCommentParams {
|
||||
root: NostrEvent | URL; // The root event to comment on
|
||||
reply?: NostrEvent | URL; // Optional reply to another comment
|
||||
content: string;
|
||||
}
|
||||
|
||||
/** Post a NIP-22 (kind 1111) comment on an event. */
|
||||
export function usePostComment() {
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ root, reply, content }: PostCommentParams) => {
|
||||
const tags: string[][] = [];
|
||||
|
||||
// d-tag identifiers
|
||||
const dRoot = root instanceof URL ? '' : root.tags.find(([name]) => name === 'd')?.[1] ?? '';
|
||||
const dReply = reply instanceof URL ? '' : reply?.tags.find(([name]) => name === 'd')?.[1] ?? '';
|
||||
|
||||
// Root event tags
|
||||
if (root instanceof URL) {
|
||||
tags.push(['I', root.toString()]);
|
||||
} else if (NKinds.addressable(root.kind)) {
|
||||
tags.push(['A', `${root.kind}:${root.pubkey}:${dRoot}`]);
|
||||
} else if (NKinds.replaceable(root.kind)) {
|
||||
tags.push(['A', `${root.kind}:${root.pubkey}:`]);
|
||||
} else {
|
||||
tags.push(['E', root.id]);
|
||||
}
|
||||
if (root instanceof URL) {
|
||||
tags.push(['K', root.hostname]);
|
||||
} else {
|
||||
tags.push(['K', root.kind.toString()]);
|
||||
tags.push(['P', root.pubkey]);
|
||||
}
|
||||
|
||||
// Reply event tags
|
||||
if (reply) {
|
||||
if (reply instanceof URL) {
|
||||
tags.push(['i', reply.toString()]);
|
||||
} else if (NKinds.addressable(reply.kind)) {
|
||||
tags.push(['a', `${reply.kind}:${reply.pubkey}:${dReply}`]);
|
||||
} else if (NKinds.replaceable(reply.kind)) {
|
||||
tags.push(['a', `${reply.kind}:${reply.pubkey}:`]);
|
||||
} else {
|
||||
tags.push(['e', reply.id]);
|
||||
}
|
||||
if (reply instanceof URL) {
|
||||
tags.push(['k', reply.hostname]);
|
||||
} else {
|
||||
tags.push(['k', reply.kind.toString()]);
|
||||
tags.push(['p', reply.pubkey]);
|
||||
}
|
||||
} else {
|
||||
// If this is a top-level comment, use the root event's tags
|
||||
if (root instanceof URL) {
|
||||
tags.push(['i', root.toString()]);
|
||||
} else if (NKinds.addressable(root.kind)) {
|
||||
tags.push(['a', `${root.kind}:${root.pubkey}:${dRoot}`]);
|
||||
} else if (NKinds.replaceable(root.kind)) {
|
||||
tags.push(['a', `${root.kind}:${root.pubkey}:`]);
|
||||
} else {
|
||||
tags.push(['e', root.id]);
|
||||
}
|
||||
if (root instanceof URL) {
|
||||
tags.push(['k', root.hostname]);
|
||||
} else {
|
||||
tags.push(['k', root.kind.toString()]);
|
||||
tags.push(['p', root.pubkey]);
|
||||
}
|
||||
}
|
||||
|
||||
const event = await publishEvent({
|
||||
kind: 1111,
|
||||
content,
|
||||
tags,
|
||||
});
|
||||
|
||||
return event;
|
||||
},
|
||||
onSuccess: (_, { root }) => {
|
||||
// Invalidate and refetch comments
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['comments', root instanceof URL ? root.toString() : root.id]
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { type Theme } from "@/contexts/AppContext";
|
||||
import { useAppContext } from "@/hooks/useAppContext";
|
||||
|
||||
/**
|
||||
* Hook to get and set the active theme
|
||||
* @returns Theme context with theme and setTheme
|
||||
*/
|
||||
export function useTheme(): { theme: Theme; setTheme: (theme: Theme) => void } {
|
||||
const { config, updateConfig } = useAppContext();
|
||||
|
||||
return {
|
||||
theme: config.theme,
|
||||
setTheme: (theme: Theme) => {
|
||||
updateConfig((currentConfig) => ({
|
||||
...currentConfig,
|
||||
theme,
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-13
@@ -15,13 +15,6 @@ type ToasterToast = ToastProps & {
|
||||
action?: ToastActionElement
|
||||
}
|
||||
|
||||
const actionTypes = {
|
||||
ADD_TOAST: "ADD_TOAST",
|
||||
UPDATE_TOAST: "UPDATE_TOAST",
|
||||
DISMISS_TOAST: "DISMISS_TOAST",
|
||||
REMOVE_TOAST: "REMOVE_TOAST",
|
||||
} as const
|
||||
|
||||
let count = 0
|
||||
|
||||
function genId() {
|
||||
@@ -29,23 +22,21 @@ function genId() {
|
||||
return count.toString()
|
||||
}
|
||||
|
||||
type ActionType = typeof actionTypes
|
||||
|
||||
type Action =
|
||||
| {
|
||||
type: ActionType["ADD_TOAST"]
|
||||
type: "ADD_TOAST";
|
||||
toast: ToasterToast
|
||||
}
|
||||
| {
|
||||
type: ActionType["UPDATE_TOAST"]
|
||||
type: "UPDATE_TOAST";
|
||||
toast: Partial<ToasterToast>
|
||||
}
|
||||
| {
|
||||
type: ActionType["DISMISS_TOAST"]
|
||||
type: "DISMISS_TOAST";
|
||||
toastId?: ToasterToast["id"]
|
||||
}
|
||||
| {
|
||||
type: ActionType["REMOVE_TOAST"]
|
||||
type: "REMOVE_TOAST";
|
||||
toastId?: ToasterToast["id"]
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { BlossomUploader } from '@nostrify/nostrify/uploaders';
|
||||
|
||||
import { useCurrentUser } from "./useCurrentUser";
|
||||
|
||||
export function useUploadFile() {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (file: File) => {
|
||||
if (!user) {
|
||||
throw new Error('Must be logged in to upload files');
|
||||
}
|
||||
|
||||
const uploader = new BlossomUploader({
|
||||
servers: [
|
||||
'https://blossom.primal.net/',
|
||||
],
|
||||
signer: user.signer,
|
||||
});
|
||||
|
||||
const tags = await uploader.upload(file);
|
||||
return tags;
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import type { WebLNProvider } from 'webln';
|
||||
import { requestProvider } from 'webln';
|
||||
|
||||
export interface WalletStatus {
|
||||
hasWebLN: boolean;
|
||||
hasNWC: boolean;
|
||||
webln: WebLNProvider | null;
|
||||
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
|
||||
isDetecting: boolean;
|
||||
preferredMethod: 'nwc' | 'webln' | 'manual';
|
||||
}
|
||||
|
||||
export function useWallet() {
|
||||
const [webln, setWebln] = useState<WebLNProvider | null>(null);
|
||||
const [isDetecting, setIsDetecting] = useState(false);
|
||||
const [hasAttemptedDetection, setHasAttemptedDetection] = useState(false);
|
||||
const { connections, getActiveConnection } = useNWC();
|
||||
|
||||
// Get the active connection directly - no memoization to avoid stale state
|
||||
const activeNWC = getActiveConnection();
|
||||
|
||||
// Detect WebLN
|
||||
const detectWebLN = useCallback(async () => {
|
||||
if (webln || isDetecting) return webln;
|
||||
|
||||
setIsDetecting(true);
|
||||
try {
|
||||
const provider = await requestProvider();
|
||||
setWebln(provider);
|
||||
setHasAttemptedDetection(true);
|
||||
return provider;
|
||||
} catch (error) {
|
||||
// Only log the error if it's not the common "no provider" error
|
||||
if (error instanceof Error && !error.message.includes('no WebLN provider')) {
|
||||
console.warn('WebLN detection error:', error);
|
||||
}
|
||||
setWebln(null);
|
||||
setHasAttemptedDetection(true);
|
||||
return null;
|
||||
} finally {
|
||||
setIsDetecting(false);
|
||||
}
|
||||
}, [webln, isDetecting]);
|
||||
|
||||
// Only auto-detect once on mount
|
||||
useEffect(() => {
|
||||
if (!hasAttemptedDetection) {
|
||||
detectWebLN();
|
||||
}
|
||||
}, [detectWebLN, hasAttemptedDetection]);
|
||||
|
||||
// Test WebLN connection
|
||||
const testWebLN = useCallback(async (): Promise<boolean> => {
|
||||
if (!webln) return false;
|
||||
|
||||
try {
|
||||
await webln.enable();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('WebLN test failed:', error);
|
||||
return false;
|
||||
}
|
||||
}, [webln]);
|
||||
|
||||
// Calculate status values reactively
|
||||
const hasNWC = useMemo(() => {
|
||||
return connections.length > 0 && connections.some(c => c.isConnected);
|
||||
}, [connections]);
|
||||
|
||||
// Determine preferred payment method
|
||||
const preferredMethod: WalletStatus['preferredMethod'] = activeNWC
|
||||
? 'nwc'
|
||||
: webln
|
||||
? 'webln'
|
||||
: 'manual';
|
||||
|
||||
const status: WalletStatus = {
|
||||
hasWebLN: !!webln,
|
||||
hasNWC,
|
||||
webln,
|
||||
activeNWC,
|
||||
isDetecting,
|
||||
preferredMethod,
|
||||
};
|
||||
|
||||
return {
|
||||
...status,
|
||||
hasAttemptedDetection,
|
||||
detectWebLN,
|
||||
testWebLN,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
import { useState, useMemo, useEffect, useCallback } from 'react';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import type { NWCConnection } from '@/hooks/useNWC';
|
||||
import { nip57 } from 'nostr-tools';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import type { WebLNProvider } from 'webln';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
export function useZaps(
|
||||
target: Event | Event[],
|
||||
webln: WebLNProvider | null,
|
||||
_nwcConnection: NWCConnection | null,
|
||||
onZapSuccess?: () => void
|
||||
) {
|
||||
const { nostr } = useNostr();
|
||||
const { toast } = useToast();
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Handle the case where an empty array is passed (from ZapButton when external data is provided)
|
||||
const actualTarget = Array.isArray(target) ? (target.length > 0 ? target[0] : null) : target;
|
||||
|
||||
const author = useAuthor(actualTarget?.pubkey);
|
||||
const { sendPayment, getActiveConnection } = useNWC();
|
||||
const [isZapping, setIsZapping] = useState(false);
|
||||
const [invoice, setInvoice] = useState<string | null>(null);
|
||||
|
||||
// Cleanup state when component unmounts
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setIsZapping(false);
|
||||
setInvoice(null);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const { data: zapEvents, ...query } = useQuery<NostrEvent[], Error>({
|
||||
queryKey: ['zaps', actualTarget?.id],
|
||||
staleTime: 30000, // 30 seconds
|
||||
refetchInterval: (query) => {
|
||||
// Only refetch if the query is currently being observed (component is mounted)
|
||||
return query.getObserversCount() > 0 ? 60000 : false;
|
||||
},
|
||||
queryFn: async (c) => {
|
||||
if (!actualTarget) return [];
|
||||
|
||||
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
|
||||
|
||||
// Query for zap receipts for this specific event
|
||||
if (actualTarget.kind >= 30000 && actualTarget.kind < 40000) {
|
||||
// Addressable event
|
||||
const identifier = actualTarget.tags.find((t) => t[0] === 'd')?.[1] || '';
|
||||
const events = await nostr.query([{
|
||||
kinds: [9735],
|
||||
'#a': [`${actualTarget.kind}:${actualTarget.pubkey}:${identifier}`],
|
||||
}], { signal });
|
||||
return events;
|
||||
} else {
|
||||
// Regular event
|
||||
const events = await nostr.query([{
|
||||
kinds: [9735],
|
||||
'#e': [actualTarget.id],
|
||||
}], { signal });
|
||||
return events;
|
||||
}
|
||||
},
|
||||
enabled: !!actualTarget?.id,
|
||||
});
|
||||
|
||||
// Process zap events into simple counts and totals
|
||||
const { zapCount, totalSats, zaps } = useMemo(() => {
|
||||
if (!zapEvents || !Array.isArray(zapEvents) || !actualTarget) {
|
||||
return { zapCount: 0, totalSats: 0, zaps: [] };
|
||||
}
|
||||
|
||||
let count = 0;
|
||||
let sats = 0;
|
||||
|
||||
zapEvents.forEach(zap => {
|
||||
count++;
|
||||
|
||||
// Try multiple methods to extract the amount:
|
||||
|
||||
// Method 1: amount tag (from zap request, sometimes copied to receipt)
|
||||
const amountTag = zap.tags.find(([name]) => name === 'amount')?.[1];
|
||||
if (amountTag) {
|
||||
const millisats = parseInt(amountTag);
|
||||
sats += Math.floor(millisats / 1000);
|
||||
return;
|
||||
}
|
||||
|
||||
// Method 2: Extract from bolt11 invoice
|
||||
const bolt11Tag = zap.tags.find(([name]) => name === 'bolt11')?.[1];
|
||||
if (bolt11Tag) {
|
||||
try {
|
||||
const invoiceSats = nip57.getSatoshisAmountFromBolt11(bolt11Tag);
|
||||
sats += invoiceSats;
|
||||
return;
|
||||
} catch (error) {
|
||||
console.warn('Failed to parse bolt11 amount:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Method 3: Parse from description (zap request JSON)
|
||||
const descriptionTag = zap.tags.find(([name]) => name === 'description')?.[1];
|
||||
if (descriptionTag) {
|
||||
try {
|
||||
const zapRequest = JSON.parse(descriptionTag);
|
||||
const requestAmountTag = zapRequest.tags?.find(([name]: string[]) => name === 'amount')?.[1];
|
||||
if (requestAmountTag) {
|
||||
const millisats = parseInt(requestAmountTag);
|
||||
sats += Math.floor(millisats / 1000);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to parse description JSON:', error);
|
||||
}
|
||||
}
|
||||
|
||||
console.warn('Could not extract amount from zap receipt:', zap.id);
|
||||
});
|
||||
|
||||
|
||||
return { zapCount: count, totalSats: sats, zaps: zapEvents };
|
||||
}, [zapEvents, actualTarget]);
|
||||
|
||||
const zap = async (amount: number, comment: string) => {
|
||||
if (amount <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsZapping(true);
|
||||
setInvoice(null); // Clear any previous invoice at the start
|
||||
|
||||
if (!user) {
|
||||
toast({
|
||||
title: 'Login required',
|
||||
description: 'You must be logged in to send a zap.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!actualTarget) {
|
||||
toast({
|
||||
title: 'Event not found',
|
||||
description: 'Could not find the event to zap.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (!author.data || !author.data?.metadata || !author.data?.event ) {
|
||||
toast({
|
||||
title: 'Author not found',
|
||||
description: 'Could not find the author of this item.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const { lud06, lud16 } = author.data.metadata;
|
||||
if (!lud06 && !lud16) {
|
||||
toast({
|
||||
title: 'Lightning address not found',
|
||||
description: 'The author does not have a lightning address configured.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get zap endpoint using the old reliable method
|
||||
const zapEndpoint = await nip57.getZapEndpoint(author.data.event);
|
||||
if (!zapEndpoint) {
|
||||
toast({
|
||||
title: 'Zap endpoint not found',
|
||||
description: 'Could not find a zap endpoint for the author.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create zap request - use appropriate event format based on kind
|
||||
// For addressable events (30000-39999), pass the object to get 'a' tag
|
||||
// For all other events, pass the ID string to get 'e' tag
|
||||
const event = (actualTarget.kind >= 30000 && actualTarget.kind < 40000)
|
||||
? actualTarget
|
||||
: actualTarget.id;
|
||||
|
||||
const zapAmount = amount * 1000; // convert to millisats
|
||||
|
||||
const zapRequest = nip57.makeZapRequest({
|
||||
profile: actualTarget.pubkey,
|
||||
event: event,
|
||||
amount: zapAmount,
|
||||
relays: [config.relayUrl],
|
||||
comment
|
||||
});
|
||||
|
||||
// Sign the zap request (but don't publish to relays - only send to LNURL endpoint)
|
||||
if (!user.signer) {
|
||||
throw new Error('No signer available');
|
||||
}
|
||||
const signedZapRequest = await user.signer.signEvent(zapRequest);
|
||||
|
||||
try {
|
||||
const res = await fetch(`${zapEndpoint}?amount=${zapAmount}&nostr=${encodeURI(JSON.stringify(signedZapRequest))}`);
|
||||
const responseData = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}: ${responseData.reason || 'Unknown error'}`);
|
||||
}
|
||||
|
||||
const newInvoice = responseData.pr;
|
||||
if (!newInvoice || typeof newInvoice !== 'string') {
|
||||
throw new Error('Lightning service did not return a valid invoice');
|
||||
}
|
||||
|
||||
// Get the current active NWC connection dynamically
|
||||
const currentNWCConnection = getActiveConnection();
|
||||
|
||||
// Try NWC first if available and properly connected
|
||||
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
|
||||
try {
|
||||
await sendPayment(currentNWCConnection, newInvoice);
|
||||
|
||||
// Clear states immediately on success
|
||||
setIsZapping(false);
|
||||
setInvoice(null);
|
||||
|
||||
toast({
|
||||
title: 'Zap successful!',
|
||||
description: `You sent ${amount} sats via NWC to the author.`,
|
||||
});
|
||||
|
||||
// Invalidate zap queries to refresh counts
|
||||
queryClient.invalidateQueries({ queryKey: ['zaps'] });
|
||||
|
||||
// Close dialog last to ensure clean state
|
||||
onZapSuccess?.();
|
||||
return;
|
||||
} catch (nwcError) {
|
||||
console.error('NWC payment failed, falling back:', nwcError);
|
||||
|
||||
// Show specific NWC error to user for debugging
|
||||
const errorMessage = nwcError instanceof Error ? nwcError.message : 'Unknown NWC error';
|
||||
toast({
|
||||
title: 'NWC payment failed',
|
||||
description: `${errorMessage}. Falling back to other payment methods...`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (webln) { // Try WebLN next
|
||||
try {
|
||||
await webln.sendPayment(newInvoice);
|
||||
|
||||
// Clear states immediately on success
|
||||
setIsZapping(false);
|
||||
setInvoice(null);
|
||||
|
||||
toast({
|
||||
title: 'Zap successful!',
|
||||
description: `You sent ${amount} sats to the author.`,
|
||||
});
|
||||
|
||||
// Invalidate zap queries to refresh counts
|
||||
queryClient.invalidateQueries({ queryKey: ['zaps'] });
|
||||
|
||||
// Close dialog last to ensure clean state
|
||||
onZapSuccess?.();
|
||||
} catch (weblnError) {
|
||||
console.error('webln payment failed, falling back:', weblnError);
|
||||
|
||||
// Show specific WebLN error to user for debugging
|
||||
const errorMessage = weblnError instanceof Error ? weblnError.message : 'Unknown WebLN error';
|
||||
toast({
|
||||
title: 'WebLN payment failed',
|
||||
description: `${errorMessage}. Falling back to other payment methods...`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
|
||||
setInvoice(newInvoice);
|
||||
setIsZapping(false);
|
||||
}
|
||||
} else { // Default - show QR code and manual Lightning URI
|
||||
setInvoice(newInvoice);
|
||||
setIsZapping(false);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Zap error:', err);
|
||||
toast({
|
||||
title: 'Zap failed',
|
||||
description: (err as Error).message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Zap error:', err);
|
||||
toast({
|
||||
title: 'Zap failed',
|
||||
description: (err as Error).message,
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
}
|
||||
};
|
||||
|
||||
const resetInvoice = useCallback(() => {
|
||||
setInvoice(null);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
zaps,
|
||||
zapCount,
|
||||
totalSats,
|
||||
...query,
|
||||
zap,
|
||||
isZapping,
|
||||
invoice,
|
||||
setInvoice,
|
||||
resetInvoice,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { genUserName } from './genUserName';
|
||||
|
||||
describe('genUserName', () => {
|
||||
it('generates a deterministic name from a seed', () => {
|
||||
const seed = 'test-seed-123';
|
||||
const name1 = genUserName(seed);
|
||||
const name2 = genUserName(seed);
|
||||
|
||||
expect(name1).toEqual('Brave Whale');
|
||||
expect(name1).toEqual(name2);
|
||||
});
|
||||
|
||||
it('generates different names for different seeds', () => {
|
||||
const name1 = genUserName('seed1');
|
||||
const name2 = genUserName('seed2');
|
||||
const name3 = genUserName('seed3');
|
||||
|
||||
// While it's theoretically possible for different seeds to generate the same name,
|
||||
// it's very unlikely with our word lists
|
||||
expect(name1).not.toBe(name2);
|
||||
expect(name2).not.toBe(name3);
|
||||
expect(name1).not.toBe(name3);
|
||||
});
|
||||
|
||||
it('handles typical Nostr pubkey format', () => {
|
||||
// Typical hex pubkey (64 characters)
|
||||
const pubkey = 'e4690a13290739da123aa17d553851dec4cdd0e9d89aa18de3741c446caf8761';
|
||||
const name = genUserName(pubkey);
|
||||
|
||||
expect(name).toEqual('Gentle Hawk');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
/** Generate a deterministic user display name based on a string seed. */
|
||||
export function genUserName(seed: string): string {
|
||||
// Use a simple hash of the pubkey to generate consistent adjective + noun combinations
|
||||
const adjectives = [
|
||||
'Swift', 'Bright', 'Calm', 'Bold', 'Wise', 'Kind', 'Quick', 'Brave',
|
||||
'Cool', 'Sharp', 'Clear', 'Strong', 'Smart', 'Fast', 'Keen', 'Pure',
|
||||
'Noble', 'Gentle', 'Fierce', 'Steady', 'Clever', 'Proud', 'Silent', 'Wild'
|
||||
];
|
||||
|
||||
const nouns = [
|
||||
'Fox', 'Eagle', 'Wolf', 'Bear', 'Lion', 'Tiger', 'Hawk', 'Owl',
|
||||
'Deer', 'Raven', 'Falcon', 'Lynx', 'Otter', 'Whale', 'Shark', 'Dolphin',
|
||||
'Phoenix', 'Dragon', 'Panther', 'Jaguar', 'Cheetah', 'Leopard', 'Puma', 'Cobra'
|
||||
];
|
||||
|
||||
// Create a simple hash from the pubkey
|
||||
let hash = 0;
|
||||
for (let i = 0; i < seed.length; i++) {
|
||||
const char = seed.charCodeAt(i);
|
||||
hash = ((hash << 5) - hash) + char;
|
||||
hash = hash & hash; // Convert to 32-bit integer
|
||||
}
|
||||
|
||||
// Use absolute value to ensure positive index
|
||||
const adjIndex = Math.abs(hash) % adjectives.length;
|
||||
const nounIndex = Math.abs(hash >> 8) % nouns.length;
|
||||
|
||||
return [adjectives[adjIndex], nouns[nounIndex]].join(' ');
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Polyfill for AbortSignal.any()
|
||||
*
|
||||
* AbortSignal.any() creates an AbortSignal that will be aborted when any of the
|
||||
* provided signals are aborted. This is useful for combining multiple abort signals.
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static
|
||||
*/
|
||||
|
||||
// Check if AbortSignal.any is already available
|
||||
if (!AbortSignal.any) {
|
||||
AbortSignal.any = function(signals: AbortSignal[]): AbortSignal {
|
||||
// If no signals provided, return a signal that never aborts
|
||||
if (signals.length === 0) {
|
||||
return new AbortController().signal;
|
||||
}
|
||||
|
||||
// If only one signal, return it directly for efficiency
|
||||
if (signals.length === 1) {
|
||||
return signals[0];
|
||||
}
|
||||
|
||||
// Check if any signal is already aborted
|
||||
for (const signal of signals) {
|
||||
if (signal.aborted) {
|
||||
// Create an already-aborted signal with the same reason
|
||||
const controller = new AbortController();
|
||||
controller.abort(signal.reason);
|
||||
return controller.signal;
|
||||
}
|
||||
}
|
||||
|
||||
// Create a new controller for the combined signal
|
||||
const controller = new AbortController();
|
||||
|
||||
// Function to abort the combined signal
|
||||
const onAbort = (event: Event) => {
|
||||
const target = event.target as AbortSignal;
|
||||
controller.abort(target.reason);
|
||||
};
|
||||
|
||||
// Listen for abort events on all input signals
|
||||
for (const signal of signals) {
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
}
|
||||
|
||||
// Clean up listeners when the combined signal is aborted
|
||||
controller.signal.addEventListener('abort', () => {
|
||||
for (const signal of signals) {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
}
|
||||
}, { once: true });
|
||||
|
||||
return controller.signal;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Polyfill for AbortSignal.timeout()
|
||||
*
|
||||
* AbortSignal.timeout() creates an AbortSignal that will be aborted after a
|
||||
* specified number of milliseconds.
|
||||
*
|
||||
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static
|
||||
*/
|
||||
|
||||
// Check if AbortSignal.timeout is already available
|
||||
if (!AbortSignal.timeout) {
|
||||
AbortSignal.timeout = function(milliseconds: number): AbortSignal {
|
||||
const controller = new AbortController();
|
||||
|
||||
setTimeout(() => {
|
||||
controller.abort(new DOMException('The operation was aborted due to timeout', 'TimeoutError'));
|
||||
}, milliseconds);
|
||||
|
||||
return controller.signal;
|
||||
};
|
||||
}
|
||||
+15
-4
@@ -1,6 +1,17 @@
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { createRoot } from 'react-dom/client';
|
||||
|
||||
import App from './App.tsx'
|
||||
import './index.css'
|
||||
// Import polyfills first
|
||||
import './lib/polyfills.ts';
|
||||
|
||||
createRoot(document.getElementById("root")!).render(<App />);
|
||||
import { ErrorBoundary } from '@/components/ErrorBoundary';
|
||||
import App from './App.tsx';
|
||||
import './index.css';
|
||||
|
||||
// FIXME: a custom font should be used. Eg:
|
||||
// import '@fontsource-variable/<font-name>';
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<ErrorBoundary>
|
||||
<App />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
@@ -0,0 +1,825 @@
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
|
||||
import { AlertCircle, Shield, Ban, UserCheck, MessageSquareX, Trash2, Plus, Eye, EyeOff } from 'lucide-react';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useAdminStorage } from '@/hooks/useAdminStorage';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { genUserName } from '@/lib/genUserName';
|
||||
import NotFound from './NotFound';
|
||||
|
||||
// Get admin npub from environment variable
|
||||
const ADMIN_NPUB = import.meta.env.VITE_ADMIN_NPUB;
|
||||
|
||||
export function AdminDashboard() {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Decode admin npub from environment variable
|
||||
let adminPubkey: string = '';
|
||||
let isValidAdminNpub = false;
|
||||
|
||||
try {
|
||||
if (ADMIN_NPUB) {
|
||||
const decoded = nip19.decode(ADMIN_NPUB);
|
||||
// @ts-expect-error - TypeScript has issues with nostr-tools type inference
|
||||
if (decoded.type === 'npub') {
|
||||
adminPubkey = decoded.data as unknown as string;
|
||||
isValidAdminNpub = true;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Invalid admin npub format
|
||||
}
|
||||
|
||||
// Always call hooks - use empty string as fallback to avoid conditional calls
|
||||
const adminAuthor = useAuthor(adminPubkey || '');
|
||||
|
||||
// Return NotFound if no valid admin npub is configured
|
||||
if (!isValidAdminNpub) {
|
||||
return <NotFound />;
|
||||
}
|
||||
|
||||
// Check if current user is the site admin
|
||||
const isAuthorized = user?.pubkey === adminPubkey;
|
||||
|
||||
if (!isAuthorized) {
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8 max-w-2xl">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Shield className="h-5 w-5 text-amber-500" />
|
||||
Site Admin Access Required
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
You need to be logged in as the site administrator to access this admin panel.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{adminAuthor.data?.metadata && (
|
||||
<div className="flex items-center gap-3 p-4 bg-muted rounded-lg">
|
||||
<Avatar>
|
||||
<AvatarImage src={adminAuthor.data.metadata.picture} />
|
||||
<AvatarFallback>
|
||||
{(adminAuthor.data.metadata.name || genUserName(adminPubkey)).slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div>
|
||||
<p className="font-medium">
|
||||
{adminAuthor.data.metadata.display_name || adminAuthor.data.metadata.name || genUserName(adminPubkey)}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Site Administrator
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Only the site administrator can access content moderation and site management features.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<LoginArea className="w-full" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8 max-w-6xl">
|
||||
<div className="mb-8">
|
||||
<h1 className="text-3xl font-bold mb-2 flex items-center gap-2">
|
||||
<Shield className="h-8 w-8" />
|
||||
Site Administration
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Manage content moderation, user access controls, and site settings
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="moderation" className="space-y-6">
|
||||
<TabsList className="grid w-full grid-cols-5">
|
||||
<TabsTrigger value="moderation">Content Moderation</TabsTrigger>
|
||||
<TabsTrigger value="users">User Management</TabsTrigger>
|
||||
<TabsTrigger value="blocked-words">Blocked Words</TabsTrigger>
|
||||
<TabsTrigger value="analytics">Site Analytics</TabsTrigger>
|
||||
<TabsTrigger value="settings">Site Settings</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="moderation">
|
||||
<ContentModeration />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="users">
|
||||
<UserManagement />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="blocked-words">
|
||||
<BlockedWordsManagement />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="analytics">
|
||||
<SiteAnalytics />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="settings">
|
||||
<SiteSettings />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ContentModeration() {
|
||||
const { nostr } = useNostr();
|
||||
const { data: adminData, updateHiddenEvents, isSaving } = useAdminStorage();
|
||||
|
||||
const recentContent = useQuery({
|
||||
queryKey: ['admin-recent-content'],
|
||||
queryFn: async ({ signal }) => {
|
||||
const timeoutSignal = AbortSignal.timeout(1500);
|
||||
const combinedSignal = AbortSignal.any([signal, timeoutSignal]);
|
||||
|
||||
const events = await nostr.query([{
|
||||
kinds: [1, 30023], // Notes and articles
|
||||
limit: 50
|
||||
}], { signal: combinedSignal });
|
||||
|
||||
return events.sort((a, b) => b.created_at - a.created_at);
|
||||
},
|
||||
});
|
||||
|
||||
const hideEvent = async (eventId: string) => {
|
||||
const newHiddenEvents = [...adminData.hiddenEvents, eventId];
|
||||
await updateHiddenEvents(newHiddenEvents);
|
||||
};
|
||||
|
||||
const unhideEvent = async (eventId: string) => {
|
||||
const newHiddenEvents = adminData.hiddenEvents.filter(id => id !== eventId);
|
||||
await updateHiddenEvents(newHiddenEvents);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Eye className="h-5 w-5" />
|
||||
Recent Content Review
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Review and moderate recent content posted to the site
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{recentContent.isLoading ? (
|
||||
<div className="space-y-4">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<div key={i} className="flex items-start gap-3 p-4 border rounded-lg">
|
||||
<Skeleton className="h-10 w-10 rounded-full" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
<Skeleton className="h-8 w-20" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : recentContent.data?.length ? (
|
||||
<div className="space-y-4">
|
||||
{recentContent.data.map((event) => {
|
||||
const isHidden = adminData.hiddenEvents.includes(event.id);
|
||||
return (
|
||||
<div key={event.id} className={`flex items-start gap-3 p-4 border rounded-lg ${isHidden ? 'opacity-50 bg-muted' : ''}`}>
|
||||
<UserAvatar pubkey={event.pubkey} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<UserName pubkey={event.pubkey} />
|
||||
<Badge variant={event.kind === 1 ? 'default' : 'secondary'}>
|
||||
{event.kind === 1 ? 'Note' : 'Article'}
|
||||
</Badge>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{new Date(event.created_at * 1000).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm line-clamp-3">
|
||||
{event.kind === 30023
|
||||
? event.tags.find(([tag]) => tag === 'title')?.[1] || 'Untitled Article'
|
||||
: event.content
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{isHidden ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => unhideEvent(event.id)}
|
||||
className="text-green-600 hover:text-green-700"
|
||||
disabled={isSaving}
|
||||
>
|
||||
<Eye className="h-4 w-4 mr-1" />
|
||||
Show
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => hideEvent(event.id)}
|
||||
className="text-red-600 hover:text-red-700"
|
||||
disabled={isSaving}
|
||||
>
|
||||
<EyeOff className="h-4 w-4 mr-1" />
|
||||
Hide
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground">No recent content found</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UserManagement() {
|
||||
const { data: adminData, updateAllowList, updateDenyList, isSaving } = useAdminStorage();
|
||||
const [newNpub, setNewNpub] = useState('');
|
||||
|
||||
const addToAllowList = async () => {
|
||||
try {
|
||||
const decoded = nip19.decode(newNpub);
|
||||
if (decoded.type === 'npub') {
|
||||
const pubkey = decoded.data as unknown as string;
|
||||
if (!adminData.allowList.includes(pubkey)) {
|
||||
const newAllowList = [...adminData.allowList, pubkey];
|
||||
const newDenyList = adminData.denyList.filter(p => p !== pubkey); // Remove from deny list if present
|
||||
|
||||
await updateAllowList(newAllowList);
|
||||
if (newDenyList.length !== adminData.denyList.length) {
|
||||
await updateDenyList(newDenyList);
|
||||
}
|
||||
setNewNpub('');
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Invalid npub format
|
||||
}
|
||||
};
|
||||
|
||||
const addToDenyList = async () => {
|
||||
try {
|
||||
const decoded = nip19.decode(newNpub);
|
||||
if (decoded.type === 'npub') {
|
||||
const pubkey = decoded.data as unknown as string;
|
||||
if (!adminData.denyList.includes(pubkey)) {
|
||||
const newDenyList = [...adminData.denyList, pubkey];
|
||||
const newAllowList = adminData.allowList.filter(p => p !== pubkey); // Remove from allow list if present
|
||||
|
||||
await updateDenyList(newDenyList);
|
||||
if (newAllowList.length !== adminData.allowList.length) {
|
||||
await updateAllowList(newAllowList);
|
||||
}
|
||||
setNewNpub('');
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Invalid npub format
|
||||
}
|
||||
};
|
||||
|
||||
const removeFromAllowList = async (pubkey: string) => {
|
||||
const newAllowList = adminData.allowList.filter(p => p !== pubkey);
|
||||
await updateAllowList(newAllowList);
|
||||
};
|
||||
|
||||
const removeFromDenyList = async (pubkey: string) => {
|
||||
const newDenyList = adminData.denyList.filter(p => p !== pubkey);
|
||||
await updateDenyList(newDenyList);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Add User Form */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<UserCheck className="h-5 w-5" />
|
||||
Add User to Lists
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Add users to allow list or deny list by their npub
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="npub1abc123..."
|
||||
value={newNpub}
|
||||
onChange={(e) => setNewNpub(e.target.value)}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button onClick={addToAllowList} variant="outline" className="text-green-600" disabled={isSaving}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Allow
|
||||
</Button>
|
||||
<Button onClick={addToDenyList} variant="outline" className="text-red-600" disabled={isSaving}>
|
||||
<Ban className="h-4 w-4 mr-1" />
|
||||
Deny
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{/* Allow List */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-green-600">
|
||||
<UserCheck className="h-5 w-5" />
|
||||
Allow List ({adminData.allowList.length})
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Users explicitly allowed to post content
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{adminData.allowList.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{adminData.allowList.map((pubkey) => (
|
||||
<UserListItem
|
||||
key={pubkey}
|
||||
pubkey={pubkey}
|
||||
onRemove={() => removeFromAllowList(pubkey)}
|
||||
variant="allow"
|
||||
disabled={isSaving}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm">No users in allow list</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Deny List */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-red-600">
|
||||
<Ban className="h-5 w-5" />
|
||||
Deny List ({adminData.denyList.length})
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Users blocked from posting content
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{adminData.denyList.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{adminData.denyList.map((pubkey) => (
|
||||
<UserListItem
|
||||
key={pubkey}
|
||||
pubkey={pubkey}
|
||||
onRemove={() => removeFromDenyList(pubkey)}
|
||||
variant="deny"
|
||||
disabled={isSaving}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm">No users in deny list</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BlockedWordsManagement() {
|
||||
const { data: adminData, updateBlockedWords, updateModerationSettings, isSaving } = useAdminStorage();
|
||||
const [newWord, setNewWord] = useState('');
|
||||
|
||||
const addBlockedWord = async () => {
|
||||
const word = newWord.trim();
|
||||
if (word && !adminData.blockedWords.includes(word)) {
|
||||
const newBlockedWords = [...adminData.blockedWords, word];
|
||||
await updateBlockedWords(newBlockedWords);
|
||||
setNewWord('');
|
||||
}
|
||||
};
|
||||
|
||||
const removeBlockedWord = async (word: string) => {
|
||||
const newBlockedWords = adminData.blockedWords.filter(w => w !== word);
|
||||
await updateBlockedWords(newBlockedWords);
|
||||
};
|
||||
|
||||
const handleKeyPress = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
addBlockedWord();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<MessageSquareX className="h-5 w-5" />
|
||||
Content Filtering Settings
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Configure automatic content filtering options
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch
|
||||
id="case-sensitive"
|
||||
checked={adminData.caseSensitive}
|
||||
onCheckedChange={(checked) => updateModerationSettings({ caseSensitive: checked })}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
<Label htmlFor="case-sensitive">Case sensitive matching</Label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<Switch
|
||||
id="whole-words"
|
||||
checked={adminData.wholeWordsOnly}
|
||||
onCheckedChange={(checked) => updateModerationSettings({ wholeWordsOnly: checked })}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
<Label htmlFor="whole-words">Match whole words only</Label>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Add Blocked Word</CardTitle>
|
||||
<CardDescription>
|
||||
Add words or phrases to automatically filter from content
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
placeholder="Enter word or phrase to block..."
|
||||
value={newWord}
|
||||
onChange={(e) => setNewWord(e.target.value)}
|
||||
onKeyPress={handleKeyPress}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button onClick={addBlockedWord} disabled={isSaving}>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Blocked Words ({adminData.blockedWords.length})</CardTitle>
|
||||
<CardDescription>
|
||||
Currently blocked words and phrases
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{adminData.blockedWords.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{adminData.blockedWords.map((word) => (
|
||||
<div key={word} className="flex items-center justify-between p-2 border rounded">
|
||||
<span className="font-mono text-sm">{word}</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => removeBlockedWord(word)}
|
||||
className="text-red-600 hover:text-red-700"
|
||||
disabled={isSaving}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-muted-foreground">No blocked words configured</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SiteAnalytics() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
const siteStats = useQuery({
|
||||
queryKey: ['site-analytics'],
|
||||
queryFn: async ({ signal }) => {
|
||||
const timeoutSignal = AbortSignal.timeout(1500);
|
||||
const combinedSignal = AbortSignal.any([signal, timeoutSignal]);
|
||||
|
||||
// Get recent site activity
|
||||
const recentEvents = await nostr.query([{
|
||||
kinds: [1, 30023], // Notes and articles
|
||||
limit: 100
|
||||
}], { signal: combinedSignal });
|
||||
|
||||
const uniqueAuthors = new Set(recentEvents.map(e => e.pubkey)).size;
|
||||
const last24h = recentEvents.filter(e => e.created_at > Date.now() / 1000 - 86400).length;
|
||||
const last7d = recentEvents.filter(e => e.created_at > Date.now() / 1000 - 604800).length;
|
||||
|
||||
return {
|
||||
totalEvents: recentEvents.length,
|
||||
uniqueAuthors,
|
||||
last24h,
|
||||
last7d,
|
||||
notes: recentEvents.filter(e => e.kind === 1).length,
|
||||
articles: recentEvents.filter(e => e.kind === 30023).length,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium">Total Content</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{siteStats.data?.totalEvents || 0}</div>
|
||||
<p className="text-xs text-muted-foreground">Recent events</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium">Active Users</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{siteStats.data?.uniqueAuthors || 0}</div>
|
||||
<p className="text-xs text-muted-foreground">Unique authors</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium">Last 24h</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{siteStats.data?.last24h || 0}</div>
|
||||
<p className="text-xs text-muted-foreground">New posts</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium">Last 7 days</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{siteStats.data?.last7d || 0}</div>
|
||||
<p className="text-xs text-muted-foreground">New posts</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Content Breakdown</CardTitle>
|
||||
<CardDescription>
|
||||
Distribution of content types on your site
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{siteStats.isLoading ? (
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-full" />
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<span>Notes</span>
|
||||
<Badge variant="default">{siteStats.data?.notes || 0}</Badge>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span>Articles</span>
|
||||
<Badge variant="secondary">{siteStats.data?.articles || 0}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SiteSettings() {
|
||||
const { data: adminData, updateSiteSettings, updateModerationSettings, isSaving } = useAdminStorage();
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Site Information</CardTitle>
|
||||
<CardDescription>
|
||||
Basic information about your site
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="site-name">Site Name</Label>
|
||||
<Input
|
||||
id="site-name"
|
||||
value={adminData.siteName}
|
||||
onChange={(e) => updateSiteSettings({ siteName: e.target.value })}
|
||||
placeholder="My Nostr Site"
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="site-description">Site Description</Label>
|
||||
<Textarea
|
||||
id="site-description"
|
||||
value={adminData.siteDescription}
|
||||
onChange={(e) => updateSiteSettings({ siteDescription: e.target.value })}
|
||||
placeholder="A description of your site..."
|
||||
rows={3}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Content Moderation</CardTitle>
|
||||
<CardDescription>
|
||||
Configure how content moderation works on your site
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label>Enable Content Moderation</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Apply blocked words and user lists to filter content
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={adminData.enableModeration}
|
||||
onCheckedChange={(checked) => updateModerationSettings({ enableModeration: checked })}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label>Auto-hide Blocked Content</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Automatically hide content that matches blocked words
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={adminData.autoHideBlocked}
|
||||
onCheckedChange={(checked) => updateModerationSettings({ autoHideBlocked: checked })}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label>Require Content Approval</Label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
All content must be manually approved before showing
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={adminData.requireApproval}
|
||||
onCheckedChange={(checked) => updateModerationSettings({ requireApproval: checked })}
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Environment Configuration</CardTitle>
|
||||
<CardDescription>
|
||||
Current environment settings
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2 font-mono text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span>VITE_ADMIN_NPUB:</span>
|
||||
<span className="text-muted-foreground">
|
||||
{ADMIN_NPUB ? `${ADMIN_NPUB.slice(0, 16)}...` : 'Not configured'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!ADMIN_NPUB && (
|
||||
<Alert className="mt-4">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Set VITE_ADMIN_NPUB environment variable to configure admin access.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Helper components
|
||||
function UserAvatar({ pubkey }: { pubkey: string }) {
|
||||
const author = useAuthor(pubkey);
|
||||
|
||||
return (
|
||||
<Avatar>
|
||||
<AvatarImage src={author.data?.metadata?.picture} />
|
||||
<AvatarFallback>
|
||||
{(author.data?.metadata?.name || genUserName(pubkey)).slice(0, 2).toUpperCase()}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
);
|
||||
}
|
||||
|
||||
function UserName({ pubkey }: { pubkey: string }) {
|
||||
const author = useAuthor(pubkey);
|
||||
|
||||
return (
|
||||
<span className="font-medium">
|
||||
{author.data?.metadata?.display_name || author.data?.metadata?.name || genUserName(pubkey)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function UserListItem({ pubkey, onRemove, variant, disabled }: {
|
||||
pubkey: string;
|
||||
onRemove: () => void;
|
||||
variant: 'allow' | 'deny';
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const npub = nip19.npubEncode(pubkey);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-3 p-2 rounded-lg border">
|
||||
<UserAvatar pubkey={pubkey} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-sm truncate">
|
||||
<UserName pubkey={pubkey} />
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{npub.slice(0, 20)}...
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onRemove}
|
||||
className={variant === 'allow' ? 'text-green-600 hover:text-green-700' : 'text-red-600 hover:text-red-700'}
|
||||
disabled={disabled}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+15
-4
@@ -1,11 +1,22 @@
|
||||
// Update this page (the content is just a fallback if you fail to update the page)
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
|
||||
// FIXME: Update this page (the content is just a fallback if you fail to update the page)
|
||||
|
||||
const Index = () => {
|
||||
useSeoMeta({
|
||||
title: 'Welcome to Your Blank App',
|
||||
description: 'A modern Nostr client application built with React, TailwindCSS, and Nostrify.',
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-900">
|
||||
<div className="text-center">
|
||||
<h1 className="text-4xl font-bold mb-4">Welcome to Your Blank App</h1>
|
||||
<p className="text-xl text-gray-600">Start building your amazing project here!</p>
|
||||
<h1 className="text-4xl font-bold mb-4 text-gray-900 dark:text-gray-100">
|
||||
Welcome to Your Blank App
|
||||
</h1>
|
||||
<p className="text-xl text-gray-600 dark:text-gray-400">
|
||||
Start building your amazing project here!
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import NotFound from './NotFound';
|
||||
|
||||
export function NIP19Page() {
|
||||
const { nip19: identifier } = useParams<{ nip19: string }>();
|
||||
|
||||
if (!identifier) {
|
||||
return <NotFound />;
|
||||
}
|
||||
|
||||
let decoded;
|
||||
try {
|
||||
decoded = nip19.decode(identifier);
|
||||
} catch {
|
||||
return <NotFound />;
|
||||
}
|
||||
|
||||
const { type } = decoded;
|
||||
|
||||
switch (type) {
|
||||
case 'npub':
|
||||
case 'nprofile':
|
||||
// AI agent should implement profile view here
|
||||
return <div>Profile placeholder</div>;
|
||||
|
||||
case 'note':
|
||||
// AI agent should implement note view here
|
||||
return <div>Note placeholder</div>;
|
||||
|
||||
case 'nevent':
|
||||
// AI agent should implement event view here
|
||||
return <div>Event placeholder</div>;
|
||||
|
||||
case 'naddr':
|
||||
// AI agent should implement addressable event view here
|
||||
return <div>Addressable event placeholder</div>;
|
||||
|
||||
default:
|
||||
return <NotFound />;
|
||||
}
|
||||
}
|
||||
+10
-4
@@ -1,9 +1,15 @@
|
||||
import { useSeoMeta } from "@unhead/react";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { useEffect } from "react";
|
||||
|
||||
const NotFound = () => {
|
||||
const location = useLocation();
|
||||
|
||||
useSeoMeta({
|
||||
title: "404 - Page Not Found",
|
||||
description: "The page you are looking for could not be found. Return to the home page to continue browsing.",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
console.error(
|
||||
"404 Error: User attempted to access non-existent route:",
|
||||
@@ -12,11 +18,11 @@ const NotFound = () => {
|
||||
}, [location.pathname]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-900">
|
||||
<div className="text-center">
|
||||
<h1 className="text-4xl font-bold mb-4">404</h1>
|
||||
<p className="text-xl text-gray-600 mb-4">Oops! Page not found</p>
|
||||
<a href="/" className="text-blue-500 hover:text-blue-700 underline">
|
||||
<h1 className="text-4xl font-bold mb-4 text-gray-900 dark:text-gray-100">404</h1>
|
||||
<p className="text-xl text-gray-600 dark:text-gray-400 mb-4">Oops! Page not found</p>
|
||||
<a href="/" className="text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 underline">
|
||||
Return to Home
|
||||
</a>
|
||||
</div>
|
||||
|
||||
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user