95 Commits
Author SHA1 Message Date
Chad Curtis c0dca78709 Admin Dashboard init 2025-09-02 00:09:46 +00:00
Chad Curtis d1744b7d71 Merge branch 'infiniteScroll' into 'main'
Add context for pagination (i.e., infinite feed scroll)

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

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

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

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

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

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

Closes #9

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

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

See merge request soapbox-pub/mkstack!8
2025-07-09 14:36:03 +00:00
Derek Ross 414e0bf029 feat: add gemini-cli support 2025-07-08 23:04:45 -04:00
Chad Curtis 7b49400951 fix login state not being reset after using key file upload method 2025-07-08 14:30:15 +00:00
Chad Curtis e226ec42a5 Make wording and icons generic 2025-07-08 14:19:17 +00:00
Chad Curtis baaf7e6ab4 Pull signup flow from Treasures 2025-07-08 13:54:02 +00:00
Alex Gleason 39afb03570 Stronger language against writing unnecessary tests 2025-07-06 18:44:42 -05:00
Alex Gleason 83db2fd539 CONTEXT.md: advise to add "alt" tags 2025-07-05 19:14:30 -05:00
Alex Gleason a2eab78ae3 Improve AppConfigSchema type 2025-07-05 17:50:21 -05:00
Alex Gleason 65b974fb41 vitest: suppress DOM output that exceeds AI context windows 2025-07-05 12:45:16 -05:00
Alex Gleason cadbc02947 Remove unused goose recipe file 2025-07-05 12:33:59 -05:00
Alex Gleason 37aaadbd70 gitignore .env files 2025-07-05 12:33:22 -05:00
65 changed files with 6385 additions and 3335 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
CONTEXT.md
+7
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
../.mcp.json
-1
View File
@@ -1 +0,0 @@
../CONTEXT.md
+6
View File
@@ -11,6 +11,7 @@ node_modules
dist dist
dist-ssr dist-ssr
*.local *.local
.ai/
# Editor directories and files # Editor directories and files
.idea .idea
@@ -23,3 +24,8 @@ dist-ssr
# Vercel # Vercel
.vercel .vercel
# Secrets
.env
.env.*
!.env.example
+4 -7
View File
@@ -5,16 +5,13 @@ default:
timeout: 1 minute timeout: 1 minute
stages: stages:
- build - test
- deploy - deploy
build: test:
stage: build stage: test
script: script:
- npm run build - npm run test
only:
variables:
- $CI_DEFAULT_BRANCH != $CI_COMMIT_REF_NAME
pages: pages:
stage: deploy stage: deploy
-1
View File
@@ -1 +0,0 @@
CONTEXT.md
-16
View File
@@ -1,16 +0,0 @@
# jsr registry should not be edited or removed
.npmrc
# vite client types are needed
src/vite-env.d.ts
# tsconfig is stable and working correctly, so should not be edited
tsconfig.json
tsconfig.app.json
tsconfig.node.json
# postcss config for Tailwind is stable and working correctly, so should not be edited unless upgrading Tailwind to v4
postcss.config.js
# vite config is stable and usually should not need to be edited
vite.config.ts
+6 -1
View File
@@ -1,9 +1,14 @@
{ {
"mcpServers": { "mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": { "nostr": {
"type": "stdio", "type": "stdio",
"command": "npx", "command": "npx",
"args": ["-y", "xjsr", "@nostrbook/mcp"] "args": ["-y", "@nostrbook/mcp@latest"]
} }
} }
} }
+6 -1
View File
@@ -1,9 +1,14 @@
{ {
"servers": { "servers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": { "nostr": {
"type": "stdio", "type": "stdio",
"command": "npx", "command": "npx",
"args": ["-y", "xjsr", "@nostrbook/mcp"] "args": ["-y", "@nostrbook/mcp@latest"]
} }
} }
} }
+170
View File
@@ -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
+1061
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1 +1 @@
CONTEXT.md AGENTS.md
-849
View File
@@ -1,849 +0,0 @@
# Project Overview
This project is a Nostr client application built with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
## Technology Stack
- **React 18.x**: Stable version of React with hooks, concurrent rendering, and improved performance
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
- **Vite**: Fast build tool and development server
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
- **TanStack Query**: For data fetching, caching, and state management
- **TypeScript**: For type-safe JavaScript development
## Project Structure
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
- `useAuthor`: Fetch user profile data by pubkey
- `useCurrentUser`: Get currently logged-in user
- `useNostrPublish`: Publish events to Nostr
- `useUploadFile`: Upload files via Blossom servers
- `useAppContext`: Access global app configuration
- `useTheme`: Theme management
- `useToast`: Toast notifications
- `useLocalStorage`: Persistent local storage
- `useLoggedInAccounts`: Manage multiple accounts
- `useLoginActions`: Authentication actions
- `useIsMobile`: Responsive design helper
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext)
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
- `AppRouter.tsx`: React Router configuration
## UI Components
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
- **Accordion**: Vertically collapsing content panels
- **Alert**: Displays important messages to users
- **AlertDialog**: Modal dialog for critical actions requiring confirmation
- **AspectRatio**: Maintains consistent width-to-height ratio
- **Avatar**: User profile pictures with fallback support
- **Badge**: Small status descriptors for UI elements
- **Breadcrumb**: Navigation aid showing current location in hierarchy
- **Button**: Customizable button with multiple variants and sizes
- **Calendar**: Date picker component
- **Card**: Container with header, content, and footer sections
- **Carousel**: Slideshow for cycling through elements
- **Chart**: Data visualization component
- **Checkbox**: Selectable input element
- **Collapsible**: Toggle for showing/hiding content
- **Command**: Command palette for keyboard-first interfaces
- **ContextMenu**: Right-click menu component
- **Dialog**: Modal window overlay
- **Drawer**: Side-sliding panel (using vaul)
- **DropdownMenu**: Menu that appears from a trigger element
- **Form**: Form validation and submission handling
- **HoverCard**: Card that appears when hovering over an element
- **InputOTP**: One-time password input field
- **Input**: Text input field
- **Label**: Accessible form labels
- **Menubar**: Horizontal menu with dropdowns
- **NavigationMenu**: Accessible navigation component
- **Pagination**: Controls for navigating between pages
- **Popover**: Floating content triggered by a button
- **Progress**: Progress indicator
- **RadioGroup**: Group of radio inputs
- **Resizable**: Resizable panels and interfaces
- **ScrollArea**: Scrollable container with custom scrollbars
- **Select**: Dropdown selection component
- **Separator**: Visual divider between content
- **Sheet**: Side-anchored dialog component
- **Sidebar**: Navigation sidebar component
- **Skeleton**: Loading placeholder
- **Slider**: Input for selecting a value from a range
- **Sonner**: Toast notification manager
- **Switch**: Toggle switch control
- **Table**: Data table with headers and rows
- **Tabs**: Tabbed interface component
- **Textarea**: Multi-line text input
- **Toast**: Toast notification component
- **ToggleGroup**: Group of toggle buttons
- **Toggle**: Two-state button
- **Tooltip**: Informational text that appears on hover
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
## System Prompt Management
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
1. Edit CONTEXT.md directly
2. The changes take effect in the next session
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
## Nostr Protocol Integration
This project comes with custom hooks for querying and publishing events on the Nostr network.
### Nostr Implementation Guidelines
- Always use the `nostr__read_nips_index` tool before implementing any Nostr features to see what kinds are currently in use across all NIPs.
- If any existing kind or NIP might offer the required functionality, use the `nostr__read_nip` tool to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers with the `nostr__generate_kind` tool if no existing suitable kinds are found after comprehensive research.
Knowing when to create a new kind versus reusing an existing kind requires careful judgement. Introducing new kinds means the project won't be interoperable with existing clients. But deviating too far from the schema of a particular kind can cause different interoperability issues.
#### Choosing Between Existing NIPs and Custom Kinds
When implementing features that could use existing NIPs, follow this decision framework:
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Use the `nostr__read_nips_index` tool to get an overview, and then `nostr__read_nip` and `nostr__read_kind` to investigate any potentially relevant NIPs or kinds in detail. The goal is to find the closest existing solution.
2. **Prioritize Existing NIPs**: Always prefer extending or using existing NIPs over creating custom kinds, even if they require minor compromises in functionality.
3. **Interoperability vs. Perfect Fit**: Consider the trade-off between:
- **Interoperability**: Using existing kinds means compatibility with other Nostr clients
- **Perfect Schema**: Custom kinds allow perfect data modeling but create ecosystem fragmentation
4. **Extension Strategy**: When existing NIPs are close but not perfect:
- Use the existing kind as the base
- Add domain-specific tags for additional metadata
- Document the extensions in `NIP.md`
5. **When to Generate Custom Kinds**:
- No existing NIP covers the core functionality
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
**Example Decision Process**:
```
Need: Equipment marketplace for farmers
Options:
1. NIP-15 (Marketplace) - Too structured for peer-to-peer sales
2. NIP-99 (Classified Listings) - Good fit, can extend with farming tags
3. Custom kind - Perfect fit but no interoperability
Decision: Use NIP-99 + farming-specific tags for best balance
```
#### Tag Design Principles
When designing tags for Nostr events, follow these principles:
1. **Kind vs Tags Separation**:
- **Kind** = Schema/structure (how the data is organized)
- **Tags** = Semantics/categories (what the data represents)
- Don't create different kinds for the same data structure
2. **Use Single-Letter Tags for Categories**:
- **Relays only index single-letter tags** for efficient querying
- Use `t` tags for categorization, not custom multi-letter tags
- Multiple `t` tags allow items to belong to multiple categories
3. **Relay-Level Filtering**:
- Design tags to enable efficient relay-level filtering with `#t: ["category"]`
- Avoid client-side filtering when relay-level filtering is possible
- Consider query patterns when designing tag structure
4. **Tag Examples**:
```json
// ❌ Wrong: Multi-letter tag, not queryable at relay level
["product_type", "electronics"]
// ✅ Correct: Single-letter tag, relay-indexed and queryable
["t", "electronics"]
["t", "smartphone"]
["t", "android"]
```
5. **Querying Best Practices**:
```typescript
// ❌ Inefficient: Get all events, filter in JavaScript
const events = await nostr.query([{ kinds: [30402] }]);
const filtered = events.filter(e => hasTag(e, 'product_type', 'electronics'));
// ✅ Efficient: Filter at relay level
const events = await nostr.query([{ kinds: [30402], '#t': ['electronics'] }]);
```
#### `t` Tag Filtering for Community-Specific Content
For applications focused on a specific community or niche, you can use `t` tags to filter events for the target audience.
**When to Use:**
- ✅ Community apps: "farmers" → `t: "farming"`, "Poland" → `t: "poland"`
- ❌ Generic platforms: Twitter clones, general Nostr clients
**Implementation:**
```typescript
// Publishing with community tag
createEvent({
kind: 1,
content: data.content,
tags: [['t', 'farming']]
});
// Querying community content
const events = await nostr.query([{
kinds: [1],
'#t': ['farming'],
limit: 20
}], { signal });
```
### Kind Ranges
An event's kind number determines the event's behavior and storage characteristics:
- **Regular Events** (1000 ≤ kind < 10000): Expected to be stored by relays permanently. Used for persistent content like notes, articles, etc.
- **Replaceable Events** (10000 ≤ kind < 20000): Only the latest event per pubkey+kind combination is stored. Used for profile metadata, contact lists, etc.
- **Addressable Events** (30000 ≤ kind < 40000): Identified by pubkey+kind+d-tag combination, only latest per combination is stored. Used for articles, long-form content, etc.
Kinds below 1000 are considered "legacy" kinds, and may have different storage characteristics based on their kind definition. For example, kind 1 is regular, while kind 3 is replaceable.
### Content Field Design Principles
When designing new event kinds, the `content` field should be used for semantically important data that doesn't need to be queried by relays. **Structured JSON data generally shouldn't go in the content field** (kind 0 being an early exception).
#### Guidelines
- **Use content for**: Large text, freeform human-readable content, or existing industry-standard JSON formats (Tiled maps, FHIR, GeoJSON)
- **Use tags for**: Queryable metadata, structured data, anything that needs relay-level filtering
- **Empty content is valid**: Many events need only tags with `content: ""`
- **Relays only index tags**: If you need to filter by a field, it must be a tag
#### Example
**✅ Good - queryable data in tags:**
```json
{
"kind": 30402,
"content": "",
"tags": [["d", "product-123"], ["title", "Camera"], ["price", "250"], ["t", "photography"]]
}
```
**❌ Bad - structured data in content:**
```json
{
"kind": 30402,
"content": "{\"title\":\"Camera\",\"price\":250,\"category\":\"photo\"}",
"tags": [["d", "product-123"]]
}
```
### NIP.md
The file `NIP.md` is used by this project to define a custom Nostr protocol document. If the file doesn't exist, it means this project doesn't have any custom kinds associated with it.
Whenever new kinds are generated, the `NIP.md` file in the project must be created or updated to document the custom event schema. Whenever the schema of one of these custom events changes, `NIP.md` must also be updated accordingly.
### The `useNostr` Hook
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
```typescript
import { useNostr } from '@nostrify/react';
function useCustomHook() {
const { nostr } = useNostr();
// ...
}
```
### Query Nostr Data with `useNostr` and Tanstack Query
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
```typescript
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/query';
function usePosts() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['posts'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [1], limit: 20 }], { signal });
return events; // these events could be transformed into another format
},
});
}
```
#### Efficient Query Design
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
**✅ Efficient - Single query with multiple kinds:**
```typescript
// Query multiple event types in one request
const events = await nostr.query([
{
kinds: [1, 6, 16], // All repost kinds in one query
'#e': [eventId],
limit: 150,
}
], { signal });
// Separate by type in JavaScript
const notes = events.filter((e) => e.kind === 1);
const reposts = events.filter((e) => e.kind === 6);
const genericReposts = events.filter((e) => e.kind === 16);
```
**❌ Inefficient - Multiple separate queries:**
```typescript
// This creates unnecessary load and can trigger rate limiting
const [notes, reposts, genericReposts] = await Promise.all([
nostr.query([{ kinds: [1], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [6], '#e': [eventId] }], { signal }),
nostr.query([{ kinds: [16], '#e': [eventId] }], { signal }),
]);
```
**Query Optimization Guidelines:**
1. **Combine kinds**: Use `kinds: [1, 6, 16]` instead of separate queries
2. **Use multiple filters**: When you need different tag filters, use multiple filter objects in a single query
3. **Adjust limits**: When combining queries, increase the limit appropriately
4. **Filter in JavaScript**: Separate event types after receiving results rather than making multiple requests
5. **Consider relay capacity**: Each query consumes relay resources and may count against rate limits
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
#### Event Validation
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
```typescript
// Example validator function for NIP-52 calendar events
function validateCalendarEvent(event: NostrEvent): boolean {
// Check if it's a calendar event kind
if (![31922, 31923].includes(event.kind)) return false;
// Check for required tags according to NIP-52
const d = event.tags.find(([name]) => name === 'd')?.[1];
const title = event.tags.find(([name]) => name === 'title')?.[1];
const start = event.tags.find(([name]) => name === 'start')?.[1];
// All calendar events require 'd', 'title', and 'start' tags
if (!d || !title || !start) return false;
// Additional validation for date-based events (kind 31922)
if (event.kind === 31922) {
// start tag should be in YYYY-MM-DD format for date-based events
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
if (!dateRegex.test(start)) return false;
}
// Additional validation for time-based events (kind 31923)
if (event.kind === 31923) {
// start tag should be a unix timestamp for time-based events
const timestamp = parseInt(start);
if (isNaN(timestamp) || timestamp <= 0) return false;
}
return true;
}
function useCalendarEvents() {
const { nostr } = useNostr();
return useQuery({
queryKey: ['calendar-events'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(1500)]);
const events = await nostr.query([{ kinds: [31922, 31923], limit: 20 }], { signal });
// Filter events through validator to ensure they meet NIP-52 requirements
return events.filter(validateCalendarEvent);
},
});
}
```
### The `useAuthor` Hook
To display profile data for a user by their Nostr pubkey (such as an event author), use the `useAuthor` hook.
```tsx
import type { NostrEvent, NostrMetadata } from '@nostrify/nostrify';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
function Post({ event }: { event: NostrEvent }) {
const author = useAuthor(event.pubkey);
const metadata: NostrMetadata | undefined = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(event.pubkey);
const profileImage = metadata?.picture;
// ...render elements with this data
}
```
#### `NostrMetadata` type
```ts
/** Kind 0 metadata. */
interface NostrMetadata {
/** A short description of the user. */
about?: string;
/** A URL to a wide (~1024x768) picture to be optionally displayed in the background of a profile screen. */
banner?: string;
/** A boolean to clarify that the content is entirely or partially the result of automation, such as with chatbots or newsfeeds. */
bot?: boolean;
/** An alternative, bigger name with richer characters than `name`. `name` should always be set regardless of the presence of `display_name` in the metadata. */
display_name?: string;
/** A bech32 lightning address according to NIP-57 and LNURL specifications. */
lud06?: string;
/** An email-like lightning address according to NIP-57 and LNURL specifications. */
lud16?: string;
/** A short name to be displayed for the user. */
name?: string;
/** An email-like Nostr address according to NIP-05. */
nip05?: string;
/** A URL to the user's avatar. */
picture?: string;
/** A web URL related in any way to the event author. */
website?: string;
}
```
### The `useNostrPublish` Hook
To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
```tsx
import { useState } from 'react';
import { useCurrentUser } from "@/hooks/useCurrentUser";
import { useNostrPublish } from '@/hooks/useNostrPublish';
export function MyComponent() {
const [ data, setData] = useState<Record<string, string>>({});
const { user } = useCurrentUser();
const { mutate: createEvent } = useNostrPublish();
const handleSubmit = () => {
createEvent({ kind: 1, content: data.content });
};
if (!user) {
return <span>You must be logged in to use this form.</span>;
}
return (
<form onSubmit={handleSubmit} disabled={!user}>
{/* ...some input fields */}
</form>
);
}
```
The `useCurrentUser` hook should be used to ensure that the user is logged in before they are able to publish Nostr events.
### Nostr Login
To enable login with Nostr, simply use the `LoginArea` component already included in this project.
```tsx
import { LoginArea } from "@/components/auth/LoginArea";
function MyComponent() {
return (
<div>
{/* other components ... */}
<LoginArea className="max-w-60" />
</div>
);
}
```
The `LoginArea` component handles all the login-related UI and interactions, including displaying login dialogs and switching between accounts. It should not be wrapped in any conditional logic.
`LoginArea` displays a "Log in" button when the user is logged out, and changes to an account switcher once the user is logged in. It is an inline-flex element by default. To make it expand to the width of its container, you can pass a className like `flex` (to make it a block element) or `w-full`. If it is left as inline-flex, it's recommended to set a max width.
### `npub`, `naddr`, and other Nostr addresses
Nostr defines a set identifiers in NIP-19. Their prefixes:
- `npub`: public keys
- `nsec`: private keys
- `note`: note ids
- `nprofile`: a nostr profile
- `nevent`: a nostr event
- `naddr`: a nostr replaceable event coordinate
- `nrelay`: a nostr relay (deprecated)
NIP-19 identifiers include a prefix, the number "1", then a base32-encoded data string.
#### Use in Filters
The base Nostr protocol uses hex string identifiers when filtering by event IDs and pubkeys. Nostr filters only accept hex strings.
```ts
// ❌ Wrong: naddr is not decoded
const events = await nostr.query(
[{ ids: [naddr] }],
{ signal }
);
```
Corrected example:
```ts
// Import nip19 from nostr-tools
import { nip19 } from 'nostr-tools';
// Decode a NIP-19 identifier
const decoded = nip19.decode(value);
// Optional: guard certain types (depending on the use-case)
if (decoded.type !== 'naddr') {
throw new Error('Unsupported Nostr identifier');
}
// Get the addr object
const naddr = decoded.data;
// ✅ Correct: naddr is expanded into the correct filter
const events = await nostr.query(
[{
kinds: [naddr.kind],
authors: [naddr.pubkey],
'#d': [naddr.identifier],
}],
{ signal }
);
```
#### Use in URL Paths
For URL routing, use NIP-19 identifiers as path parameters (e.g., `/:nip19`) to create secure, universal links to Nostr events. Decode the identifier and render the appropriate component based on the type:
- Regular events: Use `/nevent1...` paths
- Replaceable/addressable events: Use `/naddr1...` paths
Always use `naddr` identifiers for addressable events instead of just the `d` tag value, as `naddr` contains the author pubkey needed to create secure filters. This prevents security issues where malicious actors could publish events with the same `d` tag to override content.
```ts
// Secure routing with naddr
const decoded = nip19.decode(params.nip19);
if (decoded.type === 'naddr' && decoded.data.kind === 30024) {
// Render ArticlePage component
}
```
### Nostr Edit Profile
To include an Edit Profile form, place the `EditProfileForm` component in the project:
```tsx
import { EditProfileForm } from "@/components/EditProfileForm";
function EditProfilePage() {
return (
<div>
{/* you may want to wrap this in a layout or include other components depending on the project ... */}
<EditProfileForm />
</div>
);
}
```
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
### Uploading Files on Nostr
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
```tsx
import { useUploadFile } from "@/hooks/useUploadFile";
function MyComponent() {
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const handleUpload = async (file: File) => {
try {
// Provides an array of NIP-94 compatible tags
// The first tag in the array contains the URL
const [[_, url]] = await uploadFile(file);
// ...use the url
} catch (error) {
// ...handle errors
}
};
// ...rest of component
}
```
To attach files to kind 1 events, each file's URL should be appended to the event's `content`, and an `imeta` tag should be added for each file. For kind 0 events, the URL by itself can be used in relevant fields of the JSON content.
### Nostr Encryption and Decryption
The logged-in user has a `signer` object (matching the NIP-07 signer interface) that can be used for encryption and decryption. The signer's nip44 methods handle all cryptographic operations internally, including key derivation and conversation key management, so you never need direct access to private keys. Always use the signer interface for encryption rather than requesting private keys from users, as this maintains security and follows best practices.
```ts
// Get the current user
const { user } = useCurrentUser();
// Optional guard to check that nip44 is available
if (!user.signer.nip44) {
throw new Error("Please upgrade your signer extension to a version that supports NIP-44 encryption");
}
// Encrypt message to self
const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
// Decrypt message to self
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
```
### Rendering Rich Text Content
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
```tsx
import { NoteContent } from "@/components/NoteContent";
export function Post(/* ...props */) {
// ...
return (
<CardContent className="pb-2">
<div className="whitespace-pre-wrap break-words">
<NoteContent event={post} className="text-sm" />
</div>
</CardContent>
);
}
```
## App Configuration
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
```typescript
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.nostr.band",
};
```
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
## Routing
The project uses React Router with a centralized routing configuration in `AppRouter.tsx`. To add new routes:
1. Create your page component in `/src/pages/`
2. Import it in `AppRouter.tsx`
3. Add the route above the catch-all `*` route:
```tsx
<Route path="/your-path" element={<YourComponent />} />
```
The router includes automatic scroll-to-top functionality and a 404 NotFound page for unmatched routes.
## Development Practices
- Uses React Query for data fetching and caching
- Follows shadcn/ui component patterns
- Implements Path Aliases with `@/` prefix for cleaner imports
- Uses Vite for fast development and production builds
- Component-based architecture with React hooks
- Default connection to one Nostr relay for best performance
- Comprehensive provider setup with NostrLoginProvider, QueryClientProvider, and custom AppProvider
- **Never use the `any` type**: Always use proper TypeScript types for type safety
## Loading States
**Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
```tsx
// Skeleton example matching component structure
<Card>
<CardHeader>
<div className="flex items-center space-x-3">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
</CardContent>
</Card>
```
### Empty States and No Content Found
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
```tsx
import { RelaySelector } from '@/components/RelaySelector';
import { Card, CardContent } from '@/components/ui/card';
// Empty state example
<div className="col-span-full">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
No results found. Try another relay?
</p>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
</div>
```
## Design Customization
**Tailor the site's look and feel based on the user's specific request.** This includes:
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
### Adding Fonts
To add custom fonts, follow these steps:
1. **Install a font package** using the `js-dev__npm_add_package` tool:
**Any Google Font can be installed** using the @fontsource packages. Examples:
- For Inter Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/inter" })`
- For Roboto: `js-dev__npm_add_package({ name: "@fontsource/roboto" })`
- For Outfit Variable: `js-dev__npm_add_package({ name: "@fontsource-variable/outfit" })`
- For Poppins: `js-dev__npm_add_package({ name: "@fontsource/poppins" })`
- For Open Sans: `js-dev__npm_add_package({ name: "@fontsource/open-sans" })`
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
2. **Import the font** in `src/main.tsx`:
```typescript
import '@fontsource-variable/<font-name>';
```
3. **Update Tailwind configuration** in `tailwind.config.ts`:
```typescript
export default {
theme: {
extend: {
fontFamily: {
sans: ['Inter Variable', 'Inter', 'system-ui', 'sans-serif'],
},
},
},
}
```
### Recommended Font Choices by Use Case
- **Modern/Clean**: Inter Variable, Outfit Variable, or Manrope
- **Professional/Corporate**: Roboto, Open Sans, or Source Sans Pro
- **Creative/Artistic**: Poppins, Nunito, or Comfortaa
- **Technical/Code**: JetBrains Mono, Fira Code, or Source Code Pro (for monospace)
### Theme System
The project includes a complete light/dark theme system using CSS custom properties. The theme can be controlled via:
- `useTheme` hook for programmatic theme switching
- CSS custom properties defined in `src/index.css`
- Automatic dark mode support with `.dark` class
### Color Scheme Implementation
When users specify color schemes:
- Update CSS custom properties in `src/index.css` (both `:root` and `.dark` selectors)
- Use Tailwind's color palette or define custom colors
- Ensure proper contrast ratios for accessibility
- Apply colors consistently across components (buttons, links, accents)
- Test both light and dark mode variants
### Component Styling Patterns
- Use `cn()` utility for conditional class merging
- Follow shadcn/ui patterns for component variants
- Implement responsive design with Tailwind breakpoints
- Add hover and focus states for interactive elements
## Writing Tests
**Important for AI Assistants**: Only create tests when the user is experiencing a specific problem or explicitly requests tests. Do not proactively write tests for new features or components unless the user is having issues that require testing to diagnose or resolve.
### Test Setup
The project uses Vitest with jsdom environment and includes comprehensive test setup:
- **Testing Library**: React Testing Library with jest-dom matchers
- **Test Environment**: jsdom with mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
- **Test App**: `TestApp` component provides all necessary context providers for testing
The project includes a `TestApp` component that provides all necessary context providers for testing. Wrap components with this component to provide required context providers:
```tsx
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { MyComponent } from './MyComponent';
describe('MyComponent', () => {
it('renders correctly', () => {
render(
<TestApp>
<MyComponent />
</TestApp>
);
expect(screen.getByText('Expected text')).toBeInTheDocument();
});
});
```
## Testing Your Changes
Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
**Your task is not considered finished until this test passes without errors.**
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+140 -77
View File
@@ -1,116 +1,179 @@
# NIP-GNOME: Gnome Speak Translation Protocol # NIP-XX: Site Administration Events
`draft` `optional`
## Abstract ## Abstract
This NIP defines a client-side translation protocol for converting kind 1 (Short Text Note) events into "Gnome Speak" - a whimsical fantasy language that transforms regular text into gnome-themed vocabulary and expressions. 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.
## Motivation
To create an immersive and entertaining experience for users of gnome-themed Nostr clients, where all text content is automatically translated into a consistent fantasy language that maintains readability while adding magical woodland charm.
## Specification ## Specification
### Translation Scope ### Event Kind
- **MUST** translate all kind 1 events (Short Text Notes) into Gnome Speak This NIP introduces event kind `39767` for site administration data.
- **SHOULD NOT** translate other event kinds to maintain protocol compatibility
- **MUST** preserve original URLs, Nostr references (npub, note, etc.), and hashtags without translation
- **SHOULD** maintain the semantic meaning of the original text
### Translation Rules ### Event Structure
#### Vocabulary Substitution Site administration events are **addressable events** that use the `d` tag to identify different configuration categories.
Common words are replaced with gnome-themed equivalents: ```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>"
}
```
- Greetings: `hello` → `greetings, fellow earth-dweller` ### Content Schema
- Technology: `computer` → `thinking-box of metal and magic`
- Time: `today` → `this blessed sun-cycle`
- Actions: `go` → `venture forth`
- People: `friend` → `companion of the woodland path`
#### Gnome Expressions The `content` field contains a JSON object with the following structure:
- Exclamations are enhanced with gnome phrases: `!` → `! By my pointy hat!` ```json
- Sentence starters may be added: `In the sacred grove, ...` {
- Sentence endings may be appended: `...as the ancients foretold.` "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"
}
```
#### Special Formatting #### Field Descriptions
- Bitcoin/crypto terms: `bitcoin` → `✨golden acorns of the digital realm✨` - **`hiddenEvents`**: Array of event IDs that have been manually hidden by the administrator
- Nostr terms: `nostr` → `🍄message-mushroom🍄` - **`allowList`**: Array of pubkeys explicitly allowed to post content (if not empty, only these users can post)
- Greetings: `gm` → `🌅when dew kisses the earth🌅` - **`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
### Implementation ### 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 #### 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
Clients implementing this NIP: ### Security Considerations
1. **MUST** detect kind 1 events - Administration events contain sensitive moderation data and should only be published by authorized administrators
2. **MUST** apply Gnome Speak translation before displaying content - The `alt` tag provides human-readable context for the event purpose
3. **SHOULD** preserve original content for editing/replying - Clients should validate the JSON content structure before applying policies
4. **MAY** provide toggle to view original content - Consider implementing rate limiting for administration event updates
5. **SHOULD** indicate when content has been translated
#### Content Preservation ### Rationale
- Original event content **MUST** remain unchanged in storage/transmission This NIP addresses the need for persistent, cross-device site administration in decentralized Nostr applications. By storing policies as Nostr events, administrators can:
- Translation occurs only at display time
- Replies and quotes **SHOULD** reference original content, not translated
#### Tag Usage - Maintain consistent moderation across multiple devices
- Backup and restore moderation settings
- Share administrative responsibilities (with proper key management)
- Maintain audit trails of policy changes
Clients **MAY** add a `t` tag with value `gnome` to indicate gnome-themed content: The addressable event structure allows for future expansion with additional configuration categories using different `d` tag values.
## Examples
### Basic Moderation Setup
```json ```json
{ {
"kind": 1, "kind": 39767,
"content": "Hello world!", "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": [["t", "gnome"]], "tags": [
... ["d", "admin-config"],
["alt", "Site administration configuration and policies"]
]
} }
``` ```
### Example ### Allowlist-Only Community
Original event:
```json ```json
{ {
"kind": 1, "kind": 39767,
"content": "Good morning! Having coffee and checking bitcoin prices.", "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": [], "tags": [
... ["d", "admin-config"],
["alt", "Site administration configuration and policies"]
]
} }
``` ```
Displayed as:
```
"When dew kisses the earth! Partaking of bitter bean brew and witnessing ✨golden acorns of the digital realm✨ values, blessed by the forest spirits."
```
## Rationale
This approach provides:
1. **Immersive Experience**: Creates a consistent fantasy atmosphere
2. **Protocol Compatibility**: No changes to underlying Nostr protocol
3. **Reversibility**: Original content always preserved
4. **Interoperability**: Non-gnome clients display original content normally
## Security Considerations
- Translation is purely cosmetic and doesn't affect event integrity
- Original content validation remains unchanged
- No additional attack vectors introduced
## Implementation Status
This NIP is implemented in Gnome Nostr client as a client-side translation layer.
## References ## References
- [NIP-01: Basic protocol flow description](https://github.com/nostr-protocol/nips/blob/master/01.md) - [NIP-01: Basic protocol flow description](https://github.com/nostr-protocol/nips/blob/master/01.md)
- [NIP-10: Text Notes and Threads](https://github.com/nostr-protocol/nips/blob/master/10.md) - [NIP-31: Dealing with Unknown Events](https://github.com/nostr-protocol/nips/blob/master/31.md)
+9 -76
View File
@@ -1,79 +1,12 @@
# 🍄 Gnome Nostr - The Sacred Network of Woodland Folk # MKStack
A magical Nostr client where all text notes (kind 1 events) are automatically translated into the ancient gnome tongue! Connect with fellow earth-dwellers across the message-mushroom network. Template for building Nostr client application with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
## ✨ Features ## Features
- **🍄 Gnome Speak Translation**: All kind 1 events are automatically translated into whimsical gnome language - **Site Administration**: Content moderation and site management dashboard at `/admin` (see [ADMIN_DASHBOARD.md](ADMIN_DASHBOARD.md))
- **🌲 Forest-Themed UI**: Beautiful gnome-inspired design with earthy colors and woodland aesthetics - **Nostr Protocol Integration**: Full NIP support with custom hooks for querying and publishing
- **🔗 Full Nostr Compatibility**: Works with any Nostr relay and preserves all protocol functionality - **Authentication**: Secure login with NIP-07 browser extensions, bunker connections, and secret keys
- **📱 Responsive Design**: Works perfectly on desktop and mobile devices - **UI Components**: 48+ accessible components from shadcn/ui
- **🌙 Dark/Light Mode**: Toggle between day forest and night forest themes - **Responsive Design**: Mobile-first approach with Tailwind CSS
- **⚡ Lightning Fast**: Built with modern React, Vite, and TailwindCSS - **Type Safety**: Full TypeScript support with proper error handling
## 🎭 Gnome Speak Examples
Regular text is magically transformed:
- `"Hello world!"` → `"Greetings, fellow earth-dweller world! By my pointy hat!"`
- `"Good morning everyone"` → `"🌅When dew kisses the earth🌅 all forest folk"`
- `"I love bitcoin"` → `"I cherish like precious gems ✨golden acorns of the digital realm✨"`
- `"This is about #nostr"` → `"This is a woodland proclamation about #nostr"` (hashtags preserved)
## 🛡️ Protocol Preservation
While the display is transformed into gnome speak, the underlying Nostr protocol remains unchanged:
- ✅ URLs are preserved and linkified
- ✅ Nostr references (npub, note, etc.) work normally
- ✅ Hashtags remain functional for filtering
- ✅ Original content is preserved for replies and quotes
- ✅ Compatible with all other Nostr clients
## 🏗️ Technical Details
- **Framework**: React 18 with TypeScript
- **Styling**: TailwindCSS with custom gnome theme
- **Nostr**: Nostrify for protocol integration
- **Font**: Comfortaa Variable for whimsical feel
- **Build**: Vite for fast development and production builds
## 🌟 Custom NIP
This client implements a custom translation protocol documented in `NIP.md`. The translation:
- Only affects kind 1 events (Short Text Notes)
- Preserves URLs, Nostr references, and hashtags
- Maintains semantic meaning while adding magical charm
- Is purely client-side - no protocol changes required
## 🚀 Getting Started
1. **Clone the repository**
2. **Install dependencies**: `npm install`
3. **Start development**: `npm run dev`
4. **Build for production**: `npm run build`
## 🎨 Customization
The gnome vocabulary can be extended in `src/lib/gnomeSpeak.ts`. Add new word mappings to enhance the magical transformation!
## 🤝 Contributing
Contributions are welcome! Whether you want to:
- Add more gnome vocabulary
- Improve the forest-themed UI
- Fix bugs or add features
- Enhance the translation algorithm
Feel free to open issues and pull requests.
## 📜 License
This project is open source and available under the MIT License.
---
*Vibed with [MKStack](https://soapbox.pub/mkstack) • Blessed by the forest spirits 🍄✨*
**May your mushrooms grow tall and your acorns be golden!** 🌰✨
-16
View File
@@ -1,16 +0,0 @@
{
"model": "claude-sonnet-4",
"temperature": 0.2,
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
-1
View File
@@ -1 +0,0 @@
CONTEXT.md
-1
View File
@@ -1 +0,0 @@
hi
+1 -6
View File
@@ -4,15 +4,10 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:"> <meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
<title>Gnome Nostr - The Sacred Network of Woodland Folk</title>
<meta name="description" content="A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!">
<meta property="og:type" content="website">
<meta property="og:title" content="Gnome Nostr - The Sacred Network of Woodland Folk">
<meta property="og:description" content="A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!">
<link rel="manifest" href="/manifest.webmanifest"> <link rel="manifest" href="/manifest.webmanifest">
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
<script type="module" src="/src/main.tsx"></script> <script type="module" src="/src/main.tsx"></script>
</body> </body>
</html> </html>
+470 -320
View File
File diff suppressed because it is too large. Load diff
+9 -6
View File
@@ -10,10 +10,11 @@
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup" "deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
}, },
"dependencies": { "dependencies": {
"@fontsource-variable/comfortaa": "^5.2.6", "@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^3.9.0", "@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.1", "@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.5", "@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
"@radix-ui/react-accordion": "^1.2.0", "@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1", "@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0", "@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -50,20 +51,21 @@
"date-fns": "^3.6.0", "date-fns": "^3.6.0",
"embla-carousel-react": "^8.3.0", "embla-carousel-react": "^8.3.0",
"input-otp": "^1.2.4", "input-otp": "^1.2.4",
"lucide-react": "^0.462.0", "lucide-react": "^0.542.0",
"next-themes": "^0.3.0",
"nostr-tools": "^2.13.0", "nostr-tools": "^2.13.0",
"qrcode": "^1.5.4",
"react": "^18.3.1", "react": "^18.3.1",
"react-day-picker": "^8.10.1", "react-day-picker": "^8.10.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-hook-form": "^7.53.0", "react-hook-form": "^7.53.0",
"react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3", "react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2", "react-router-dom": "^6.26.2",
"recharts": "^2.12.7", "recharts": "^2.12.7",
"sonner": "^1.5.0",
"tailwind-merge": "^2.5.2", "tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3", "vaul": "^0.9.3",
"webln": "^0.3.2",
"zod": "^3.25.71" "zod": "^3.25.71"
}, },
"devDependencies": { "devDependencies": {
@@ -74,6 +76,7 @@
"@testing-library/jest-dom": "^6.6.3", "@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0", "@testing-library/react": "^16.3.0",
"@types/node": "^22.5.5", "@types/node": "^22.5.5",
"@types/qrcode": "^1.5.5",
"@types/react": "^18.3.1", "@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1", "@types/react-dom": "^18.3.1",
"@vitejs/plugin-react-swc": "^3.5.0", "@vitejs/plugin-react-swc": "^3.5.0",
-21
View File
@@ -1,21 +0,0 @@
{
"name": "Gnome Nostr - The Sacred Network of Woodland Folk",
"short_name": "Gnome Nostr",
"description": "A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!",
"start_url": "/",
"display": "standalone",
"background_color": "#f0f5f0",
"theme_color": "#d97706",
"icons": [
{
"src": "/icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icon-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
-32
View File
@@ -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]>
+9 -8
View File
@@ -7,10 +7,10 @@ import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense } from 'react'; import { Suspense } from 'react';
import NostrProvider from '@/components/NostrProvider'; import NostrProvider from '@/components/NostrProvider';
import { Toaster } from "@/components/ui/toaster"; import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip"; import { TooltipProvider } from "@/components/ui/tooltip";
import { NostrLoginProvider } from '@nostrify/react/login'; import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider'; import { AppProvider } from '@/components/AppProvider';
import { NWCProvider } from '@/contexts/NWCContext';
import { AppConfig } from '@/contexts/AppContext'; import { AppConfig } from '@/contexts/AppContext';
import AppRouter from './AppRouter'; import AppRouter from './AppRouter';
@@ -49,13 +49,14 @@ export function App() {
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'> <NostrLoginProvider storageKey='nostr:login'>
<NostrProvider> <NostrProvider>
<TooltipProvider> <NWCProvider>
<Toaster /> <TooltipProvider>
<Sonner /> <Toaster />
<Suspense> <Suspense>
<AppRouter /> <AppRouter />
</Suspense> </Suspense>
</TooltipProvider> </TooltipProvider>
</NWCProvider>
</NostrProvider> </NostrProvider>
</NostrLoginProvider> </NostrLoginProvider>
</QueryClientProvider> </QueryClientProvider>
+6
View File
@@ -2,6 +2,8 @@ import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop"; import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index"; import Index from "./pages/Index";
import { NIP19Page } from "./pages/NIP19Page";
import { AdminDashboard } from "./pages/AdminDashboard";
import NotFound from "./pages/NotFound"; import NotFound from "./pages/NotFound";
export function AppRouter() { export function AppRouter() {
@@ -10,6 +12,10 @@ export function AppRouter() {
<ScrollToTop /> <ScrollToTop />
<Routes> <Routes>
<Route path="/" element={<Index />} /> <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 */} {/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} /> <Route path="*" element={<NotFound />} />
</Routes> </Routes>
+41
View File
@@ -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>
);
}
+1 -1
View File
@@ -14,7 +14,7 @@ interface AppProviderProps {
} }
// Zod schema for AppConfig validation // Zod schema for AppConfig validation
const AppConfigSchema: z.ZodType<AppConfig> = z.object({ const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
theme: z.enum(['dark', 'light', 'system']), theme: z.enum(['dark', 'light', 'system']),
relayUrl: z.string().url(), relayUrl: z.string().url(),
}); });
+113
View File
@@ -0,0 +1,113 @@
import { Component, ErrorInfo, ReactNode } from 'react';
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
errorInfo: ErrorInfo | null;
}
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode;
}
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null,
};
}
static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
return {
hasError: true,
error,
};
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('Error caught by ErrorBoundary:', error, errorInfo);
this.setState({
error,
errorInfo,
});
}
handleReset = () => {
this.setState({
hasError: false,
error: null,
errorInfo: null,
});
};
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (
<div className="min-h-screen bg-background flex items-center justify-center p-4">
<div className="max-w-md w-full space-y-4">
<div className="text-center">
<h2 className="text-2xl font-bold text-foreground mb-2">
Something went wrong
</h2>
<p className="text-muted-foreground">
An unexpected error occurred. The error has been reported.
</p>
</div>
<div className="bg-muted p-4 rounded-lg">
<details className="text-sm">
<summary className="cursor-pointer font-medium text-foreground">
Error details
</summary>
<div className="mt-2 space-y-2">
<div>
<strong className="text-foreground">Message:</strong>
<p className="text-muted-foreground mt-1">
{this.state.error?.message}
</p>
</div>
{this.state.error?.stack && (
<div>
<strong className="text-foreground">Stack trace:</strong>
<pre className="text-xs text-muted-foreground mt-1 overflow-auto max-h-32">
{this.state.error.stack}
</pre>
</div>
)}
</div>
</details>
</div>
<div className="flex gap-2">
<button
onClick={this.handleReset}
className="flex-1 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors"
>
Try again
</button>
<button
onClick={() => window.location.reload()}
className="flex-1 px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90 transition-colors"
>
Reload page
</button>
</div>
</div>
</div>
);
}
return this.props.children;
}
}
-193
View File
@@ -1,193 +0,0 @@
import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Send, Sparkles, Leaf } from 'lucide-react';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { translateToGnomeSpeak } from '@/lib/gnomeSpeak';
import { useToast } from '@/hooks/useToast';
export function GnomeComposer() {
const [content, setContent] = useState('');
const [isPreviewMode, setIsPreviewMode] = useState(false);
const { user } = useCurrentUser();
const { mutate: createEvent, isPending } = useNostrPublish();
const { toast } = useToast();
const author = useAuthor(user?.pubkey || '');
const metadata = author.data?.metadata;
const displayName = metadata?.name ?? (user?.pubkey ? genUserName(user.pubkey) : 'Anonymous Gnome');
const profileImage = metadata?.picture;
const handleSubmit = () => {
if (!content.trim()) {
toast({
title: "Empty woodland proclamation!",
description: "Even gnomes need something to say to the forest folk.",
variant: "destructive",
});
return;
}
if (!user) {
toast({
title: "Authentication required",
description: "You must be logged in to share woodland wisdom.",
variant: "destructive",
});
return;
}
createEvent(
{
kind: 1,
content: content.trim(),
tags: [['t', 'gnome']] // Tag all posts as gnome content
},
{
onSuccess: () => {
setContent('');
setIsPreviewMode(false);
toast({
title: "Woodland proclamation sent! 🍄",
description: "Your message has been carried by the forest winds to all the message-mushrooms.",
});
},
onError: (error) => {
toast({
title: "Forest spirits are troubled",
description: `Failed to send your proclamation: ${error.message}`,
variant: "destructive",
});
}
}
);
};
const gnomeTranslatedContent = content ? translateToGnomeSpeak(content) : '';
if (!user) {
return (
<Card className="mb-6 border-2 border-dashed border-muted">
<CardContent className="py-8 text-center">
<div className="space-y-4">
<div className="text-4xl">🍄</div>
<div>
<h3 className="font-semibold mb-2">Join the Forest Council</h3>
<p className="text-muted-foreground">
Log in to share your woodland wisdom with fellow gnomes across the message-mushroom network!
</p>
</div>
</div>
</CardContent>
</Card>
);
}
return (
<Card className="mb-6 border-2 border-primary/20 shadow-lg">
<CardHeader className="pb-3">
<div className="flex items-center space-x-3">
<Avatar className="h-10 w-10 border-2 border-primary/30">
<AvatarImage src={profileImage} alt={displayName} />
<AvatarFallback className="bg-primary text-primary-foreground font-bold">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1">
<div className="flex items-center space-x-2">
<CardTitle className="text-lg">Share Woodland Wisdom</CardTitle>
<Badge variant="secondary" className="gnome-wiggle">
🍄 Gnome Speak
</Badge>
</div>
<p className="text-sm text-muted-foreground">
Your words will be translated into the ancient gnome tongue
</p>
</div>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<div className="flex items-center justify-between">
<label className="text-sm font-medium">Your Message:</label>
<Button
variant="ghost"
size="sm"
onClick={() => setIsPreviewMode(!isPreviewMode)}
className="text-xs"
>
<Sparkles className="h-3 w-3 mr-1" />
{isPreviewMode ? 'Edit' : 'Preview Gnome Speak'}
</Button>
</div>
{!isPreviewMode ? (
<Textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Share your thoughts with the forest folk... (will be translated to gnome speak)"
className="min-h-[100px] resize-none border-2 border-border/50 focus:border-primary/50"
maxLength={280}
/>
) : (
<div className="min-h-[100px] p-3 border-2 border-accent/30 rounded-md bg-accent/5">
<p className="text-sm text-muted-foreground mb-2 font-medium">
🍄 Gnome Speak Translation:
</p>
<div className="text-sm leading-relaxed">
{gnomeTranslatedContent || (
<span className="text-muted-foreground italic">
Your gnome translation will appear here...
</span>
)}
</div>
</div>
)}
<div className="flex items-center justify-between text-xs text-muted-foreground">
<span>
{content.length}/280 characters
</span>
{content && (
<span className="text-accent">
✨ Will be auto-translated to gnome speak
</span>
)}
</div>
</div>
<div className="flex items-center justify-between pt-2">
<div className="flex items-center space-x-2 text-xs text-muted-foreground">
<Leaf className="h-3 w-3" />
<span>Broadcasting to message-mushroom network</span>
</div>
<Button
onClick={handleSubmit}
disabled={!content.trim() || isPending}
className="font-medium"
>
{isPending ? (
<>
<Sparkles className="h-4 w-4 mr-2 animate-spin" />
Sending to Forest...
</>
) : (
<>
<Send className="h-4 w-4 mr-2" />
Share Wisdom
</>
)}
</Button>
</div>
</CardContent>
</Card>
);
}
-221
View File
@@ -1,221 +0,0 @@
import { useQuery } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { Heart, MessageCircle, Repeat2 } from 'lucide-react';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { NoteContent } from '@/components/NoteContent';
import { RelaySelector } from '@/components/RelaySelector';
import type { NostrEvent } from '@nostrify/nostrify';
function GnomePost({ event }: { event: NostrEvent }) {
const author = useAuthor(event.pubkey);
const metadata = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(event.pubkey);
const profileImage = metadata?.picture;
const about = metadata?.about;
// Format timestamp
const timestamp = new Date(event.created_at * 1000);
const timeAgo = formatTimeAgo(timestamp);
return (
<Card className="mb-4 border-2 border-border/50 hover:border-primary/30 transition-all duration-300 hover:shadow-lg mushroom-glow">
<CardHeader className="pb-3">
<div className="flex items-start space-x-3">
<Avatar className="h-12 w-12 border-2 border-primary/20">
<AvatarImage src={profileImage} alt={displayName} />
<AvatarFallback className="bg-secondary text-secondary-foreground font-bold">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0">
<div className="flex items-center space-x-2">
<h3 className="font-semibold text-foreground truncate">
{displayName}
</h3>
<Badge variant="secondary" className="text-xs gnome-wiggle">
🍄 Gnome
</Badge>
</div>
{about && (
<p className="text-sm text-muted-foreground truncate mt-1">
{about}
</p>
)}
<p className="text-xs text-muted-foreground mt-1">
{timeAgo} • via message-mushroom 🍄
</p>
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="mb-4">
<NoteContent event={event} className="text-sm leading-relaxed" />
</div>
{/* Gnome-themed interaction buttons */}
<div className="flex items-center space-x-6 pt-2 border-t border-border/30">
<Button variant="ghost" size="sm" className="text-muted-foreground hover:text-primary group">
<Heart className="h-4 w-4 mr-1 group-hover:fill-current transition-all" />
<span className="text-xs">Sprinkle Fairy Dust</span>
</Button>
<Button variant="ghost" size="sm" className="text-muted-foreground hover:text-accent group">
<MessageCircle className="h-4 w-4 mr-1" />
<span className="text-xs">Forest Whisper</span>
</Button>
<Button variant="ghost" size="sm" className="text-muted-foreground hover:text-secondary group">
<Repeat2 className="h-4 w-4 mr-1" />
<span className="text-xs">Spread Seeds</span>
</Button>
</div>
</CardContent>
</Card>
);
}
function GnomePostSkeleton() {
return (
<Card className="mb-4">
<CardHeader className="pb-3">
<div className="flex items-start space-x-3">
<Skeleton className="h-12 w-12 rounded-full" />
<div className="flex-1 space-y-2">
<div className="flex items-center space-x-2">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-5 w-16" />
</div>
<Skeleton className="h-3 w-32" />
<Skeleton className="h-3 w-20" />
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="space-y-2 mb-4">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
<Skeleton className="h-4 w-3/5" />
</div>
<div className="flex items-center space-x-6 pt-2 border-t border-border/30">
<Skeleton className="h-8 w-20" />
<Skeleton className="h-8 w-20" />
<Skeleton className="h-8 w-20" />
<Skeleton className="h-8 w-20" />
</div>
</CardContent>
</Card>
);
}
function formatTimeAgo(date: Date): string {
const now = new Date();
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
if (diffInSeconds < 60) {
return 'just now';
} else if (diffInSeconds < 3600) {
const minutes = Math.floor(diffInSeconds / 60);
return `${minutes}m ago`;
} else if (diffInSeconds < 86400) {
const hours = Math.floor(diffInSeconds / 3600);
return `${hours}h ago`;
} else {
const days = Math.floor(diffInSeconds / 86400);
return `${days}d ago`;
}
}
export function GnomeFeed() {
const { nostr } = useNostr();
const { data: posts, isLoading, error } = useQuery({
queryKey: ['gnome-feed'],
queryFn: async (c) => {
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
// Query for kind 1 events (text notes) that will be translated to gnome speak
const events = await nostr.query([
{
kinds: [1],
limit: 50,
}
], { signal });
// Sort by creation time (newest first)
return events.sort((a, b) => b.created_at - a.created_at);
},
refetchInterval: 30000, // Refetch every 30 seconds
});
if (error) {
return (
<div className="col-span-full">
<Card className="border-dashed border-destructive/50">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<div className="text-4xl">🍄💔</div>
<div>
<h3 className="font-semibold text-destructive mb-2">
The forest spirits are troubled!
</h3>
<p className="text-muted-foreground mb-4">
Unable to connect to the message-mushroom network. The woodland whispers have gone silent.
</p>
<RelaySelector className="w-full" />
</div>
</div>
</CardContent>
</Card>
</div>
);
}
if (isLoading) {
return (
<div className="space-y-4">
{Array.from({ length: 5 }).map((_, i) => (
<GnomePostSkeleton key={i} />
))}
</div>
);
}
if (!posts || posts.length === 0) {
return (
<div className="col-span-full">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<div className="text-6xl gnome-wiggle">🍄</div>
<div>
<h3 className="font-semibold mb-2">
The forest is quiet today...
</h3>
<p className="text-muted-foreground mb-4">
No woodland proclamations found. Perhaps the gnomes are all busy tending their gardens? Try another message-mushroom relay to discover more forest folk!
</p>
<RelaySelector className="w-full" />
</div>
</div>
</CardContent>
</Card>
</div>
);
}
return (
<div className="space-y-4">
{posts.map((post) => (
<GnomePost key={post.id} event={post} />
))}
</div>
);
}
-88
View File
@@ -1,88 +0,0 @@
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { LoginArea } from '@/components/auth/LoginArea';
import { RelaySelector } from '@/components/RelaySelector';
import { useTheme } from '@/hooks/useTheme';
import { Moon, Sun, Leaf, TreePine, Sparkles } from 'lucide-react';
export function GnomeHeader() {
const { theme, setTheme } = useTheme();
return (
<Card className="mb-6 border-2 border-primary/30 bg-gradient-to-r from-primary/5 via-accent/5 to-secondary/5">
<CardContent className="py-6">
<div className="flex flex-col space-y-4">
{/* Main header */}
<div className="flex items-center justify-between">
<div className="flex items-center space-x-4">
<div className="text-3xl gnome-wiggle">🍄</div>
<div>
<h1 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Gnome Nostr
</h1>
<p className="text-sm text-muted-foreground">
The sacred network of woodland folk
</p>
</div>
</div>
<div className="flex items-center space-x-3">
<Badge variant="secondary" className="hidden md:flex items-center space-x-1">
<Sparkles className="h-3 w-3" />
<span>Gnome Speak</span>
</Badge>
<Button
variant="ghost"
size="sm"
onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
className="text-muted-foreground hover:text-foreground"
>
{theme === 'light' ? (
<Moon className="h-4 w-4" />
) : (
<Sun className="h-4 w-4" />
)}
<span className="hidden sm:inline ml-1">
{theme === 'light' ? 'Night Forest' : 'Day Forest'}
</span>
</Button>
<LoginArea className="max-w-48" />
</div>
</div>
{/* Info and controls bar */}
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between space-y-3 sm:space-y-0 pt-3 border-t border-border/30">
<div className="flex items-center space-x-4 text-xs text-muted-foreground">
<div className="flex items-center space-x-1">
<TreePine className="h-3 w-3" />
<span className="hidden sm:inline">Text notes translated to gnome speak</span>
<span className="sm:hidden">Gnome translation active</span>
</div>
</div>
<div className="flex items-center space-x-2">
<Leaf className="h-3 w-3 text-muted-foreground" />
<span className="text-xs text-muted-foreground">Relay:</span>
<RelaySelector className="max-w-48" />
</div>
</div>
{/* Welcome message */}
<div className="bg-accent/10 border border-accent/20 rounded-lg p-4 text-center">
<p className="text-sm text-accent-foreground">
<span className="font-medium">🌟 Welcome to the enchanted forest!</span>
<br />
<span className="text-xs text-muted-foreground mt-1 block">
All text notes are magically translated into the ancient gnome tongue.
Share your woodland wisdom with fellow earth-dwellers!
</span>
</p>
</div>
</div>
</CardContent>
</Card>
);
}
+2 -4
View File
@@ -22,10 +22,9 @@ describe('NoteContent', () => {
</TestApp> </TestApp>
); );
// The URL should still be linkified even after gnome translation const link = screen.getByRole('link', { name: 'https://example.com' });
const link = screen.getByRole('link', { name: /https:\/\/example/ });
expect(link).toBeInTheDocument(); expect(link).toBeInTheDocument();
expect(link.getAttribute('href')).toMatch(/https:\/\/example/); expect(link).toHaveAttribute('href', 'https://example.com');
expect(link).toHaveAttribute('target', '_blank'); expect(link).toHaveAttribute('target', '_blank');
}); });
@@ -94,7 +93,6 @@ describe('NoteContent', () => {
</TestApp> </TestApp>
); );
// Hashtags are preserved during gnome translation
const nostrHashtag = screen.getByRole('link', { name: '#nostr' }); const nostrHashtag = screen.getByRole('link', { name: '#nostr' });
const bitcoinHashtag = screen.getByRole('link', { name: '#bitcoin' }); const bitcoinHashtag = screen.getByRole('link', { name: '#bitcoin' });
+1 -6
View File
@@ -5,7 +5,6 @@ import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor'; import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName'; import { genUserName } from '@/lib/genUserName';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { translateToGnomeSpeak, shouldTranslateToGnomeSpeak } from '@/lib/gnomeSpeak';
interface NoteContentProps { interface NoteContentProps {
event: NostrEvent; event: NostrEvent;
@@ -19,11 +18,7 @@ export function NoteContent({
}: NoteContentProps) { }: NoteContentProps) {
// Process the content to render mentions, links, etc. // Process the content to render mentions, links, etc.
const content = useMemo(() => { const content = useMemo(() => {
// Translate to gnome speak if it's a kind 1 event const text = event.content;
const originalText = event.content;
const text = shouldTranslateToGnomeSpeak(event.kind)
? translateToGnomeSpeak(originalText)
: originalText;
// Regex to find URLs, Nostr references, and hashtags // Regex to find URLs, Nostr references, and hashtags
const regex = /(https?:\/\/[^\s]+)|nostr:(npub1|note1|nprofile1|nevent1)([023456789acdefghjklmnpqrstuvwxyz]+)|(#\w+)/g; const regex = /(https?:\/\/[^\s]+)|nostr:(npub1|note1|nprofile1|nevent1)([023456789acdefghjklmnpqrstuvwxyz]+)|(#\w+)/g;
+395
View File
@@ -0,0 +1,395 @@
import { useState, forwardRef } from 'react';
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
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}
</>
);
}
+58
View File
@@ -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>
);
}
+470
View File
@@ -0,0 +1,470 @@
import { useState, useEffect, useRef, forwardRef } from 'react';
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
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>
);
}
+11 -1
View File
@@ -1,7 +1,7 @@
// NOTE: This file is stable and usually should not be modified. // 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. // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react'; import { ChevronDown, LogOut, UserIcon, UserPlus, Wallet } from 'lucide-react';
import { import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
@@ -11,6 +11,7 @@ import {
} from '@/components/ui/dropdown-menu.tsx'; } from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { RelaySelector } from '@/components/RelaySelector'; import { RelaySelector } from '@/components/RelaySelector';
import { WalletModal } from '@/components/WalletModal';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts'; import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName'; import { genUserName } from '@/lib/genUserName';
@@ -63,6 +64,15 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</DropdownMenuItem> </DropdownMenuItem>
))} ))}
<DropdownMenuSeparator /> <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 <DropdownMenuItem
onClick={onAddAccountClick} onClick={onAddAccountClick}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md' className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
+19 -10
View File
@@ -2,7 +2,7 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested. // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { useState } from 'react'; import { useState } from 'react';
import { User } from 'lucide-react'; import { User, UserPlus } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx'; import { Button } from '@/components/ui/button.tsx';
import LoginDialog from './LoginDialog'; import LoginDialog from './LoginDialog';
import SignupDialog from './SignupDialog'; import SignupDialog from './SignupDialog';
@@ -29,18 +29,27 @@ export function LoginArea({ className }: LoginAreaProps) {
{currentUser ? ( {currentUser ? (
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} /> <AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
) : ( ) : (
<Button <div className="flex gap-3 justify-center">
onClick={() => setLoginDialogOpen(true)} <Button
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' 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> <User className='w-4 h-4' />
</Button> <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 <LoginDialog
isOpen={loginDialogOpen} isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)} onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin} onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)} onSignup={() => setSignupDialogOpen(true)}
/> />
+252 -96
View File
@@ -1,19 +1,15 @@
// NOTE: This file is stable and usually should not be modified. // 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. // It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useRef, useState } from 'react'; import React, { useRef, useState, useEffect } from 'react';
import { Shield, Upload } from 'lucide-react'; import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input.tsx'; import { Input } from '@/components/ui/input';
import { import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
Dialog, import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
DialogContent, import { Alert, AlertDescription } from '@/components/ui/alert';
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog.tsx';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs.tsx';
import { useLoginActions } from '@/hooks/useLoginActions'; import { useLoginActions } from '@/hooks/useLoginActions';
import { cn } from '@/lib/utils';
interface LoginDialogProps { interface LoginDialogProps {
isOpen: boolean; isOpen: boolean;
@@ -22,54 +18,124 @@ interface LoginDialogProps {
onSignup?: () => void; 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 LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState(''); const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState(''); const [bunkerUri, setBunkerUri] = useState('');
const [errors, setErrors] = useState<{
nsec?: string;
bunker?: string;
file?: string;
extension?: string;
}>({});
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
const login = useLoginActions(); 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); setIsLoading(true);
setErrors(prev => ({ ...prev, extension: undefined }));
try { try {
if (!('nostr' in window)) { if (!('nostr' in window)) {
throw new Error('Nostr extension not found. Please install a NIP-07 extension.'); throw new Error('Nostr extension not found. Please install a NIP-07 extension.');
} }
login.extension(); await login.extension();
onLogin(); onLogin();
onClose(); 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); console.error('Extension login failed:', error);
setErrors(prev => ({
...prev,
extension: error instanceof Error ? error.message : 'Extension login failed'
}));
} finally { } finally {
setIsLoading(false); 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 = () => { const handleKeyLogin = () => {
if (!nsec.trim()) return; if (!nsec.trim()) {
setIsLoading(true); setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
return;
try {
login.nsec(nsec);
onLogin();
onClose();
} catch (error) {
console.error('Nsec login failed:', error);
} finally {
setIsLoading(false);
} }
if (!validateNsec(nsec)) {
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
return;
}
executeLogin(nsec);
}; };
const handleBunkerLogin = () => { const handleBunkerLogin = async () => {
if (!bunkerUri.trim() || !bunkerUri.startsWith('bunker://')) return; 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); setIsLoading(true);
setErrors(prev => ({ ...prev, bunker: undefined }));
try { try {
login.bunker(bunkerUri); await login.bunker(bunkerUri);
onLogin(); onLogin();
onClose(); onClose();
} catch (error) { // Clear the URI from memory
console.error('Bunker login failed:', error); setBunkerUri('');
} catch {
setErrors(prev => ({
...prev,
bunker: 'Failed to connect to bunker. Please check the URI.'
}));
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@@ -79,10 +145,27 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
const file = e.target.files?.[0]; const file = e.target.files?.[0];
if (!file) return; if (!file) return;
setIsFileLoading(true);
setErrors({});
const reader = new FileReader(); const reader = new FileReader();
reader.onload = (event) => { reader.onload = (event) => {
setIsFileLoading(false);
const content = event.target?.result as string; 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); reader.readAsText(file);
}; };
@@ -94,58 +177,139 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
} }
}; };
const defaultTab = 'nostr' in window ? 'extension' : 'key';
return ( return (
<Dialog open={isOpen} onOpenChange={onClose}> <Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className='sm:max-w-md p-0 overflow-hidden rounded-2xl'> <DialogContent
<DialogHeader className='px-6 pt-6 pb-0 relative'> className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl overflow-y-scroll")}
<DialogTitle className='text-xl font-semibold text-center'>Log in</DialogTitle> >
<DialogDescription className='text-center text-muted-foreground mt-2'> <DialogHeader className={cn('px-6 pt-6 pb-1 relative')}>
Access your account securely with your preferred method
</DialogDescription> <DialogDescription className="text-center">
Sign up or log in to continue
</DialogDescription>
</DialogHeader> </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'> {/* Divider */}
<Tabs defaultValue={'nostr' in window ? 'extension' : 'key'} className='w-full'> <div className='relative'>
<TabsList className='grid grid-cols-3 mb-6'> <div className='absolute inset-0 flex items-center'>
<TabsTrigger value='extension'>Extension</TabsTrigger> <div className='w-full border-t border-gray-300 dark:border-gray-600'></div>
<TabsTrigger value='key'>Nsec</TabsTrigger> </div>
<TabsTrigger value='bunker'>Bunker</TabsTrigger> <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> </TabsList>
<TabsContent value='extension' className='space-y-3 bg-muted'>
<TabsContent value='extension' className='space-y-4'> {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'> <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' /> <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'> <p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
Login with one click using the browser extension Login with one click using the browser extension
</p> </p>
<Button <div className="flex justify-center">
className='w-full rounded-full py-6' <Button
onClick={handleExtensionLogin} className='w-full rounded-full py-4'
disabled={isLoading} onClick={handleExtensionLogin}
> disabled={isLoading}
{isLoading ? 'Logging in...' : 'Login with Extension'} >
</Button> {isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
</div> </div>
</TabsContent> </TabsContent>
<TabsContent value='key' className='space-y-4'> <TabsContent value='key' className='space-y-4'>
<div className='space-y-4'> <div className='space-y-4'>
<div className='space-y-2'> <div className='space-y-2'>
<label htmlFor='nsec' className='text-sm font-medium text-gray-700 dark:text-gray-400'> <label htmlFor='nsec' className='text-sm font-medium'>
Enter your nsec Secret Key (nsec)
</label> </label>
<Input <Input
type='password'
id='nsec' id='nsec'
type="password"
value={nsec} value={nsec}
onChange={(e) => setNsec(e.target.value)} onChange={(e) => {
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary' 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...' 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>
<div className='text-center'> <div className='text-center'>
<p className='text-sm mb-2 text-gray-600 dark:text-gray-400'>Or upload a key file</p>
<input <input
type='file' type='file'
accept='.txt' accept='.txt'
@@ -155,25 +319,21 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
/> />
<Button <Button
variant='outline' 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()} onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
> >
<Upload className='w-4 h-4 mr-2' /> <Upload className='w-4 h-4 mr-2' />
Upload Nsec File {isFileLoading ? 'Reading File...' : 'Upload Your Key File'}
</Button> </Button>
{errors.file && (
<p className="text-sm text-red-500 mt-2">{errors.file}</p>
)}
</div> </div>
<Button
className='w-full rounded-full py-6 mt-4'
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
>
{isLoading ? 'Verifying...' : 'Login with Nsec'}
</Button>
</div> </div>
</TabsContent> </TabsContent>
<TabsContent value='bunker' className='space-y-4'> <TabsContent value='bunker' className='space-y-3 bg-muted'>
<div className='space-y-2'> <div className='space-y-2'>
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'> <label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Bunker URI Bunker URI
@@ -181,40 +341,36 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
<Input <Input
id='bunkerUri' id='bunkerUri'
value={bunkerUri} value={bunkerUri}
onChange={(e) => setBunkerUri(e.target.value)} onChange={(e) => {
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary' 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://' placeholder='bunker://'
autoComplete="off"
/> />
{bunkerUri && !bunkerUri.startsWith('bunker://') && ( {errors.bunker && (
<p className='text-red-500 text-xs'>URI must start with bunker://</p> <p className="text-sm text-red-500">{errors.bunker}</p>
)} )}
</div> </div>
<Button <div className="flex justify-center">
className='w-full rounded-full py-6' <Button
onClick={handleBunkerLogin} className='w-full rounded-full py-4'
disabled={isLoading || !bunkerUri.trim() || !bunkerUri.startsWith('bunker://')} onClick={handleBunkerLogin}
> disabled={isLoading || !bunkerUri.trim()}
{isLoading ? 'Connecting...' : 'Login with Bunker'} >
</Button> {isLoading ? 'Connecting...' : 'Login with Bunker'}
</Button>
</div>
</TabsContent> </TabsContent>
</Tabs> </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> </div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
); );
}; };
export default LoginDialog; export default LoginDialog;
+650 -109
View File
@@ -1,163 +1,704 @@
// NOTE: This file is stable and usually should not be modified. // 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. // 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 React, { useState, useEffect, useRef } from 'react';
import { Download, Key } from 'lucide-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.tsx'; import { Button } from '@/components/ui/button';
import { import { Input } from '@/components/ui/input';
Dialog, import { Textarea } from '@/components/ui/textarea';
DialogContent, import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
DialogDescription, import { Card, CardContent } from '@/components/ui/card';
DialogHeader, import { toast } from '@/hooks/useToast';
DialogTitle,
} from '@/components/ui/dialog.tsx';
import { toast } from '@/hooks/useToast.ts';
import { useLoginActions } from '@/hooks/useLoginActions'; import { useLoginActions } from '@/hooks/useLoginActions';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useUploadFile } from '@/hooks/useUploadFile';
import { generateSecretKey, nip19 } from 'nostr-tools'; import { generateSecretKey, nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils';
interface SignupDialogProps { interface SignupDialogProps {
isOpen: boolean; isOpen: boolean;
onClose: () => void; onClose: () => void;
onComplete?: () => void;
} }
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => { const sanitizeFilename = (filename: string) => {
const [step, setStep] = useState<'generate' | 'download' | 'done'>('generate'); 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 [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = 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 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 // Generate a proper nsec key using nostr-tools
const generateKey = () => { const generateKey = () => {
setIsLoading(true); setIsLoading(true);
setShowSparkles(true);
try {
// Generate a new secret key // Add a dramatic pause for the key generation effect
const sk = generateSecretKey(); setTimeout(() => {
try {
// Convert to nsec format // Generate a new secret key
setNsec(nip19.nsecEncode(sk)); const sk = generateSecretKey();
setStep('download');
} catch (error) { // Convert to nsec format
console.error('Failed to generate key:', error); setNsec(nip19.nsecEncode(sk));
toast({ setStep('download');
title: 'Error',
description: 'Failed to generate key. Please try again.', toast({
variant: 'destructive', title: 'Your Secret Key is Ready!',
}); description: 'A new secret key has been generated for you.',
} finally { });
setIsLoading(false); } catch {
} toast({
title: 'Error',
description: 'Failed to generate key. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
setShowSparkles(false);
}
}, 2000);
}; };
const downloadKey = () => { const downloadKey = () => {
// Create a blob with the key text try {
const blob = new Blob([nsec], { type: 'text/plain' }); // Create a blob with the key text
const url = globalThis.URL.createObjectURL(blob); 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 // Sanitize filename
const a = document.createElement('a'); const filename = sanitizeFilename('nostr-nsec-key.txt');
a.href = url;
a.download = 'nsec.txt';
document.body.appendChild(a);
a.click();
// Clean up // Create a temporary link element and trigger download
globalThis.URL.revokeObjectURL(url); const a = document.createElement('a');
document.body.removeChild(a); a.href = url;
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
toast({ // Clean up immediately
title: 'Key downloaded', globalThis.URL.revokeObjectURL(url);
description: 'Your key has been downloaded. Keep it safe!', document.body.removeChild(a);
});
// Mark as secured
setKeySecured('downloaded');
toast({
title: 'Secret Key Saved!',
description: 'Your key has been safely stored.',
});
} catch {
toast({
title: 'Download failed',
description: 'Could not download the key file. Please copy it manually.',
variant: 'destructive',
});
}
}; };
const finishSignup = () => {
login.nsec(nsec);
setStep('done');
onClose();
toast({ const finishKeySetup = () => {
title: 'Account created', try {
description: 'You are now logged in.', 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 ( return (
<Dialog open={isOpen} onOpenChange={onClose}> <Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className='sm:max-w-md p-0 overflow-hidden rounded-2xl'> <DialogContent
<DialogHeader className='px-6 pt-6 pb-0 relative'> className={cn("max-w-[95vw] sm:max-w-md max-h-[90vh] max-h-[90dvh] p-0 overflow-hidden rounded-2xl flex flex-col")}
<DialogTitle className='text-xl font-semibold text-center'> >
{step === 'generate' && 'Create Your Account'} <DialogHeader className={cn('px-6 pt-6 pb-1 relative flex-shrink-0')}>
{step === 'download' && 'Download Your Key'} <DialogTitle className={cn('font-semibold text-center text-lg')}>
{step === 'done' && 'Setting Up Your Account'} {getTitle()}
</DialogTitle> </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> </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'> {/* Benefits */}
{step === 'generate' && ( <div className='grid grid-cols-1 gap-2 text-sm'>
<div className='text-center space-y-6'> <div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<div className='p-4 rounded-lg bg-gray-50 dark:bg-gray-800 flex items-center justify-center'> <Shield className='w-4 h-4' />
<Key className='w-16 h-16 text-primary' /> Decentralized and censorship-resistant
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<User className='w-4 h-4' />
You are in control of your data
</div>
<div className='flex items-center justify-center gap-2 text-blue-700 dark:text-blue-300'>
<Globe className='w-4 h-4' />
Join a global network
</div>
</div>
</div>
<div className='space-y-3'>
<Button
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
onClick={() => setStep('generate')}
>
<LogIn className='w-5 h-5 mr-2' />
Get Started
</Button>
</div> </div>
<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> </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' && ( {step === 'download' && (
<div className='space-y-6'> <div className='text-center space-y-4'>
<div className='p-4 rounded-lg border bg-gray-50 dark:bg-gray-800 overflow-auto'> {/* Key reveal */}
<code className='text-xs break-all'>{nsec}</code> <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>
<div className='text-sm text-gray-600 dark:text-gray-300 space-y-2'> {/* Key vault */}
<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> {/* Security options */}
<li>Store it somewhere safe</li> <div className='space-y-3'>
<li>Never share this key with anyone</li>
</ul>
<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>
<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 <Button
variant='outline' variant='outline'
className='w-full' className='w-full rounded-full py-3 disabled:opacity-50 disabled:cursor-not-allowed'
onClick={downloadKey} onClick={() => finishSignup(true)}
disabled={isPublishing || isUploading}
> >
<Download className='w-4 h-4 mr-2' /> {isPublishing ? (
Download Key <>
</Button> <div className='w-4 h-4 mr-2 border-2 border-current border-t-transparent rounded-full animate-spin' />
Setting up account...
<Button </>
className='w-full rounded-full py-6' ) : (
onClick={finishSignup} 'Skip for now'
> )}
I've saved my key, continue
</Button> </Button>
</div> </div>
</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> </div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
+153
View File
@@ -0,0 +1,153 @@
import { useState } from 'react';
import { Link } from 'react-router-dom';
import { NostrEvent } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor';
import { useComments } from '@/hooks/useComments';
import { CommentForm } from './CommentForm';
import { NoteContent } from '@/components/NoteContent';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { DropdownMenu, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { MessageSquare, ChevronDown, ChevronRight, MoreHorizontal } from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { genUserName } from '@/lib/genUserName';
interface CommentProps {
root: NostrEvent | URL;
comment: NostrEvent;
depth?: number;
maxDepth?: number;
limit?: number;
}
export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: CommentProps) {
const [showReplyForm, setShowReplyForm] = useState(false);
const [showReplies, setShowReplies] = useState(depth < 2); // Auto-expand first 2 levels
const author = useAuthor(comment.pubkey);
const { data: commentsData } = useComments(root, limit);
const metadata = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(comment.pubkey)
const timeAgo = formatDistanceToNow(new Date(comment.created_at * 1000), { addSuffix: true });
// Get direct replies to this comment
const replies = commentsData?.getDirectReplies(comment.id) || [];
const hasReplies = replies.length > 0;
return (
<div className={`space-y-3 ${depth > 0 ? 'ml-6 border-l-2 border-muted pl-4' : ''}`}>
<Card className="bg-card/50">
<CardContent className="p-4">
<div className="space-y-3">
{/* Comment Header */}
<div className="flex items-start justify-between">
<div className="flex items-center space-x-3">
<Link to={`/${nip19.npubEncode(comment.pubkey)}`}>
<Avatar className="h-8 w-8 hover:ring-2 hover:ring-primary/30 transition-all cursor-pointer">
<AvatarImage src={metadata?.picture} />
<AvatarFallback className="text-xs">
{displayName.charAt(0)}
</AvatarFallback>
</Avatar>
</Link>
<div>
<Link
to={`/${nip19.npubEncode(comment.pubkey)}`}
className="font-medium text-sm hover:text-primary transition-colors"
>
{displayName}
</Link>
<p className="text-xs text-muted-foreground">{timeAgo}</p>
</div>
</div>
</div>
{/* Comment Content */}
<div className="text-sm">
<NoteContent event={comment} className="text-sm" />
</div>
{/* Comment Actions */}
<div className="flex items-center justify-between pt-2">
<div className="flex items-center space-x-2">
<Button
variant="ghost"
size="sm"
onClick={() => setShowReplyForm(!showReplyForm)}
className="h-8 px-2 text-xs"
>
<MessageSquare className="h-3 w-3 mr-1" />
Reply
</Button>
{hasReplies && (
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
<CollapsibleTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 px-2 text-xs">
{showReplies ? (
<ChevronDown className="h-3 w-3 mr-1" />
) : (
<ChevronRight className="h-3 w-3 mr-1" />
)}
{replies.length} {replies.length === 1 ? 'reply' : 'replies'}
</Button>
</CollapsibleTrigger>
</Collapsible>
)}
</div>
{/* Comment menu */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-8 px-2 text-xs"
aria-label="Comment options"
>
<MoreHorizontal className="h-3 w-3" />
</Button>
</DropdownMenuTrigger>
</DropdownMenu>
</div>
</div>
</CardContent>
</Card>
{/* Reply Form */}
{showReplyForm && (
<div className="ml-6">
<CommentForm
root={root}
reply={comment}
onSuccess={() => setShowReplyForm(false)}
placeholder="Write a reply..."
compact
/>
</div>
)}
{/* Replies */}
{hasReplies && (
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
<CollapsibleContent className="space-y-3">
{replies.map((reply) => (
<Comment
key={reply.id}
root={root}
comment={reply}
depth={depth + 1}
maxDepth={maxDepth}
limit={limit}
/>
))}
</CollapsibleContent>
</Collapsible>
)}
</div>
);
}
+90
View File
@@ -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>
);
}
+100
View File
@@ -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>
);
}
-29
View File
@@ -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 }
+8
View File
@@ -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>;
}
+237
View File
@@ -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,
};
}
+98
View File
@@ -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,
});
}
+221
View File
@@ -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,
};
}
+15
View File
@@ -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;
}
+92
View File
@@ -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]
});
},
});
}
+94
View File
@@ -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,
};
}
+338
View File
@@ -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,
};
}
+62 -116
View File
@@ -4,85 +4,89 @@
@layer base { @layer base {
:root { :root {
/* Gnome Forest Theme - Light Mode */ --background: 0 0% 100%;
--background: 120 20% 97%; /* Very light sage green */ --foreground: 222.2 84% 4.9%;
--foreground: 120 15% 15%; /* Dark forest green */
--card: 120 25% 95%; /* Light moss green */ --card: 0 0% 100%;
--card-foreground: 120 15% 15%; --card-foreground: 222.2 84% 4.9%;
--popover: 120 25% 95%; --popover: 0 0% 100%;
--popover-foreground: 120 15% 15%; --popover-foreground: 222.2 84% 4.9%;
--primary: 25 85% 55%; /* Warm mushroom orange */ --primary: 222.2 47.4% 11.2%;
--primary-foreground: 120 25% 95%; --primary-foreground: 210 40% 98%;
--secondary: 120 30% 85%; /* Soft forest green */ --secondary: 210 40% 96.1%;
--secondary-foreground: 120 15% 15%; --secondary-foreground: 222.2 47.4% 11.2%;
--muted: 120 20% 90%; /* Light moss */ --muted: 210 40% 96.1%;
--muted-foreground: 120 10% 45%; /* Medium forest green */ --muted-foreground: 215.4 16.3% 46.9%;
--accent: 45 90% 70%; /* Golden acorn yellow */ --accent: 210 40% 96.1%;
--accent-foreground: 120 15% 15%; --accent-foreground: 222.2 47.4% 11.2%;
--destructive: 0 84.2% 60.2%; /* Red mushroom */ --destructive: 0 84.2% 60.2%;
--destructive-foreground: 120 25% 95%; --destructive-foreground: 210 40% 98%;
--border: 120 25% 85%; /* Soft green border */ --border: 214.3 31.8% 91.4%;
--input: 120 25% 90%; /* Light input background */ --input: 214.3 31.8% 91.4%;
--ring: 25 85% 55%; /* Mushroom orange focus ring */ --ring: 222.2 84% 4.9%;
--radius: 0.75rem; /* More rounded for organic feel */ --radius: 0.5rem;
--sidebar-background: 120 30% 92%; --sidebar-background: 0 0% 98%;
--sidebar-foreground: 120 15% 20%;
--sidebar-primary: 25 85% 55%; --sidebar-foreground: 240 5.3% 26.1%;
--sidebar-primary-foreground: 120 25% 95%;
--sidebar-accent: 120 25% 88%; --sidebar-primary: 240 5.9% 10%;
--sidebar-accent-foreground: 120 15% 15%;
--sidebar-border: 120 25% 80%; --sidebar-primary-foreground: 0 0% 98%;
--sidebar-ring: 25 85% 55%;
--sidebar-accent: 240 4.8% 95.9%;
--sidebar-accent-foreground: 240 5.9% 10%;
--sidebar-border: 220 13% 91%;
--sidebar-ring: 217.2 91.2% 59.8%;
} }
.dark { .dark {
/* Gnome Forest Theme - Dark Mode (Night in the Forest) */ --background: 222.2 84% 4.9%;
--background: 120 25% 8%; /* Deep forest night */ --foreground: 210 40% 98%;
--foreground: 120 20% 85%; /* Light moss green */
--card: 120 20% 12%; /* Dark forest floor */ --card: 222.2 84% 4.9%;
--card-foreground: 120 20% 85%; --card-foreground: 210 40% 98%;
--popover: 120 20% 12%; --popover: 222.2 84% 4.9%;
--popover-foreground: 120 20% 85%; --popover-foreground: 210 40% 98%;
--primary: 25 85% 65%; /* Bright mushroom orange */ --primary: 210 40% 98%;
--primary-foreground: 120 20% 12%; --primary-foreground: 222.2 47.4% 11.2%;
--secondary: 120 15% 20%; /* Dark moss */ --secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 120 20% 85%; --secondary-foreground: 210 40% 98%;
--muted: 120 15% 18%; /* Dark undergrowth */ --muted: 217.2 32.6% 17.5%;
--muted-foreground: 120 15% 60%; /* Medium light green */ --muted-foreground: 215 20.2% 65.1%;
--accent: 45 90% 75%; /* Bright golden acorn */ --accent: 217.2 32.6% 17.5%;
--accent-foreground: 120 20% 12%; --accent-foreground: 210 40% 98%;
--destructive: 0 75% 55%; /* Dark red mushroom */ --destructive: 0 62.8% 30.6%;
--destructive-foreground: 120 20% 85%; --destructive-foreground: 210 40% 98%;
--border: 120 20% 20%; /* Dark forest border */ --border: 217.2 32.6% 17.5%;
--input: 120 20% 15%; /* Dark input background */ --input: 217.2 32.6% 17.5%;
--ring: 25 85% 65%; /* Bright mushroom focus ring */ --ring: 212.7 26.8% 83.9%;
--sidebar-background: 240 5.9% 10%;
--sidebar-background: 120 25% 10%; --sidebar-foreground: 240 4.8% 95.9%;
--sidebar-foreground: 120 20% 80%; --sidebar-primary: 224.3 76.3% 48%;
--sidebar-primary: 25 85% 65%; --sidebar-primary-foreground: 0 0% 100%;
--sidebar-primary-foreground: 120 20% 12%; --sidebar-accent: 240 3.7% 15.9%;
--sidebar-accent: 120 20% 18%; --sidebar-accent-foreground: 240 4.8% 95.9%;
--sidebar-accent-foreground: 120 20% 85%; --sidebar-border: 240 3.7% 15.9%;
--sidebar-border: 120 20% 20%; --sidebar-ring: 217.2 91.2% 59.8%;
--sidebar-ring: 25 85% 65%;
} }
} }
@@ -93,63 +97,5 @@
body { body {
@apply bg-background text-foreground; @apply bg-background text-foreground;
background-image:
radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.1) 0%, transparent 50%),
radial-gradient(circle at 80% 20%, rgba(255, 119, 48, 0.1) 0%, transparent 50%),
radial-gradient(circle at 40% 40%, rgba(120, 200, 120, 0.05) 0%, transparent 50%);
} }
}
/* Gnome-specific animations and effects */
@keyframes gnome-wiggle {
0%, 100% { transform: rotate(-1deg); }
50% { transform: rotate(1deg); }
}
@keyframes mushroom-glow {
0%, 100% { box-shadow: 0 0 5px rgba(255, 119, 48, 0.3); }
50% { box-shadow: 0 0 15px rgba(255, 119, 48, 0.5); }
}
@keyframes forest-shimmer {
0% { background-position: -200% 0; }
100% { background-position: 200% 0; }
}
.gnome-wiggle {
animation: gnome-wiggle 2s ease-in-out infinite;
}
.mushroom-glow {
animation: mushroom-glow 3s ease-in-out infinite;
}
.forest-shimmer {
background: linear-gradient(
90deg,
transparent,
rgba(120, 200, 120, 0.2),
transparent
);
background-size: 200% 100%;
animation: forest-shimmer 3s ease-in-out infinite;
}
/* Custom scrollbar for gnome theme */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: hsl(var(--muted));
border-radius: 4px;
}
::-webkit-scrollbar-thumb {
background: hsl(var(--primary));
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: hsl(var(--accent));
} }
-61
View File
@@ -1,61 +0,0 @@
import { describe, it, expect } from 'vitest';
import { translateToGnomeSpeak, shouldTranslateToGnomeSpeak } from './gnomeSpeak';
describe('gnomeSpeak', () => {
describe('shouldTranslateToGnomeSpeak', () => {
it('returns true for kind 1 events', () => {
expect(shouldTranslateToGnomeSpeak(1)).toBe(true);
});
it('returns false for other event kinds', () => {
expect(shouldTranslateToGnomeSpeak(0)).toBe(false);
expect(shouldTranslateToGnomeSpeak(3)).toBe(false);
expect(shouldTranslateToGnomeSpeak(1111)).toBe(false);
expect(shouldTranslateToGnomeSpeak(30023)).toBe(false);
});
});
describe('translateToGnomeSpeak', () => {
it('translates basic words to gnome speak', () => {
const result = translateToGnomeSpeak('Hello world! This is good.');
expect(result).toContain('Greetings, fellow');
expect(result).toContain('splendid as');
});
it('preserves URLs during translation', () => {
const result = translateToGnomeSpeak('Check out https://example.com for good info');
expect(result).toMatch(/https:\/\/example/);
expect(result).toContain('splendid as');
});
it('preserves nostr references during translation', () => {
const result = translateToGnomeSpeak('Follow nostr:npub1zg69v7ys40x77y352eufp27daufrg4ncjz4ummcjx3t83y9tehhsqepuh0 for good content');
expect(result).toContain('nostr:npub1zg69v7ys40x77y352eufp27daufrg4ncjz4ummcjx3t83y9tehhsqepuh0');
expect(result).toContain('splendid as');
});
it('preserves hashtags during translation', () => {
const result = translateToGnomeSpeak('This is about #nostr and #bitcoin development');
expect(result).toContain('#nostr');
expect(result).toContain('#bitcoin');
});
it('adds gnome-specific formatting for special terms', () => {
const result = translateToGnomeSpeak('I love bitcoin and gm everyone!');
expect(result).toContain('golden acorns of the digital realm');
expect(result).toContain('🌅when dew kisses the earth🌅');
});
it('handles empty or invalid input', () => {
expect(translateToGnomeSpeak('')).toBe('');
expect(translateToGnomeSpeak(null as unknown as string)).toBe(null);
expect(translateToGnomeSpeak(undefined as unknown as string)).toBe(undefined);
});
it('capitalizes sentences properly', () => {
const result = translateToGnomeSpeak('hello world. this is good.');
expect(result).toMatch(/^[A-Z]/); // Should start with capital letter
expect(result).toMatch(/\. [A-Z]/); // Should capitalize after periods
});
});
});
-923
View File
@@ -1,923 +0,0 @@
/**
* Gnome Speak Translator
* Transforms regular text into whimsical gnome language
*/
// Common gnome words and phrases
const gnomeVocabulary: Record<string, string> = {
// Greetings and expressions
'hello': 'greetings, fellow earth-dweller',
'hi': 'huzzah',
'hey': 'ho there',
'howdy': 'well met, forest-friend',
'welcome': 'blessed be your arrival',
'goodbye': 'may your mushrooms grow tall',
'bye': 'farewell, friend of the forest',
'farewell': 'until the paths cross again',
'thanks': 'blessings of the garden upon you',
'thank you': 'may the roots remember your kindness',
'please': 'if it pleases the woodland spirits',
'sorry': 'forgive this humble gnome',
'excuse me': 'pardon this forest-dweller',
'yes': 'aye, by my pointy hat',
'yeah': 'indeed, forest-friend',
'yep': 'certainly, woodland-companion',
'absolutely': 'as sure as ancient-oaks',
'definitely': 'certain as sunrise',
'certainly': 'without doubt, earth-friend',
'sure': 'as reliable as mountain-stones',
'no': 'nay, not even for all the acorns in the forest',
'nope': 'negative, forest-friend',
'never': 'not in a thousand-seasons',
'maybe': 'perhaps, if the mushrooms align',
'perhaps': 'possibly, when stars-align',
'possibly': 'might be, if spirits-will',
'probably': 'likely as autumn-leaves-falling',
'ok': 'very well, tiny friend',
'okay': 'indeed, little earth-dweller',
'alright': 'acceptable to forest-council',
'fine': 'satisfactory as spring-weather',
'wow': 'by the ancient-spirits',
'whoa': 'sacred mushrooms preserve-us',
'oh': 'woodland-spirits witness',
'oops': 'clumsy as startled-squirrels',
'darn': 'cursed as wilted-flowers',
// Common descriptive words
'good': 'splendid as morning dew',
'great': 'magnificent as ancient oak',
'awesome': 'wondrous as fairy rings',
'amazing': 'astounding as dragon sightings',
'incredible': 'miraculous as talking trees',
'wonderful': 'marvelous as rainbow bridges',
'excellent': 'superb as crystal caves',
'fantastic': 'enchanting as unicorn meadows',
'perfect': 'flawless as crystal dewdrops',
'beautiful': 'lovely as blooming flowers',
'pretty': 'charming as flower petals',
'gorgeous': 'stunning as sunset glades',
'handsome': 'dashing as noble stags',
'nice': 'pleasant as garden breeze',
'sweet': 'endearing as honey-flavored-words',
'cool': 'refreshing as spring water',
'hot': 'blazing as dragon breath',
'warm': 'cozy as hearth embers',
'cold': 'frigid as mountain peaks',
'bad': 'cursed as wilted leaves',
'terrible': 'dreadful as goblin raids',
'horrible': 'ghastly as poisoned wells',
'awful': 'abysmal as barren wastelands',
'ugly': 'unsightly as rotting stumps',
'hideous': 'repulsive as swamp creatures',
'disgusting': 'revolting as rotten-smell-smellers',
'gross': 'sickening as filth-encountering',
'big': 'enormous as giant toadstools',
'large': 'vast as forest clearings',
'huge': 'colossal as mountain trolls',
'massive': 'immense as ancient trees',
'giant': 'titanic as elder dragons',
'small': 'tiny as acorn caps',
'little': 'wee as dewdrops',
'tiny': 'minuscule as fairy footprints',
'miniature': 'pocket-sized as gnome homes',
'fast': 'swift as woodland sprites',
'quick': 'rapid as darting squirrels',
'speedy': 'fleet as racing rabbits',
'slow': 'leisurely as growing moss',
'sluggish': 'plodding as sleepy bears',
'new': 'fresh as spring shoots',
'old': 'ancient as elder trees',
'young': 'youthful as new growth',
'fresh': 'crisp as dawn air',
'stale': 'aged as ancient crumbs',
'clean': 'pure as mountain springs',
'dirty': 'soiled as muddy paths',
'rich': 'wealthy as treasure hoards',
'poor': 'humble as simple folk',
'expensive': 'costly as rare gems',
'cheap': 'affordable as common stones',
'free': 'unbound as forest winds',
'easy': 'simple as breathing air',
'difficult': 'challenging as mountain climbing',
'hard': 'tough as ancient bark',
'soft': 'gentle as rabbit fur',
'strong': 'mighty as bear strength',
'weak': 'frail as spider silk',
'heavy': 'weighty as boulder loads',
'light': 'airy as dandelion fluff',
'dark': 'shadowy as deep cave',
'bright': 'radiant as summer sun',
'loud': 'noisy as thunder crashes',
'quiet': 'silent as falling snow',
'busy': 'active as worker ants',
'lazy': 'idle as sunbathing cats',
'tired': 'weary as day\'s end',
'awake': 'alert as watchful owls',
'alive': 'living with forest vitality',
'dead': 'lifeless as fallen logs',
'healthy': 'robust as oak trees',
'sick': 'ailing like withered plants',
'safe': 'secure as burrow homes',
'dangerous': 'perilous as cliff edges',
'careful': 'cautious as deer at streams',
'careless': 'reckless as storm winds',
'smart': 'clever as cunning foxes',
'stupid': 'mindlessly as senseless acts',
'wise': 'sage as ancient owls',
'foolish': 'unwise as reckless youth',
'funny': 'amusing as playful otters',
'serious': 'grave as solemn ceremonies',
'strange': 'odd as two-headed mushrooms',
'normal': 'ordinary as daily sunrise',
'special': 'unique as snowflake patterns',
'different': 'distinct as individual leaves',
'same': 'identical as twin acorns',
'similar': 'alike as sister streams',
'equal': 'equivalent as balanced scales',
'fair': 'just as forest law',
'unfair': 'unjust as stolen honey',
'true': 'accurate as gnome-wisdom',
'false': 'untrue as winter promises',
'right': 'correct as compass needles',
'wrong': 'mistaken as lost travelers',
'correct': 'proper as forest protocol',
'important': 'significant as ancient laws',
'interesting': 'fascinating as rare discoveries',
'boring': 'dull as watching grass grow',
'fun': 'enjoyable as harvest festivals',
'lucky': 'fortunate as four-leaf clovers',
'unlucky': 'cursed as broken mirrors',
'successful': 'triumphant as victorious warriors',
'popular': 'beloved as festival leaders',
'famous': 'renowned as legendary heroes',
'unknown': 'mysterious as hidden valleys',
// Emotions and feelings
'happy': 'merry as spring festivals',
'joyful': 'gleeful as dancing pixies',
'cheerful': 'bright as sunny meadows',
'excited': 'thrilled as treasure hunters',
'delighted': 'pleased as successful gardeners',
'ecstatic': 'overjoyed as festival winners',
'elated': 'uplifted as soaring-eagles',
'content': 'satisfied as well-fed-bears',
'pleased': 'gratified as successful-gardeners',
'glad': 'happy as singing-birds',
'relieved': 'unburdened as dropped-heavy-packs',
'grateful': 'thankful as rain-blessed-crops',
'proud': 'dignified as royal stags',
'confident': 'assured as mountain peaks',
'brave': 'courageous as warrior bears',
'bold': 'daring as cliff-climbing-goats',
'calm': 'peaceful as still ponds',
'relaxed': 'at-ease as sunbathing-cats',
'peaceful': 'tranquil as morning-meadows',
'sad': 'melancholy as autumn rain',
'unhappy': 'sorrowful as wilting flowers',
'depressed': 'gloomy as storm clouds',
'miserable': 'wretched as lost wanderers',
'heartbroken': 'shattered as fallen-bird-eggs',
'lonely': 'isolated as single-trees',
'hurt': 'wounded as thorn-pricked-paws',
'angry': 'wrathful as disturbed badgers',
'mad': 'furious as territorial bears',
'furious': 'enraged as protective mothers',
'annoyed': 'vexed as pestered squirrels',
'irritated': 'bothered as interrupted naps',
'frustrated': 'blocked like dammed-streams',
'afraid': 'fearful as startled mice',
'scared': 'frightened as hunted-rabbits',
'terrified': 'petrified as stone-statues',
'nervous': 'jittery as caffeine-buzzed-squirrels',
'worried': 'concerned as protective-parents',
'anxious': 'worried as storm-watching-sailors',
'surprised': 'astonished as sudden storms',
'shocked': 'stunned as lightning-struck-trees',
'amazed': 'astounded as miracle-witnesses',
'confused': 'puzzled as riddle-hearers',
'lost': 'directionless as pathless-wanderers',
'curious': 'inquisitive as exploring-kittens',
'interested': 'engaged as story-listeners',
'bored': 'uninterested as sleepy-sloths',
'jealous': 'envious as covetous-dragons',
'envious': 'resentful as have-nots',
'greedy': 'grasping as hoarding-squirrels',
'selfish': 'self-centered as narcissistic-peacocks',
'generous': 'giving as abundant-fruit-trees',
'kind': 'gentle as mother\'s touch',
'mean': 'nasty as stinging-nettles',
'cruel': 'harsh as winter-storms',
'embarrassed': 'ashamed as public-mistake-makers',
'guilty': 'remorseful as wrongdoing-confessors',
'ashamed': 'dishonored as oath-breakers',
// Actions and verbs
'go': 'venture forth',
'come': 'approach the sacred circle',
'see': 'witness with gnome-eyes',
'look': 'gaze upon',
'watch': 'observe like sentinel-owls',
'listen': 'hear the whispers of the wind',
'hear': 'perceive with gnome-ears',
'speak': 'utter in ancient dialect',
'talk': 'speak in the ancient tongue',
'say': 'declare to forest council',
'tell': 'relate tales by firelight',
'ask': 'inquire of the wise ones',
'answer': 'respond with woodland-wisdom',
'think': 'ponder in the mushroom circle',
'know': 'hold wisdom in thy cap',
'learn': 'gather knowledge like berries',
'teach': 'share wisdom of the ancients',
'understand': 'comprehend with woodland wisdom',
'remember': 'recall from memory-moss',
'forget': 'lose to the mists of time',
'believe': 'trust in forest magic',
'hope': 'wish upon evening stars',
'feel': 'sense with gnome-heart',
'love': 'cherish like precious gems',
'like': 'fancy as favorite flowers',
'hate': 'despise like garden pests',
'want': 'desire like moths seek flame',
'need': 'require like flowers need rain',
'have': 'possess like territorial-bears',
'get': 'obtain through forest cunning',
'give': 'bestow gifts of the heart',
'take': 'gather like squirrels in autumn',
'put': 'place with gnomish care',
'make': 'craft with gnomish hands',
'do': 'perform with woodland-skill',
'work': 'toil in the earth',
'play': 'frolic like woodland creatures',
'help': 'lend aid to fellow forest-folk',
'try': 'attempt with gnomish determination',
'use': 'employ with woodland wisdom',
'find': 'discover hidden treasures',
'lose': 'misplace in the deep woods',
'keep': 'guard like dragon\'s treasure',
'save': 'preserve like squirrels save nuts',
'spend': 'use like autumn leaves falling',
'buy': 'trade for with shiny pebbles',
'sell': 'barter in the market grove',
'pay': 'offer tribute to forest spirits',
'win': 'triumph like mighty oak',
'start': 'begin the woodland journey',
'stop': 'halt like deer sensing danger',
'end': 'conclude like sunset',
'finish': 'complete like harvest-gathering',
'begin': 'commence the forest-quest',
'continue': 'proceed along woodland-path',
'change': 'transform like caterpillars',
'move': 'shift like dancing leaves',
'stay': 'remain rooted like ancient trees',
'leave': 'depart on woodland winds',
'return': 'come back to the sacred grove',
'arrive': 'reach journey\'s end',
'travel': 'journey through wild lands',
'visit': 'call upon forest friends',
'meet': 'encounter on woodland paths',
'follow': 'walk the same forest path',
'lead': 'guide like wise elders',
'run': 'scamper through the underbrush',
'walk': 'stroll the forest paths',
'sit': 'perch upon mushroom throne',
'stand': 'rise like proud saplings',
'sleep': 'rest in the embrace of moss',
'wake': 'greet the morning sun',
'eat': 'partake of nature\'s gifts',
'drink': 'sip the sacred waters',
'cook': 'prepare over gnome-fires',
'read': 'decipher the runes of knowledge',
'write': 'inscribe upon bark and stone',
'build': 'construct like industrious beavers',
'break': 'shatter like brittle ice',
'fix': 'mend with gnomish skill',
'open': 'unseal like blooming flowers',
'close': 'shut like evening blossoms',
'turn': 'rotate like seasons changing',
'carry': 'bear like pack mules',
'hold': 'grasp with gnomish grip',
'throw': 'hurl like catapult stones',
'catch': 'capture like spider webs',
'send': 'dispatch like messenger birds',
'bring': 'carry like busy ants',
'show': 'reveal like dawn breaking',
'hide': 'conceal in forest-shadows',
'wait': 'pause like patient stones',
'hurry': 'rush like urgent-messengers',
'choose': 'select like wise owls',
'decide': 'determine by mushroom council',
'plan': 'scheme like clever foxes',
'create': 'birth from gnomish imagination',
'destroy': 'unmake like winter storms',
'grow': 'flourish like spring gardens',
'die': 'return to the eternal soil',
'live': 'dwell in harmony with nature',
'happen': 'occur by woodland chance',
'seem': 'appear like morning mist',
'become': 'transform into',
'remain': 'stay like enduring-stones',
'appear': 'manifest like forest-spirits',
'disappear': 'vanish like morning-mist',
'exist': 'be present in forest-realm',
'matter': 'be important as ancient oaks',
'care': 'tend like garden keeper',
'worry': 'fret like anxious rabbits',
'call': 'summon with woodland voice',
'let': 'allow the forest spirits',
'allow': 'permit by gnomish law',
'join': 'unite like flowing streams',
'share': 'spread like dandelion seeds',
'agree': 'harmonize like bird songs',
'disagree': 'clash like thunder storms',
'fight': 'battle like fierce badgers',
'argue': 'quarrel like territorial squirrels',
'discuss': 'debate in council circles',
'explain': 'clarify like morning light',
'describe': 'paint word-pictures',
'compare': 'measure against ancient standards',
'include': 'embrace within the circle',
'exclude': 'banish from sacred-grove',
'add': 'include like gathering-berries',
'remove': 'extract like pulling-weeds',
'increase': 'grow like expanding-trees',
'decrease': 'shrink like autumn-leaves',
'improve': 'enhance like garden-tending',
'develop': 'cultivate like patient farmers',
'manage': 'oversee like head gardener',
'control': 'command like forest kings',
'organize': 'arrange like busy bees',
'prepare': 'ready like winter-preparations',
'provide': 'supply from nature\'s storehouse',
'offer': 'present like gift-bearing visitors',
'accept': 'receive with grateful heart',
'refuse': 'decline like stubborn-mules',
'reject': 'spurn like bitter-berries',
'receive': 'welcome like spring rain',
'support': 'uphold like sturdy roots',
'oppose': 'resist like stubborn stones',
'protect': 'shield like mother bears',
'attack': 'assault like angry wasps',
'defend': 'guard like loyal hounds',
'escape': 'flee like startled rabbits',
'avoid': 'evade like nimble deer',
'reach': 'extend like growing vines',
'touch': 'contact with gentle-paws',
'push': 'shove like rolling boulders',
'pull': 'draw like flowing streams',
'lift': 'raise like morning mist',
'drop': 'release like autumn leaves',
'pick': 'select like berry gatherers',
'enter': 'cross the sacred threshold',
'exit': 'depart through hidden doors',
'pass': 'traverse like mountain paths',
'cross': 'bridge like fallen-logs',
'climb': 'ascend like squirrel-acrobats',
'jump': 'leap like bounding-deer',
'fall': 'tumble like rolling-acorns',
'swim': 'glide like graceful-fish',
'dance': 'move like wind-blown-leaves',
'sing': 'vocalize like morning-birds',
'laugh': 'chortle like amused-gnomes',
'cry': 'weep like rain-clouds',
'smile': 'grin like happy-sunflowers',
'frown': 'scowl like storm-clouds',
// Technology terms (gnome-ified)
'computer': 'thinking-box of metal and magic',
'laptop': 'portable wisdom-chest',
'phone': 'speaking-crystal',
'smartphone': 'clever communication-gem',
'internet': 'the great web of knowledge',
'website': 'digital mushroom ring',
'email': 'letter-sprite delivery',
'password': 'secret gnome-word',
'app': 'magical tool-sprite',
'software': 'spell-weaving programs',
'program': 'coded spell-sequence',
'code': 'mystical rune-writing',
'bug': 'mischievous code-gremlin',
'update': 'spell-enhancement ritual',
'download': 'summon from the ether',
'upload': 'send to the cloud-spirits',
'file': 'digital scroll-bundle',
'delete': 'banish to the void',
'bitcoin': 'golden acorns of the digital realm',
'crypto': 'mystical coin-magic',
'blockchain': 'the eternal ledger of the earth spirits',
'nostr': 'the sacred network of gnome-kind',
'relay': 'message-mushroom',
'post': 'woodland proclamation',
'message': 'whisper carried by wind',
'chat': 'friendly forest-chatter',
'comment': 'thoughtful tree-response',
'reply': 'echo from the grove',
'mention': 'call by woodland-name',
'tag': 'forest-marker label',
'hashtag': 'topic-gathering symbol',
'follower': 'path-walking companion',
'friend': 'woodland-path companion',
'user': 'forest-path wanderer',
'account': 'woodland-identity record',
'profile': 'forest-dweller description',
'avatar': 'spirit-image representation',
'feed': 'stream of woodland-news',
'trending': 'popular as festival-topics',
'viral': 'spreading like wildfire-news',
// Time and nature
'today': 'this blessed sun-cycle',
'tomorrow': 'the next dawn',
'yesterday': 'the previous twilight',
'now': 'this very forest-moment',
'soon': 'before the next acorn-fall',
'later': 'after the sun-shift',
'early': 'with the first bird-songs',
'late': 'when shadows grow long',
'morning': 'when dew kisses the earth',
'afternoon': 'when sun reaches tree-tops',
'evening': 'when fireflies dance',
'night': 'when the moon watches over',
'day': 'sun-blessed time',
'week': 'seven turnings of the earth',
'month': 'one moon-cycle',
'year': 'full journey round the sun',
'time': 'the eternal forest-flow',
'moment': 'brief woodland-instant',
'hour': 'sun-shadow measurement',
'minute': 'tiny time-fragment',
'second': 'heartbeat-duration',
'season': 'nature\'s changing-mood',
'spring': 'time of awakening-growth',
'summer': 'season of abundant-warmth',
'autumn': 'harvest of golden-leaves',
'winter': 'the great forest-slumber',
'weather': 'sky-spirit\'s current-mood',
'rain': 'sky-tears blessing the earth',
'snow': 'winter\'s white forest-blanket',
'sun': 'the great golden-eye',
'moon': 'night\'s silver-guardian',
'stars': 'celestial navigation-gems',
'sky': 'the endless blue-canopy',
'cloud': 'sky-spirit\'s fluffy-messenger',
'wind': 'breath of the forest-spirits',
'storm': 'sky-spirits\' angry-dance',
'thunder': 'voice of the cloud-giants',
'lightning': 'sky-fire\'s brilliant-flash',
'rainbow': 'bridge between earth and sky',
'nature': 'the great mother-spirit',
'earth': 'our beloved soil-mother',
'world': 'the vast forest-realm',
'ground': 'the solid earth-foundation',
'soil': 'the life-giving dirt-magic',
'rock': 'earth\'s ancient bone-structure',
'stone': 'small piece of mountain-heart',
'mountain': 'earth\'s reaching-toward-sky',
'hill': 'gentle earth-rise',
'valley': 'earth\'s peaceful-embrace',
'forest': 'the sacred tree-gathering',
'tree': 'earth\'s reaching-toward-light',
'branch': 'tree\'s extending-arm',
'leaf': 'tree\'s breathing-surface',
'root': 'tree\'s earth-drinking-finger',
'flower': 'plant\'s colorful-celebration',
'grass': 'earth\'s green-carpet',
'plant': 'earth\'s growing-child',
'garden': 'tended plant-paradise',
'water': 'life-giving crystal liquid',
'river': 'flowing water-pathway',
'lake': 'earth\'s water-mirror',
'ocean': 'vast water-wilderness',
'fire': 'dancing heat-spirit',
'flame': 'fire\'s reaching-tongue',
'smoke': 'fire\'s gray-breath',
'wood': 'tree\'s gift-material',
'animal': 'forest-dwelling-creature',
'bird': 'sky-dancing-singer',
'fish': 'water-dwelling-swimmer',
'dog': 'loyal four-legged-friend',
'cat': 'independent whisker-hunter',
'horse': 'noble four-legged-runner',
'cow': 'gentle milk-giving-beast',
'pig': 'round mud-loving-creature',
'chicken': 'feathered egg-laying-bird',
'bear': 'mighty forest-guardian',
'wolf': 'pack-hunting-howler',
'deer': 'graceful forest-leaper',
'rabbit': 'quick-hopping-nibbler',
'squirrel': 'tree-climbing-nut-gatherer',
'mouse': 'tiny cheese-seeking-creature',
'rat': 'clever tunnel-dwelling-survivor',
'snake': 'slithering ground-crawler',
'spider': 'web-weaving-hunter',
'bee': 'buzzing honey-maker',
'butterfly': 'colorful flower-dancer',
'ant': 'industrious colony-worker',
'fly': 'annoying buzzing-pest',
'mosquito': 'blood-seeking-tiny-vampire',
'frog': 'pond-dwelling-croaker',
'turtle': 'shell-carrying-slow-walker',
'owl': 'wise night-hunting-watcher',
'eagle': 'majestic sky-soaring-hunter',
'dragon': 'legendary fire-breathing-beast',
'unicorn': 'mythical horn-bearing-horse',
'fairy': 'tiny magical-forest-sprite',
'elf': 'pointed-ear-woodland-dweller',
'dwarf': 'bearded mountain-tunnel-digger',
'wizard': 'spell-casting-wise-elder',
'witch': 'potion-brewing-magic-user',
'ghost': 'transparent spirit-being',
'monster': 'frightening creature-of-darkness',
// Food and sustenance
'food': 'earth\'s bounty',
'meal': 'feast of forest-gifts',
'breakfast': 'dawn\'s energy-awakening',
'lunch': 'midday sustenance-break',
'dinner': 'evening\'s nourishment-gathering',
'snack': 'small between-meal-nibble',
'hungry': 'craving earth\'s-nourishment',
'thirsty': 'needing liquid-refreshment',
'full': 'satisfied with belly-bounty',
'coffee': 'bitter bean brew',
'tea': 'leaf-water of wisdom',
'milk': 'cow\'s white-gift',
'juice': 'fruit\'s liquid-essence',
'beer': 'grain\'s fermented-celebration',
'wine': 'grape\'s aged-transformation',
'bread': 'grain-gift of the fields',
'cake': 'sweet celebration-tower',
'cookie': 'small sweet-disk',
'pizza': 'flat bread with toppings-garden',
'meat': 'animal\'s protein-gift',
'vegetable': 'earth\'s colorful-children',
'fruit': 'tree\'s sweet-offering',
'apple': 'red orb of crisp-sweetness',
'banana': 'yellow crescent-fruit',
'orange': 'citrus sun-sphere',
'cheese': 'milk\'s aged-transformation',
'egg': 'bird\'s oval-creation',
'honey': 'bee\'s golden-sweetness',
'sugar': 'cane\'s crystallized-sweetness',
'salt': 'sea\'s mineral-gift',
'spicy': 'fire-tongue-sensation',
'delicious': 'wonderfully tasty-pleasure',
'tasty': 'pleasing to tongue-senses',
'yummy': 'delightfully satisfying-flavor',
// People and relationships
'person': 'wanderer of the mortal realm',
'people': 'fellow earth-dwellers',
'human': 'tall-folk',
'man': 'bearded earth-walker',
'woman': 'graceful forest-daughter',
'child': 'young sprout',
'baby': 'tiny seedling',
'boy': 'male young-sprout',
'girl': 'female young-blossom',
'family': 'clan of the same burrow',
'mother': 'nurturing life-bringer',
'father': 'protecting life-provider',
'parent': 'life-giving-elder',
'son': 'male offspring-sprout',
'daughter': 'female offspring-blossom',
'brother': 'male sibling-companion',
'sister': 'female sibling-friend',
'husband': 'male life-bond-companion',
'wife': 'female life-bond-companion',
'boyfriend': 'courting male-companion',
'girlfriend': 'courting female-companion',
'neighbor': 'nearby-dwelling-friend',
'stranger': 'unknown path-crosser',
'teacher': 'wisdom-sharing-elder',
'student': 'knowledge-seeking-sprout',
'doctor': 'healing-arts-practitioner',
'worker': 'labor-providing-being',
'boss': 'work-directing-leader',
'leader': 'group-guiding-chief',
'team': 'cooperating-group-unit',
'group': 'gathered-together-collection',
'community': 'shared-dwelling-collective',
// Places and locations
'place': 'woodland-location',
'home': 'cozy burrow-dwelling',
'house': 'family nest-structure',
'building': 'tall human-construction',
'room': 'enclosed dwelling-space',
'kitchen': 'food-preparation-chamber',
'bedroom': 'sleeping-rest-sanctuary',
'bathroom': 'cleansing-water-room',
'office': 'work-task-chamber',
'school': 'learning-wisdom-hall',
'hospital': 'healing-treatment-center',
'store': 'goods-trading-establishment',
'restaurant': 'food-serving-hall',
'park': 'public green-space',
'street': 'paved pathway-for-travel',
'road': 'long travel-route',
'city': 'large human-settlement',
'town': 'medium human-gathering',
'village': 'small community-cluster',
'country': 'large territorial-region',
'state': 'governmental-territory-division',
'beach': 'sandy water-meeting-shore',
'island': 'water-surrounded-land',
'desert': 'dry sandy-wasteland',
'farm': 'food-growing-sanctuary',
'field': 'open earth-expanse',
'meadow': 'flower-filled-clearing',
// Objects and things
'thing': 'woodland-object',
'object': 'physical forest-item',
'item': 'individual possession-piece',
'stuff': 'various collected-objects',
'book': 'knowledge-filled-pages',
'paper': 'tree-pulp-writing-surface',
'pen': 'ink-flowing-writing-stick',
'pencil': 'graphite-marking-tool',
'car': 'metal traveling-box',
'bike': 'two-wheeled-pedal-machine',
'train': 'long track-riding-transport',
'plane': 'sky-flying-metal-bird',
'boat': 'water-floating-vessel',
'ship': 'large ocean-crossing-craft',
'chair': 'sitting-support-furniture',
'table': 'flat surface-for-placing',
'bed': 'sleeping-comfort-platform',
'door': 'entrance-barrier-portal',
'window': 'transparent wall-opening',
'wall': 'vertical room-boundary',
'floor': 'horizontal walking-surface',
'roof': 'overhead shelter-covering',
'box': 'storage-container-cube',
'bag': 'flexible carrying-container',
'bottle': 'liquid-holding-vessel',
'cup': 'small drinking-container',
'plate': 'flat food-serving-disk',
'knife': 'sharp cutting-blade',
'fork': 'pronged eating-tool',
'spoon': 'curved scooping-utensil',
'clothes': 'body-covering-garments',
'shirt': 'upper-body-covering',
'pants': 'leg-covering-garment',
'shoes': 'foot-protecting-coverings',
'hat': 'head-covering-accessory',
'ring': 'finger-circling-jewelry',
'key': 'lock-opening-metal-tool',
'money': 'trade-value-tokens',
'coin': 'small metal-currency-disk',
'card': 'flat rectangular-object',
'gift': 'present-offering-surprise',
'toy': 'play-entertainment-object',
'game': 'rule-based-fun-activity',
'ball': 'round bouncing-sphere',
'tool': 'work-assisting-implement',
'machine': 'mechanical working-device',
'camera': 'image-capturing-box',
'picture': 'visual-image-representation',
'photo': 'light-captured-moment',
'mirror': 'reflection-showing-surface',
'lamp': 'artificial light-provider',
'candle': 'wax flame-holder',
'ice': 'frozen solid-water',
'glass': 'transparent brittle-material',
'metal': 'hard shiny-material',
'plastic': 'synthetic flexible-material',
'rubber': 'bouncy stretchy-material',
'fabric': 'woven thread-material',
'leather': 'animal-hide-material',
'string': 'thin flexible-cord',
'rope': 'thick strong-cord',
'chain': 'linked metal-connections',
'wire': 'thin metal-strand',
'nail': 'sharp fastening-spike',
'screw': 'threaded fastening-rod',
'hammer': 'striking-force-tool',
'saw': 'cutting-teeth-tool',
'brush': 'bristled cleaning-tool',
'paint': 'color-coating-liquid',
'soap': 'cleaning-foam-substance',
'towel': 'drying-absorption-cloth',
'blanket': 'warmth-providing-cover',
'pillow': 'head-supporting-cushion',
'clock': 'time-displaying-device',
'calendar': 'date-organizing-chart',
'map': 'location-showing-guide',
'flag': 'symbolic cloth-banner',
'seed': 'plant\'s future-potential',
'stick': 'small wood-piece',
'shell': 'sea-creature\'s protective-home',
'feather': 'bird\'s flight-enabling-plume',
'bone': 'skeleton\'s structural-piece',
'fur': 'animal\'s warm-covering',
'scale': 'fish\'s protective-armor',
'horn': 'animal\'s pointed-growth',
'tail': 'animal\'s rear-appendage',
'wing': 'flight-enabling-appendage',
'claw': 'sharp grasping-nail',
'tooth': 'biting-chewing-bone',
'eye': 'vision-sensing-orb',
'ear': 'sound-detecting-organ',
'nose': 'smell-sensing-protrusion',
'mouth': 'eating-speaking-opening',
'hand': 'grasping-manipulation-appendage',
'finger': 'hand\'s flexible-digit',
'foot': 'walking-support-appendage',
'toe': 'foot\'s small-digit',
'head': 'thinking-sensing-sphere',
'hair': 'head\'s growing-strands',
'face': 'front-expression-surface',
'neck': 'head-connecting-column',
'shoulder': 'arm-connecting-joint',
'arm': 'reaching-grasping-limb',
'leg': 'walking-supporting-limb',
'knee': 'leg-bending-joint',
'chest': 'front-torso-area',
'stomach': 'food-digesting-organ',
'heart': 'blood-pumping-organ',
'brain': 'thinking-control-organ',
'blood': 'life-flowing-red-liquid',
'skin': 'body\'s protective-covering',
'muscle': 'movement-creating-tissue',
'breath': 'life-sustaining-air-flow',
'voice': 'sound-producing-expression',
'word': 'meaning-carrying-sound-unit',
'language': 'communication-sound-system',
'name': 'identity-labeling-word',
'story': 'event-narrative-tale',
'joke': 'humor-creating-tale',
'song': 'melodic-sound-creation',
'music': 'organized-sound-art',
'sound': 'air-vibration-sensation',
'noise': 'unwanted-sound-disturbance',
'silence': 'absence-of-sound',
'color': 'light-wavelength-perception',
'red': 'blood-fire-color',
'blue': 'sky-water-color',
'green': 'grass-leaf-color',
'yellow': 'sun-gold-color',
'purple': 'royal-flower-color',
'pink': 'blossom-blush-color',
'brown': 'earth-wood-color',
'black': 'night-shadow-color',
'white': 'snow-cloud-color',
'gray': 'storm-stone-color',
'silver': 'moon-metal-color',
'gold': 'treasure-sun-color',
};
// Gnome exclamations and interjections
const gnomeExclamations = [
'By my pointy hat!',
'Great toadstools!',
'Mushroom caps!',
'Sacred acorns!',
'Blessed berries!',
'Garden spirits preserve us!',
'Forest magic!',
'Woodland wonders!',
'Gnome\'s beard!',
'Tiny treasures!',
'Earth\'s bounty!',
'Root and branch!',
'Moss and mushrooms!',
'Fern and flower!',
'Bark and berry!',
'Stone and stream!'
];
// Gnome sentence starters
const gnomeSentenceStarters = [
'In the sacred grove, ',
'By the ancient oak, ',
'Beneath the mushroom ring, ',
'Among the forest folk, ',
'In the woodland realm, ',
'By the babbling brook, ',
'Under the starlit sky, ',
'Within the garden walls, ',
'Beside the fairy ring, ',
'Through the morning mist, ',
'As the seasons turn, ',
'When the moon is full, ',
'In the depths of the forest, ',
'Where the wild things grow, ',
'Beyond the garden gate, '
];
// Gnome sentence endings
const gnomeSentenceEndings = [
', as the ancients foretold.',
', blessed by the forest spirits.',
', in harmony with nature.',
', according to gnome wisdom.',
', as written in the bark of the elder tree.',
', by the light of the fireflies.',
', under the watchful eyes of the owls.',
', with the blessing of the earth mother.',
', as sure as mushrooms grow.',
', in the way of our people.',
', following the old traditions.',
', as the seasons decree.',
', by the sacred laws of the woodland.',
', in the manner of the wise ones.',
', as nature intended.'
];
/**
* Translates regular text into gnome speak
*/
export function translateToGnomeSpeak(text: string): string {
if (!text || typeof text !== 'string') {
return text;
}
let gnomeText = text.toLowerCase();
// Preserve URLs
const urlRegex = /(https?:\/\/[^\s]+)/g;
const urlMatches: string[] = [];
gnomeText = gnomeText.replace(urlRegex, (match) => {
urlMatches.push(match);
return `__URL_${urlMatches.length - 1}__`;
});
// Preserve nostr: references
const nostrRegex = /(nostr:(npub1|note1|nprofile1|nevent1|naddr1)([023456789acdefghjklmnpqrstuvwxyz]+))/g;
const nostrMatches: string[] = [];
gnomeText = gnomeText.replace(nostrRegex, (match) => {
nostrMatches.push(match);
return `__NOSTR_${nostrMatches.length - 1}__`;
});
// Preserve hashtags
const hashtagRegex = /(#\w+)/g;
const hashtagMatches: string[] = [];
gnomeText = gnomeText.replace(hashtagRegex, (match) => {
hashtagMatches.push(match);
return `__HASHTAG_${hashtagMatches.length - 1}__`;
});
// Replace words with gnome equivalents
Object.entries(gnomeVocabulary).forEach(([english, gnome]) => {
const escapedEnglish = english.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(`\\b${escapedEnglish}\\b`, 'gi');
gnomeText = gnomeText.replace(regex, gnome);
});
// Add gnome exclamations for emphasis
gnomeText = gnomeText.replace(/!/g, () => {
const exclamation = gnomeExclamations[Math.floor(Math.random() * gnomeExclamations.length)];
return `! ${exclamation}`;
});
// Add gnome sentence starters occasionally
const sentences = gnomeText.split(/[.!?]+/).filter(s => s.trim());
const gnomeSentences = sentences.map((sentence, index) => {
const trimmed = sentence.trim();
if (!trimmed) return sentence;
// Add starter to some sentences (not all, to avoid repetition)
if (Math.random() < 0.3 && index > 0) {
const starter = gnomeSentenceStarters[Math.floor(Math.random() * gnomeSentenceStarters.length)];
return starter + trimmed;
}
return trimmed;
});
// Rejoin sentences
gnomeText = gnomeSentences.join('. ');
// Add gnome endings occasionally
if (Math.random() < 0.4) {
const ending = gnomeSentenceEndings[Math.floor(Math.random() * gnomeSentenceEndings.length)];
gnomeText += ending;
}
// Capitalize first letter of sentences
gnomeText = gnomeText.replace(/(^|[.!?]\s+)([a-z])/g, (match, prefix, letter) => {
return prefix + letter.toUpperCase();
});
// Add some gnome-specific formatting
gnomeText = gnomeText.replace(/\b(bitcoin|btc)\b/gi, '✨golden acorns of the digital realm✨');
gnomeText = gnomeText.replace(/\b(gm|good morning)\b/gi, '🌅when dew kisses the earth🌅');
gnomeText = gnomeText.replace(/\b(gn|good night)\b/gi, '🌙when the moon watches over🌙');
// Restore preserved patterns
gnomeText = gnomeText.replace(/__URL_(\d+)__/g, (_, index) => urlMatches[parseInt(index)]);
gnomeText = gnomeText.replace(/__NOSTR_(\d+)__/g, (_, index) => nostrMatches[parseInt(index)]);
gnomeText = gnomeText.replace(/__HASHTAG_(\d+)__/g, (_, index) => hashtagMatches[parseInt(index)]);
return gnomeText;
}
/**
* Checks if text should be translated (only kind 1 events)
*/
export function shouldTranslateToGnomeSpeak(eventKind: number): boolean {
return eventKind === 1;
}
+8 -3
View File
@@ -3,10 +3,15 @@ import { createRoot } from 'react-dom/client';
// Import polyfills first // Import polyfills first
import './lib/polyfills.ts'; import './lib/polyfills.ts';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import App from './App.tsx'; import App from './App.tsx';
import './index.css'; import './index.css';
// Import gnome-themed font // FIXME: a custom font should be used. Eg:
import '@fontsource-variable/comfortaa'; // import '@fontsource-variable/<font-name>';
createRoot(document.getElementById("root")!).render(<App />); createRoot(document.getElementById("root")!).render(
<ErrorBoundary>
<App />
</ErrorBoundary>
);
+825
View File
@@ -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>
);
}
+12 -26
View File
@@ -1,36 +1,22 @@
import { useSeoMeta } from '@unhead/react'; import { useSeoMeta } from '@unhead/react';
import { GnomeHeader } from '@/components/GnomeHeader';
import { GnomeComposer } from '@/components/GnomeComposer'; // FIXME: Update this page (the content is just a fallback if you fail to update the page)
import { GnomeFeed } from '@/components/GnomeFeed';
const Index = () => { const Index = () => {
useSeoMeta({ useSeoMeta({
title: 'Gnome Nostr - The Sacred Network of Woodland Folk', title: 'Welcome to Your Blank App',
description: 'A magical Nostr client where all messages are translated into the ancient gnome tongue. Connect with fellow earth-dwellers across the message-mushroom network!', description: 'A modern Nostr client application built with React, TailwindCSS, and Nostrify.',
}); });
return ( return (
<div className="min-h-screen bg-background"> <div className="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-900">
<div className="container max-w-2xl mx-auto px-4 py-6"> <div className="text-center">
<GnomeHeader /> <h1 className="text-4xl font-bold mb-4 text-gray-900 dark:text-gray-100">
<GnomeComposer /> Welcome to Your Blank App
<GnomeFeed /> </h1>
<p className="text-xl text-gray-600 dark:text-gray-400">
{/* Footer with MKStack attribution */} Start building your amazing project here!
<div className="mt-12 pt-6 border-t border-border/30 text-center"> </p>
<p className="text-xs text-muted-foreground">
Vibed with{' '}
<a
href="https://soapbox.pub/mkstack"
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:text-accent transition-colors underline"
>
MKStack
</a>
{' '}• Blessed by the forest spirits 🍄✨
</p>
</div>
</div> </div>
</div> </div>
); );
+42
View File
@@ -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 />;
}
}
+60
View File
@@ -0,0 +1,60 @@
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { ErrorBoundary } from '@/components/ErrorBoundary';
// Test component that throws an error
const ThrowError = ({ shouldThrow }: { shouldThrow: boolean }) => {
if (shouldThrow) {
throw new Error('Test error');
}
return <div>No error</div>;
};
describe('ErrorBoundary', () => {
it('renders children when no error occurs', () => {
render(
<ErrorBoundary>
<div>Test content</div>
</ErrorBoundary>
);
expect(screen.getByText('Test content')).toBeInTheDocument();
});
it('catches and displays error when child throws', () => {
// Suppress console.error for this test
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
render(
<ErrorBoundary>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
expect(screen.getByText('An unexpected error occurred. The error has been reported.')).toBeInTheDocument();
consoleSpy.mockRestore();
});
it('uses custom fallback when provided', () => {
const customFallback = <div>Custom error message</div>;
// Suppress console.error for this test
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
render(
<ErrorBoundary fallback={customFallback}>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
expect(screen.getByText('Custom error message')).toBeInTheDocument();
consoleSpy.mockRestore();
});
});
+6 -3
View File
@@ -4,6 +4,7 @@ import { BrowserRouter } from 'react-router-dom';
import { NostrLoginProvider } from '@nostrify/react/login'; import { NostrLoginProvider } from '@nostrify/react/login';
import NostrProvider from '@/components/NostrProvider'; import NostrProvider from '@/components/NostrProvider';
import { AppProvider } from '@/components/AppProvider'; import { AppProvider } from '@/components/AppProvider';
import { NWCProvider } from '@/contexts/NWCContext';
import { AppConfig } from '@/contexts/AppContext'; import { AppConfig } from '@/contexts/AppContext';
interface TestAppProps { interface TestAppProps {
@@ -31,9 +32,11 @@ export function TestApp({ children }: TestAppProps) {
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='test-login'> <NostrLoginProvider storageKey='test-login'>
<NostrProvider> <NostrProvider>
<BrowserRouter> <NWCProvider>
{children} <BrowserRouter>
</BrowserRouter> {children}
</BrowserRouter>
</NWCProvider>
</NostrProvider> </NostrProvider>
</NostrLoginProvider> </NostrLoginProvider>
</QueryClientProvider> </QueryClientProvider>
-3
View File
@@ -19,9 +19,6 @@ export default {
} }
}, },
extend: { extend: {
fontFamily: {
sans: ['Comfortaa Variable', 'Comfortaa', 'system-ui', 'sans-serif'],
},
colors: { colors: {
border: 'hsl(var(--border))', border: 'hsl(var(--border))',
input: 'hsl(var(--input))', input: 'hsl(var(--input))',
+3
View File
@@ -19,6 +19,9 @@ export default defineConfig(() => ({
onConsoleLog(log) { onConsoleLog(log) {
return !log.includes("React Router Future Flag Warning"); return !log.includes("React Router Future Flag Warning");
}, },
env: {
DEBUG_PRINT_LIMIT: '0', // Suppress DOM output that exceeds AI context windows
},
}, },
resolve: { resolve: {
alias: { alias: {