Author SHA1 Message Date
Chad Curtis 4d5df6535f try to mimic a little closer to surveil 2025-07-08 06:45:41 +00:00
Chad Curtis 4734e96fe7 more steps 2025-07-08 06:37:01 +00:00
Chad Curtis e0ad32447a pull in signup button too 2025-07-08 06:24:43 +00:00
Chad Curtis 8aed77c49b readd comment 2025-07-08 06:17:57 +00:00
Chad Curtis 4e780190cb attempt to implement signup onboarding flow from surveil/treasures 2025-07-08 06:16:21 +00:00
Alex Gleason ad1c8b123c "Efficient Query Design" 2025-06-17 19:39:47 -05:00
Alex Gleason 4e1c43ee13 npm audit fix 2025-06-16 14:11:01 -05:00
Alex Gleason 1e179b4396 Add AbortSignal polyfills 2025-06-15 12:35:47 -05:00
Alex Gleason cd5376ff49 Add missing nostr__ server prefixes 2025-06-15 10:55:39 -05:00
Alex Gleason 561975cded Add @latest to js-dev-mcp 2025-06-14 22:37:43 -05:00
Alex Gleason 7a5fce4933 Use js-dev-mcp from npm 2025-06-14 22:36:58 -05:00
Alex Gleason 8559a004e8 Simplify "Nostr Implementation Guidelines" again 2025-06-13 22:09:06 -05:00
Alex Gleason df40d30f15 Emphasize "Nostr Implementation Guidelines" section 2025-06-13 20:59:25 -05:00
Alex Gleason 062545d061 Use fully qualified tool names in CONTEXT.md 2025-06-13 20:56:15 -05:00
Alex Gleason 9625533ed4 Add t-tag guidance 2025-06-13 19:49:46 -05:00
Alex Gleason db09c45a54 "Testing Your Changes" tweak for Gemini 2025-06-13 18:54:50 -05:00
Alex Gleason ed143157bf Add "Thorough NIP Review" bullet for Gemini Flash 2025-06-13 18:53:28 -05:00
Alex Gleason 9646620a46 Merge branch 'nostr-deploy' into 'main'
Update deploy command in package.json to use nostr-deploy-cli

See merge request soapbox-pub/mkstack!6
2025-06-11 19:23:17 +00:00
sepehr-safari 830c10fe8d Update deploy command in package.json to use nostr-deploy-cli 2025-06-11 22:15:41 +03:00
Alex Gleason 927010c0d0 1 minute timeout 2025-06-09 22:35:34 -05:00
Alex Gleason e70b3640e8 Remove prerendering after all 2025-06-09 22:30:09 -05:00
Alex Gleason 1983126de9 Prerender with Puppeteer 2025-06-09 22:03:22 -05:00
Alex Gleason 87d3cfb2eb Add manifest link to head 2025-06-09 21:19:43 -05:00
Alex Gleason 98aa853716 Teach the robot to use tags instead of json data in content 2025-06-09 15:16:17 -05:00
Alex Gleason 5d4a19eb9c Vibed by -> Vibed with 2025-06-09 09:24:03 -05:00
Alex Gleason 10386c2c38 Avoid any type 2025-06-09 00:24:57 -05:00
Alex Gleason 034b5eab33 Vibed by MKStack 2025-06-08 23:54:04 -05:00
Alex Gleason fddd1d20f3 Run vercel with npx, remove as dev dependency 2025-06-08 09:36:22 -05:00
Alex Gleason aa1088499f Merge branch 'vercel-deploy' into 'main'
Add Vercel as a devDependency and update deploy command to replace Surge with Vercel

See merge request soapbox-pub/mkstack!5
2025-06-08 13:15:56 +00:00
sepehr-safari c07a53e727 Add Vercel as a devDependency and update deploy command to replace Surge with Vercel 2025-06-08 15:50:28 +03:00
Alex Gleason 68202d655e Add InferSeoMetaPlugin 2025-06-07 16:37:03 -05:00
Alex Gleason 641f570329 Only add the client tag if the page is served over https 2025-06-07 16:32:28 -05:00
Alex Gleason c2d5187efb Add information about tags to context 2025-06-07 16:24:11 -05:00
Alex Gleason 9ad31aa674 Add clarifying section about creating new kinds vs using existing kinds 2025-06-07 15:47:56 -05:00
Alex Gleason d1a4e26f79 Add Unhead 2025-06-07 15:19:21 -05:00
Alex Gleason b3bc9d45e0 Tell the robot to use the generate_kind tool 2025-06-07 14:29:29 -05:00
Alex Gleason 1b74dc38fd Switch to Nostrbook MCP from npm 2025-06-07 13:58:00 -05:00
Alex Gleason 7a7d91dbed Add no-inline-script eslint rule 2025-06-07 10:56:52 -05:00
Alex Gleason 2d325f7343 inter -> font-name 2025-06-06 14:28:01 -05:00
Alex Gleason d2854f917c Add event validation step to context 2025-06-05 05:23:23 -05:00
Alex Gleason 28cda6d365 Remove unnecessary text 2025-06-04 18:34:23 -05:00
Alex Gleason da87f2c7b1 RelaySelector should not accept any props 2025-06-04 18:32:45 -05:00
Alex Gleason 61508020ae Tell the robot to manage a NIP.md file 2025-06-04 17:56:30 -05:00
Alex Gleason f146bf58d7 Add a sane default CSP 2025-06-04 13:07:41 -05:00
Alex Gleason cd87b6e430 Publish to preset relays 2025-06-04 11:32:12 -05:00
Alex Gleason 696c5ba963 Bully the robot to use skeletons instead of spinners 2025-06-04 11:00:35 -05:00
Alex Gleason 36e49106a6 Update CONTEXT.md with latest changes 2025-06-04 10:35:07 -05:00
Alex Gleason 048bf4cc69 Refactor AppProvider, AppConfig and presetRelays 2025-06-04 10:20:31 -05:00
Alex Gleason 3ad83cd114 Refactor AppProvider 2025-06-04 10:06:38 -05:00
Alex Gleason c3310ab485 Consolidate ThemeProvider and AppProvider 2025-06-04 09:42:53 -05:00
Alex Gleason bce7af2e76 Remove dark mode text from CONTEXT.md 2025-06-04 09:15:25 -05:00
Alex Gleason f762136f14 Remove Spinner and don't lazy-load components 2025-06-04 09:14:44 -05:00
Alex Gleason 5b90ebe482 Prevent the bot from disabling eslint rules 2025-06-02 22:35:07 -05:00
Alex Gleason c2ff2a990f Reorder relays 2025-06-02 22:13:22 -05:00
Alex Gleason 0481cd024e Tweak the default relay list 2025-06-02 22:08:03 -05:00
Alex Gleason 1617d80ece Use hostname in client tag 2025-06-02 22:05:03 -05:00
Alex Gleason a8163d7a6c Add RelaySelector 2025-06-02 21:46:07 -05:00
Alex Gleason 190f0cd791 Switch back to relay.nostr.band 2025-06-02 18:41:06 -05:00
Alex Gleason aa4110e6b3 CONTEXT.md tweaks 2025-06-02 15:25:16 -05:00
Alex Gleason 94d1688f43 Loosen color scheme phrasing 2025-06-02 11:53:12 -05:00
Alex Gleason 9f12c58dc0 Add Design Customization section to CONTEXT.md 2025-06-02 10:53:54 -05:00
Alex Gleason 0ee653f631 Make light theme the default 2025-06-02 10:14:56 -05:00
Alex Gleason 3672a13ac8 Bully the robot to add a custom font 2025-06-02 10:13:20 -05:00
Alex Gleason ac46749fad Don't write tests so religiously 2025-06-01 21:34:11 -05:00
Alex Gleason 1fc548c7e9 Improve eslint rules for unused vars 2025-06-01 17:28:25 -05:00
Alex Gleason 8bdff8da6d Lazy load page components 2025-06-01 16:26:09 -05:00
Alex Gleason 3a34db8320 Add dark theme support to NotFound.tsx 2025-06-01 16:08:27 -05:00
Alex Gleason 065f3cfe02 Suppress only React Router Future warnings in tests 2025-06-01 15:36:05 -05:00
Alex Gleason ed2d3798ea Silence console output from passed tests 2025-06-01 14:28:02 -05:00
Alex Gleason 03f804ed90 Clarify signer usage 2025-06-01 11:57:37 -05:00
Alex Gleason aa1e2145d0 Fix NoteContent test 2025-06-01 11:12:35 -05:00
Alex Gleason 130300f1c1 Use generated username fallback in other parts of the UI 2025-06-01 11:11:13 -05:00
Alex Gleason 9cb2795496 Add genUserName module 2025-06-01 11:04:22 -05:00
Alex Gleason 34770a3145 LoginArea display and context improvements 2025-06-01 11:00:53 -05:00
Alex Gleason 37bee859b6 Upgrade Vite to 6.x, fixing dependency vulnerability 2025-06-01 09:58:00 -05:00
Alex Gleason 139e6696db Improve LoginArea sizing and space 2025-06-01 09:47:15 -05:00
Alex Gleason 738b512d9c ThemeProvider nitpicks 2025-06-01 09:37:49 -05:00
Alex Gleason 7c5fe75572 Generate a deterministic name from pubkey if no display name is set 2025-06-01 09:28:20 -05:00
Alex Gleason 865ca7039f Improve NoteContent and NoteContent tests 2025-06-01 09:20:00 -05:00
Alex Gleason acbe053c97 Add nip19 routing info to CONTEXT.md 2025-06-01 08:57:58 -05:00
Alex Gleason 830d806933 NoteContent can linkify any kind, add TestApp component and "Testing Your Changes" to CONTEXT.md 2025-06-01 08:39:33 -05:00
Alex Gleason ee42c84171 Scroll to top during navigation changes 2025-06-01 07:32:33 -05:00
Alex Gleason 98f3305aa1 Add FIXME comment to Index.tsx 2025-05-31 00:03:40 +02:00
Alex Gleason 2d326ca5e9 Remove ThemeToggle component 2025-05-31 00:01:08 +02:00
Alex Gleason dbd28373a5 Require additional index.html properties 2025-05-30 23:58:38 +02:00
Alex Gleason ed3080d34e Return errors for FIXME comments 2025-05-30 23:46:15 +02:00
Alex Gleason 79ed87e67c useNostrPublish returns the event 2025-05-30 23:40:57 +02:00
Alex Gleason 9221693edb Remove theme toggle from CONTEXT.md 2025-05-30 23:38:20 +02:00
Alex Gleason 1b8dab92b9 webmanifest eslint 2025-05-30 23:02:12 +02:00
Alex Gleason 95de9fde27 eslint HTML title 2025-05-30 22:58:43 +02:00
Alex Gleason 81f90b9985 Add dark theme support to placeholder index 2025-05-30 22:48:59 +02:00
Alex Gleason 0e8a141490 Add custom eslint rule: no-placeholder-comments 2025-05-30 22:45:59 +02:00
Alex Gleason a6eeb05d6e Add ThemeProvider 2025-05-30 22:38:23 +02:00
Alex Gleason e0d94fae71 Add GitLab CI file 2025-05-30 22:19:04 +02:00
Alex Gleason be2d2d63fa Add PWA _redirects file 2025-05-30 22:18:50 +02:00
Alex Gleason f633f4b423 Use claude sonnet, not opus 2025-05-29 22:11:40 +02:00
Alex Gleason 2c5d38013f Switch to Ditto relay, don't include intentional error in App.tsx lol 2025-05-27 23:48:03 +02:00
Alex Gleason d14652559e Add test suite 2025-05-27 23:10:17 +02:00
Alex Gleason 4254b9eb0b Change phrasing of relay list AI comments 2025-05-27 22:44:48 +02:00
Alex Gleason e099d8b467 Merge branch 'eslint' into 'main'
Add eslint to ci

See merge request soapbox-pub/mkstack!4
2025-05-23 10:40:36 +00:00
Alex Gleason ef7667501b Add eslint to ci 2025-05-23 12:39:21 +02:00
Alex Gleason 7edfde7e9f Upgrade model to claude-sonnet-4 2025-05-22 21:38:26 +02:00
Alex Gleason 69faf49454 Add max width to AccountSwitcher 2025-05-20 03:32:37 -05:00
Alex Gleason aa2468b656 Kind 1 text rendering 2025-05-17 00:37:39 -05:00
Alex Gleason 7ee419bc6d Stop setting wrong relay URLs 2025-05-16 18:30:47 -05:00
Alex Gleason 73e7e818b2 Improve AccountSwitcher without kind 0 2025-05-16 14:09:28 -05:00
Alex Gleason ebc399776d Fix SignupDialog (so it logs the user in immediately after generating the key) 2025-05-16 13:55:12 -05:00
Alex Gleason 56df17b56e CONTEXT: fix Nostr headings depth 2025-05-16 13:47:14 -05:00
Alex Gleason 856d333c30 CONTEXT: encryption and decryption 2025-05-16 13:43:59 -05:00
Alex Gleason b24578f0db CONTEXT: LoginArea should not be wrapped in any conditional logic 2025-05-16 12:30:41 -05:00
Alex Gleason cc3d87192c Add a "client" tag to all published events 2025-05-16 12:28:01 -05:00
Alex Gleason 70eceef6ae Fix ci script type checking 2025-05-14 23:09:39 -05:00
Alex Gleason 601b3ce370 Add file uploads with Blossom 2025-05-14 17:15:00 -05:00
Alex Gleason f77a6a4af3 Add EditProfileForm 2025-05-14 15:56:53 -05:00
Alex Gleason d05a78880a CONTEXT.md: small correction for nip19 identifiers 2025-05-14 12:00:02 -05:00
Alex Gleason 750c165c05 Merge branch 'nip19' into 'main'
Add NIP-19 decoding to context

See merge request soapbox-pub/mkstack!3
2025-05-10 21:55:00 +00:00
Alex Gleason aa91528de8 Add NIP-19 decoding to context 2025-05-10 16:54:06 -05:00
Alex Gleason 95eb9634b5 Upgrade Nostrify 2025-05-10 10:00:02 -05:00
Alex Gleason 69060820f8 Include 404.html in build 2025-05-09 19:23:25 -05:00
Alex Gleason 1a431c9d8a Add useAuthor code snippet to CONTEXT.md 2025-05-09 16:10:33 -05:00
Alex Gleason 246ffb2181 Improve stack image 2025-05-07 11:19:08 -05:00
Alex Gleason db13869675 Improve stack banner 2025-05-07 10:41:39 -05:00
Alex Gleason b8137d0751 Change stack banner image 2025-05-06 18:06:03 -05:00
Alex Gleason 16ca716db2 add stack image 2025-05-05 21:47:02 -05:00
Alex Gleason 70dec2fc9a Add stack.json, mcp.json -> agent.json 2025-05-05 21:15:37 -05:00
Alex Gleason cac4ae6b93 Upgrade @nostrify/react 2025-05-04 18:40:41 -05:00
Alex Gleason a7fcaaf1f3 Add mcp.json 2025-05-03 16:26:06 -05:00
Alex Gleason 3052ce66f1 Merge branch 'fix-mac-issue' into 'main'
Fix mac issue

See merge request soapbox-pub/mkstack!2
2025-05-02 15:43:50 +00:00
danidfra 87a0846bbe Fix mac issue 2025-05-02 12:40:51 -03:00
Alex Gleason e4d081d3da Add npm deploy script 2025-04-26 13:59:26 -05:00
Alex Gleason d623f11653 Add GitHub Pages deploy action 2025-04-25 13:46:43 -05:00
Alex Gleason 2ac30c4f29 Use just relay.nostr.band as the default relay for now 2025-04-25 09:50:32 -05:00
Alex Gleason b8603ff80e Remove unused App.css 2025-04-25 09:43:03 -05:00
Alex Gleason 3cc2fe6d64 Add a placeholder useNostr hook 2025-04-25 09:32:43 -05:00
71 changed files with 7155 additions and 3800 deletions

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
name: Deploy to GitHub Pages
on:
# Runs on pushes targeting the default branch
push:
branches: ["main"]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
# Single deploy job
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
- name: Install dependencies and build
run: |
npm install
npm run build
cp dist/index.html dist/404.html
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: dist
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
+30
View File
@@ -0,0 +1,30 @@
name: Test
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
- name: Clean install dependencies
run: |
rm -rf node_modules package-lock.json
npm install
- name: Run tests
run: npm run test
+3
View File
@@ -20,3 +20,6 @@ dist-ssr
*.njsproj *.njsproj
*.sln *.sln
*.sw? *.sw?
# Vercel
.vercel
+30
View File
@@ -0,0 +1,30 @@
image: node:22
default:
interruptible: true
timeout: 1 minute
stages:
- build
- deploy
build:
stage: build
script:
- npm run build
only:
variables:
- $CI_DEFAULT_BRANCH != $CI_COMMIT_REF_NAME
pages:
stage: deploy
script:
- npm run build
- rm -rf public
- mv dist public
artifacts:
paths:
- public
only:
variables:
- $CI_DEFAULT_BRANCH == $CI_COMMIT_REF_NAME
+670 -19
View File
@@ -9,17 +9,35 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- **Vite**: Fast build tool and development server - **Vite**: Fast build tool and development server
- **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind - **shadcn/ui**: Unstyled, accessible UI components built with Radix UI and Tailwind
- **Nostrify**: Nostr protocol framework for Deno and web - **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: For client-side routing - **React Router**: For client-side routing with BrowserRouter and ScrollToTop functionality
- **TanStack Query**: For data fetching, caching, and state management - **TanStack Query**: For data fetching, caching, and state management
- **TypeScript**: For type-safe JavaScript development - **TypeScript**: For type-safe JavaScript development
## Project Structure ## Project Structure
- `/src/components/`: UI components including NostrProvider for Nostr integration - `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/hooks/`: Custom hooks including `useNostr` and `useNostrQuery` - `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/pages/`: Page components used by React Router - `/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/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext)
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets - `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
- `AppRouter.tsx`: React Router configuration
## UI Components ## UI Components
@@ -42,7 +60,7 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
- **Command**: Command palette for keyboard-first interfaces - **Command**: Command palette for keyboard-first interfaces
- **ContextMenu**: Right-click menu component - **ContextMenu**: Right-click menu component
- **Dialog**: Modal window overlay - **Dialog**: Modal window overlay
- **Drawer**: Side-sliding panel - **Drawer**: Side-sliding panel (using vaul)
- **DropdownMenu**: Menu that appears from a trigger element - **DropdownMenu**: Menu that appears from a trigger element
- **Form**: Form validation and submission handling - **Form**: Form validation and submission handling
- **HoverCard**: Card that appears when hovering over an element - **HoverCard**: Card that appears when hovering over an element
@@ -75,10 +93,174 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS. These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
## System Prompt Management
The AI assistant's behavior and knowledge is defined by the CONTEXT.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
1. Edit CONTEXT.md directly
2. The changes take effect in the next session
## "Vibed with MKStack"
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/tools/mkstack/
## Nostr Protocol Integration ## Nostr Protocol Integration
This project comes with custom hooks for querying and publishing events on the Nostr network. 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
The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively. The `useNostr` hook returns an object containing a `nostr` property, with `.query()` and `.event()` methods for querying and publishing Nostr events respectively.
@@ -115,11 +297,148 @@ function usePosts() {
} }
``` ```
#### 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. 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 ### The `useNostrPublish` Hook
To publish events, use the `useNostrPublish` hook in this project. To publish events, use the `useNostrPublish` hook in this project. This hook automatically adds a "client" tag to published events.
```tsx ```tsx
import { useState } from 'react'; import { useState } from 'react';
@@ -163,13 +482,199 @@ function MyComponent() {
<div> <div>
{/* other components ... */} {/* other components ... */}
<LoginArea /> <LoginArea className="max-w-60" />
</div> </div>
); );
} }
``` ```
The `LoginArea` component displays a "Log in" button when the user is logged out, and changes to an account switcher once the user is logged in. It handles all the login-related UI and interactions internally, including displaying login dialogs and switching between accounts. 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 ## Development Practices
@@ -178,21 +683,167 @@ The `LoginArea` component displays a "Log in" button when the user is logged out
- Implements Path Aliases with `@/` prefix for cleaner imports - Implements Path Aliases with `@/` prefix for cleaner imports
- Uses Vite for fast development and production builds - Uses Vite for fast development and production builds
- Component-based architecture with React hooks - Component-based architecture with React hooks
- Default connection to multiple Nostr relays for network redundancy - 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
## Build & Deployment ## Loading States
- Build for production: `npm run build` **Use skeleton loading** for structured content (feeds, profiles, forms). **Use spinners** only for buttons or short operations.
- Development build: `npm run build:dev`
```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 ## Testing Your Changes
Whenever you modify code, you should test your changes after you're finished by running: Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
```bash **Your task is not considered finished until this test passes without errors.**
npm run ci
```
This command will typecheck the code and attempt to build it.
Your task is not considered finished until this test passes without errors.
+2 -6
View File
@@ -1,7 +1,3 @@
# mkstack # MKStack
> NOTE: This README is from a template and should be replaced with your project description. Template for building Nostr client application with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
## Created with mkstack
mkstack is a starter template for building Nostr web clients in TypeScript, using React, Tailwind, shadcn/ui, Vite, and Nostrify.
+15
View File
@@ -0,0 +1,15 @@
{
"model": "claude-sonnet-4",
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
+146
View File
@@ -0,0 +1,146 @@
# Custom ESLint Rules
This directory contains custom ESLint rules for the project.
## no-inline-script
This rule prevents the use of inline script tags in HTML files. Inline scripts can pose security risks and violate Content Security Policy (CSP) directives.
### Examples
❌ **Bad** - These will trigger the rule:
```html
<!-- Inline JavaScript code -->
<script>
console.log("This is inline JavaScript");
</script>
<!-- Inline JSON-LD structured data -->
<script type="application/ld+json">
{"@context": "https://schema.org", "@type": "Organization"}
</script>
```
✅ **Good** - These are fine:
```html
<!-- External script files -->
<script src="/js/app.js"></script>
<script type="module" src="/src/main.tsx"></script>
<!-- Empty script tags (no content) -->
<script id="data-container"></script>
```
### Configuration
The rule is configured in `eslint.config.js` as:
```javascript
"custom/no-inline-script": "error"
```
### Purpose
This rule helps maintain security best practices by:
- Preventing XSS vulnerabilities from inline scripts
- Enforcing Content Security Policy compliance
- Encouraging separation of concerns (HTML structure vs JavaScript logic)
- Making code easier to maintain and debug
## no-placeholder-comments
This rule detects and flags comments that start with "// In a real" (case-insensitive). These comments typically indicate placeholder implementations that should be replaced with real code.
### Examples
❌ **Bad** - These will trigger the rule:
```javascript
// In a real application, this would connect to a database
const data = [];
// in a real world scenario, this would be different
const config = {};
/* In a real implementation, we would handle errors */
const handleError = () => {};
```
✅ **Good** - These are fine:
```javascript
// This is a regular comment
const data = [];
// TODO: Implement database connection
const config = {};
// Note: In a real application, consider using a database
const handleError = () => {};
```
### Configuration
The rule is configured in `eslint.config.js` as:
```javascript
"custom/no-placeholder-comments": "error"
```
You can change the severity level to:
- `"off"` - Disable the rule
- `"warn"` - Show as warning
- `"error"` - Show as error (current setting)
### Purpose
This rule helps ensure that placeholder comments used during development are replaced with actual implementations before code is committed or deployed to production.
## require-webmanifest
This rule ensures that HTML files include a proper web manifest link tag and that the referenced manifest file exists. Web manifests are essential for Progressive Web Apps (PWAs) and provide metadata about the application.
### Examples
❌ **Bad** - These will trigger the rule:
```html
<!-- Missing manifest link entirely -->
<head>
<title>My App</title>
</head>
<!-- Manifest file doesn't exist -->
<head>
<link rel="manifest" href="/nonexistent-manifest.json">
</head>
<!-- Invalid manifest link (missing rel or href) -->
<head>
<link href="/manifest.json">
</head>
```
✅ **Good** - These are fine:
```html
<!-- Proper manifest link with existing file -->
<head>
<link rel="manifest" href="/manifest.json">
</head>
<!-- Alternative valid manifest link -->
<head>
<link rel="manifest" href="/public/site.webmanifest">
</head>
```
### Configuration
The rule is configured in `eslint.config.js` as:
```javascript
"custom/require-webmanifest": "error"
```
### Purpose
This rule helps ensure:
- PWA compliance by requiring a web manifest
- Proper manifest file structure and accessibility
- Better user experience on mobile devices
- App installation capabilities
- Consistent branding and metadata across platforms
+11
View File
@@ -0,0 +1,11 @@
import noInlineScript from './no-inline-script.js';
import noPlaceholderComments from './no-placeholder-comments.js';
import requireWebmanifest from './require-webmanifest.js';
export default {
rules: {
'no-inline-script': noInlineScript,
'no-placeholder-comments': noPlaceholderComments,
'require-webmanifest': requireWebmanifest,
},
};
+40
View File
@@ -0,0 +1,40 @@
/**
* Rule to prevent inline script tags in HTML files
*/
export default {
meta: {
type: 'problem',
docs: {
description: 'Prevent inline script tags in HTML files',
category: 'Security',
recommended: true,
},
fixable: null,
schema: [],
messages: {
noInlineScript: 'Inline script tags are not allowed. Move script content to external files.',
},
},
create(context) {
return {
// For HTML files, we need to check script tags
'ScriptTag'(node) {
// Check if this is an inline script (has content but no src attribute)
const hasContent = node.value && node.value.value && node.value.value.trim().length > 0;
const hasSrc = node.attributes && node.attributes.some(attr =>
attr.key && attr.key.value === 'src'
);
// If the script has content but no src attribute, it's an inline script
if (hasContent && !hasSrc) {
context.report({
node,
messageId: 'noInlineScript',
});
}
},
};
},
};
+45
View File
@@ -0,0 +1,45 @@
/**
* Custom ESLint rule to detect placeholder comments starting with "// In a real"
* These comments indicate incomplete implementations that should be replaced with real code.
*/
export default {
meta: {
type: "problem",
docs: {
description: "Disallow placeholder comments starting with '// In a real'",
category: "Best Practices",
recommended: true,
},
fixable: null,
schema: [],
messages: {
placeholderComment: "Placeholder comment detected: '{{comment}}'. This should be replaced with a real implementation.",
},
},
create(context) {
const sourceCode = context.getSourceCode();
return {
Program() {
const comments = sourceCode.getAllComments();
comments.forEach((comment) => {
const commentText = comment.value.trim();
// Check if comment starts with "In a real" (case-insensitive)
if (commentText.toLowerCase().startsWith("in a real")) {
context.report({
node: comment,
messageId: "placeholderComment",
data: {
comment: `// ${commentText}`,
},
});
}
});
},
};
},
};
+84
View File
@@ -0,0 +1,84 @@
import fs from 'fs';
import path from 'path';
export default {
meta: {
type: 'problem',
docs: {
description: 'Require web manifest file and proper HTML link tag',
category: 'Best Practices',
},
fixable: null,
schema: [],
messages: {
missingManifestFile: 'Web manifest file not found. Expected {{expectedPath}}',
missingManifestLink: 'Missing web manifest link tag in HTML head',
invalidManifestLink: 'Web manifest link tag has incorrect rel or href attribute',
},
},
create(context) {
const filename = context.getFilename();
// Only run this rule on HTML files
if (!filename.endsWith('.html')) {
return {};
}
return {
Program(node) {
const sourceCode = context.getSourceCode();
const htmlContent = sourceCode.getText();
// Check for manifest link tag in HTML
const manifestLinkRegex = /<link[^>]*rel=["']manifest["'][^>]*>/i;
const manifestMatch = htmlContent.match(manifestLinkRegex);
if (!manifestMatch) {
context.report({
node,
messageId: 'missingManifestLink',
});
return;
}
// Extract href from the manifest link
const hrefMatch = manifestMatch[0].match(/href=["']([^"']+)["']/i);
if (!hrefMatch) {
context.report({
node,
messageId: 'invalidManifestLink',
});
return;
}
const manifestPath = hrefMatch[1];
// Resolve the manifest file path relative to the project root
const htmlDir = path.dirname(filename);
let resolvedManifestPath;
if (manifestPath.startsWith('/')) {
// Absolute path - check in public directory first, then project root
const publicPath = path.resolve(htmlDir, 'public' + manifestPath);
const rootPath = path.resolve(htmlDir, '.' + manifestPath);
resolvedManifestPath = fs.existsSync(publicPath) ? publicPath : rootPath;
} else {
// Relative path
resolvedManifestPath = path.resolve(htmlDir, manifestPath);
}
// Check if the manifest file exists
if (!fs.existsSync(resolvedManifestPath)) {
context.report({
node,
messageId: 'missingManifestFile',
data: {
expectedPath: manifestPath,
},
});
}
},
};
},
};
+47 -1
View File
@@ -3,6 +3,9 @@ import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks"; import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh"; import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint"; import tseslint from "typescript-eslint";
import htmlEslint from "@html-eslint/eslint-plugin";
import htmlParser from "@html-eslint/parser";
import customRules from "./eslint-rules/index.js";
export default tseslint.config( export default tseslint.config(
{ ignores: ["dist"] }, { ignores: ["dist"] },
@@ -13,9 +16,14 @@ export default tseslint.config(
ecmaVersion: 2020, ecmaVersion: 2020,
globals: globals.browser, globals: globals.browser,
}, },
linterOptions: {
noInlineConfig: true, // Prevents all eslint-disable comments
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
},
plugins: { plugins: {
"react-hooks": reactHooks, "react-hooks": reactHooks,
"react-refresh": reactRefresh, "react-refresh": reactRefresh,
"custom": customRules,
}, },
rules: { rules: {
...reactHooks.configs.recommended.rules, ...reactHooks.configs.recommended.rules,
@@ -23,7 +31,45 @@ export default tseslint.config(
"warn", "warn",
{ allowConstantExport: true }, { allowConstantExport: true },
], ],
"@typescript-eslint/no-unused-vars": "off", "@typescript-eslint/no-unused-vars": [
"error",
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"ignoreRestSiblings": true,
},
],
"custom/no-placeholder-comments": "error",
"no-warning-comments": [
"error",
{ terms: ["fixme"] },
],
},
},
{
files: ["**/*.html"],
plugins: {
"@html-eslint": htmlEslint,
"custom": customRules,
},
languageOptions: {
parser: htmlParser,
},
rules: {
"@html-eslint/require-title": "error",
"@html-eslint/require-meta-charset": "error",
"@html-eslint/require-meta-description": "error",
"@html-eslint/require-meta-viewport": "error",
"@html-eslint/require-open-graph-protocol": [
"error",
[
"og:type",
"og:title",
"og:description",
],
],
"custom/no-inline-script": "error",
"custom/require-webmanifest": "error",
}, },
} }
); );
+2 -1
View File
@@ -3,7 +3,8 @@
<head> <head>
<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" />
<title>mkstack</title> <meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
<link rel="manifest" href="/manifest.webmanifest">
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
+3961 -3153
View File
File diff suppressed because it is too large. Load diff
+15 -8
View File
@@ -5,16 +5,14 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "npm i && vite", "dev": "npm i && vite",
"build": "npm i && vite build", "build": "npm i && vite build && cp dist/index.html dist/404.html",
"build:dev": "npm i && vite build --mode development", "test": "npm i && tsc -p tsconfig.app.json --noEmit && eslint && vitest run && vite build",
"ci": "npm i && tsc --noEmit && vite build", "deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
"lint": "npm i && eslint .",
"preview": "npm i && vite preview"
}, },
"dependencies": { "dependencies": {
"@hookform/resolvers": "^3.9.0", "@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.44.0", "@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.1",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.1", "@nostrify/react": "npm:@jsr/nostrify__react@^0.2.5",
"@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",
@@ -43,6 +41,8 @@
"@radix-ui/react-toggle-group": "^1.1.0", "@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4", "@radix-ui/react-tooltip": "^1.1.4",
"@tanstack/react-query": "^5.56.2", "@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cmdk": "^1.0.0", "cmdk": "^1.0.0",
@@ -51,6 +51,7 @@
"input-otp": "^1.2.4", "input-otp": "^1.2.4",
"lucide-react": "^0.462.0", "lucide-react": "^0.462.0",
"next-themes": "^0.3.0", "next-themes": "^0.3.0",
"nostr-tools": "^2.13.0",
"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",
@@ -66,7 +67,11 @@
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.9.0", "@eslint/js": "^9.9.0",
"@html-eslint/eslint-plugin": "^0.41.0",
"@html-eslint/parser": "^0.41.0",
"@tailwindcss/typography": "^0.5.15", "@tailwindcss/typography": "^0.5.15",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@types/node": "^22.5.5", "@types/node": "^22.5.5",
"@types/react": "^18.3.1", "@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1", "@types/react-dom": "^18.3.1",
@@ -76,10 +81,12 @@
"eslint-plugin-react-hooks": "^5.1.0-rc.0", "eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.9", "eslint-plugin-react-refresh": "^0.4.9",
"globals": "^15.9.0", "globals": "^15.9.0",
"jsdom": "^26.1.0",
"postcss": "^8.4.47", "postcss": "^8.4.47",
"tailwindcss": "^3.4.11", "tailwindcss": "^3.4.11",
"typescript": "^5.5.3", "typescript": "^5.5.3",
"typescript-eslint": "^8.0.1", "typescript-eslint": "^8.0.1",
"vite": "^5.4.1" "vite": "^6.3.5",
"vitest": "^3.1.4"
} }
} }
+1
View File
@@ -0,0 +1 @@
/* /index.html 200
-42
View File
@@ -1,42 +0,0 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
+8
View File
@@ -0,0 +1,8 @@
import { render } from '@testing-library/react';
import { test } from 'vitest';
import App from './App';
test('App', () => {
render(<App />);
})
+41 -19
View File
@@ -1,17 +1,24 @@
import NostrProvider from '@/components/NostrProvider' // NOTE: This file should normally not be modified unless you are adding a new provider.
// To add new routes, edit the AppRouter.tsx file.
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createHead, UnheadProvider } from '@unhead/react/client';
import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense } from 'react';
import NostrProvider from '@/components/NostrProvider';
import { Toaster } from "@/components/ui/toaster"; import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner"; import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip"; import { TooltipProvider } from "@/components/ui/tooltip";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { NostrLoginProvider } from '@nostrify/react/login'; import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import AppRouter from './AppRouter'; import AppRouter from './AppRouter';
// AI: do not modify this relay list const head = createHead({
const defaultRelays = [ plugins: [
'wss://relay.damus.io', InferSeoMetaPlugin(),
'wss://relay.nostr.band', ],
'wss://ditto.pub/relay', });
];
const queryClient = new QueryClient({ const queryClient = new QueryClient({
defaultOptions: { defaultOptions: {
@@ -23,22 +30,37 @@ const queryClient = new QueryClient({
}, },
}); });
// NOTE: This file should normally not be modified unless you are adding a new provider. const defaultConfig: AppConfig = {
// To add new routes, edit the AppRouter.tsx file. theme: "light",
relayUrl: "wss://relay.nostr.band",
};
const presetRelays = [
{ url: 'wss://ditto.pub/relay', name: 'Ditto' },
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
{ url: 'wss://relay.damus.io', name: 'Damus' },
{ url: 'wss://relay.primal.net', name: 'Primal' },
];
export function App() { export function App() {
return ( return (
<NostrLoginProvider storageKey='nostr:login'> <UnheadProvider head={head}>
<NostrProvider relays={defaultRelays}> <AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<TooltipProvider> <NostrLoginProvider storageKey='nostr:login'>
<Toaster /> <NostrProvider>
<Sonner /> <TooltipProvider>
<AppRouter /> <Toaster />
</TooltipProvider> <Sonner />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider> </QueryClientProvider>
</NostrProvider> </AppProvider>
</NostrLoginProvider> </UnheadProvider>
); );
} }
+2
View File
@@ -1,4 +1,5 @@
import { BrowserRouter, Route, Routes } from "react-router-dom"; import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import Index from "./pages/Index"; import Index from "./pages/Index";
import NotFound from "./pages/NotFound"; import NotFound from "./pages/NotFound";
@@ -6,6 +7,7 @@ import NotFound from "./pages/NotFound";
export function AppRouter() { export function AppRouter() {
return ( return (
<BrowserRouter> <BrowserRouter>
<ScrollToTop />
<Routes> <Routes>
<Route path="/" element={<Index />} /> <Route path="/" element={<Index />} />
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */} {/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
+86
View File
@@ -0,0 +1,86 @@
import { ReactNode, useEffect } from 'react';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
interface AppProviderProps {
children: ReactNode;
/** Application storage key */
storageKey: string;
/** Default app configuration */
defaultConfig: AppConfig;
/** Optional list of preset relays to display in the RelaySelector */
presetRelays?: { name: string; url: string }[];
}
export function AppProvider(props: AppProviderProps) {
const {
children,
storageKey,
defaultConfig,
presetRelays,
} = props;
// App configuration state with localStorage persistence
const [config, setConfig] = useLocalStorage<AppConfig>(storageKey, defaultConfig);
// Generic config updater with callback pattern
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
setConfig(updater);
};
const appContextValue: AppContextType = {
config,
updateConfig,
presetRelays,
};
// Apply theme effects to document
useApplyTheme(config.theme);
return (
<AppContext.Provider value={appContextValue}>
{children}
</AppContext.Provider>
);
}
/**
* Hook to apply theme changes to the document root
*/
function useApplyTheme(theme: Theme) {
useEffect(() => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
if (theme === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')
.matches
? 'dark'
: 'light';
root.classList.add(systemTheme);
return;
}
root.classList.add(theme);
}, [theme]);
// Handle system theme changes when theme is set to "system"
useEffect(() => {
if (theme !== 'system') return;
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
const systemTheme = mediaQuery.matches ? 'dark' : 'light';
root.classList.add(systemTheme);
};
mediaQuery.addEventListener('change', handleChange);
return () => mediaQuery.removeEventListener('change', handleChange);
}, [theme]);
}
+349
View File
@@ -0,0 +1,349 @@
import React, { useEffect, useRef } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
import { Button } from '@/components/ui/button';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Loader2, Upload } from 'lucide-react';
import { NSchema as n, type NostrMetadata } from '@nostrify/nostrify';
import { useQueryClient } from '@tanstack/react-query';
import { useUploadFile } from '@/hooks/useUploadFile';
export const EditProfileForm: React.FC = () => {
const queryClient = useQueryClient();
const { user, metadata } = useCurrentUser();
const { mutateAsync: publishEvent, isPending } = useNostrPublish();
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const { toast } = useToast();
// Initialize the form with default values
const form = useForm<NostrMetadata>({
resolver: zodResolver(n.metadata()),
defaultValues: {
name: '',
about: '',
picture: '',
banner: '',
website: '',
nip05: '',
bot: false,
},
});
// Update form values when user data is loaded
useEffect(() => {
if (metadata) {
form.reset({
name: metadata.name || '',
about: metadata.about || '',
picture: metadata.picture || '',
banner: metadata.banner || '',
website: metadata.website || '',
nip05: metadata.nip05 || '',
bot: metadata.bot || false,
});
}
}, [metadata, form]);
// Handle file uploads for profile picture and banner
const uploadPicture = async (file: File, field: 'picture' | 'banner') => {
try {
// The first tuple in the array contains the URL
const [[_, url]] = await uploadFile(file);
form.setValue(field, url);
toast({
title: 'Success',
description: `${field === 'picture' ? 'Profile picture' : 'Banner'} uploaded successfully`,
});
} catch (error) {
console.error(`Failed to upload ${field}:`, error);
toast({
title: 'Error',
description: `Failed to upload ${field === 'picture' ? 'profile picture' : 'banner'}. Please try again.`,
variant: 'destructive',
});
}
};
const onSubmit = async (values: NostrMetadata) => {
if (!user) {
toast({
title: 'Error',
description: 'You must be logged in to update your profile',
variant: 'destructive',
});
return;
}
try {
// Combine existing metadata with new values
const data = { ...metadata, ...values };
// Clean up empty values
for (const key in data) {
if (data[key] === '') {
delete data[key];
}
}
// Publish the metadata event (kind 0)
await publishEvent({
kind: 0,
content: JSON.stringify(data),
});
// Invalidate queries to refresh the data
queryClient.invalidateQueries({ queryKey: ['logins'] });
queryClient.invalidateQueries({ queryKey: ['author', user.pubkey] });
toast({
title: 'Success',
description: 'Your profile has been updated',
});
} catch (error) {
console.error('Failed to update profile:', error);
toast({
title: 'Error',
description: 'Failed to update your profile. Please try again.',
variant: 'destructive',
});
}
};
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Name</FormLabel>
<FormControl>
<Input placeholder="Your name" {...field} />
</FormControl>
<FormDescription>
This is your display name that will be displayed to others.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="about"
render={({ field }) => (
<FormItem>
<FormLabel>Bio</FormLabel>
<FormControl>
<Textarea
placeholder="Tell others about yourself"
className="resize-none"
{...field}
/>
</FormControl>
<FormDescription>
A short description about yourself.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<FormField
control={form.control}
name="picture"
render={({ field }) => (
<ImageUploadField
field={field}
label="Profile Picture"
placeholder="https://example.com/profile.jpg"
description="URL to your profile picture. You can upload an image or provide a URL."
previewType="square"
onUpload={(file) => uploadPicture(file, 'picture')}
/>
)}
/>
<FormField
control={form.control}
name="banner"
render={({ field }) => (
<ImageUploadField
field={field}
label="Banner Image"
placeholder="https://example.com/banner.jpg"
description="URL to a wide banner image for your profile. You can upload an image or provide a URL."
previewType="wide"
onUpload={(file) => uploadPicture(file, 'banner')}
/>
)}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<FormField
control={form.control}
name="website"
render={({ field }) => (
<FormItem>
<FormLabel>Website</FormLabel>
<FormControl>
<Input placeholder="https://yourwebsite.com" {...field} />
</FormControl>
<FormDescription>
Your personal website or social media link.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="nip05"
render={({ field }) => (
<FormItem>
<FormLabel>NIP-05 Identifier</FormLabel>
<FormControl>
<Input placeholder="[email protected]" {...field} />
</FormControl>
<FormDescription>
Your verified Nostr identifier.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="bot"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">Bot Account</FormLabel>
<FormDescription>
Mark this account as automated or a bot.
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<Button
type="submit"
className="w-full md:w-auto"
disabled={isPending || isUploading}
>
{(isPending || isUploading) && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
Save Profile
</Button>
</form>
</Form>
);
};
// Reusable component for image upload fields
interface ImageUploadFieldProps {
field: {
value: string | undefined;
onChange: (value: string) => void;
name: string;
onBlur: () => void;
};
label: string;
placeholder: string;
description: string;
previewType: 'square' | 'wide';
onUpload: (file: File) => void;
}
const ImageUploadField: React.FC<ImageUploadFieldProps> = ({
field,
label,
placeholder,
description,
previewType,
onUpload,
}) => {
const fileInputRef = useRef<HTMLInputElement>(null);
return (
<FormItem>
<FormLabel>{label}</FormLabel>
<div className="flex flex-col gap-2">
<FormControl>
<Input
placeholder={placeholder}
name={field.name}
value={field.value ?? ''}
onChange={e => field.onChange(e.target.value)}
onBlur={field.onBlur}
/>
</FormControl>
<div className="flex items-center gap-2">
<input
type="file"
ref={fileInputRef}
accept="image/*"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) {
onUpload(file);
}
}}
/>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
>
<Upload className="h-4 w-4 mr-2" />
Upload Image
</Button>
{field.value && (
<div className={`h-10 ${previewType === 'square' ? 'w-10' : 'w-24'} rounded overflow-hidden`}>
<img
src={field.value}
alt={`${label} preview`}
className="h-full w-full object-cover"
/>
</div>
)}
</div>
</div>
<FormDescription>
{description}
</FormDescription>
<FormMessage />
</FormItem>
);
};
+31 -5
View File
@@ -1,28 +1,54 @@
import React, { useEffect, useRef } from 'react';
import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify'; import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify';
import { NostrContext } from '@nostrify/react'; import { NostrContext } from '@nostrify/react';
import React, { useRef } from 'react'; import { useQueryClient } from '@tanstack/react-query';
import { useAppContext } from '@/hooks/useAppContext';
interface NostrProviderProps { interface NostrProviderProps {
children: React.ReactNode; children: React.ReactNode;
relays: string[];
} }
const NostrProvider: React.FC<NostrProviderProps> = (props) => { const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const { children, relays } = props; const { children } = props;
const { config, presetRelays } = useAppContext();
const queryClient = useQueryClient();
// Create NPool instance only once // Create NPool instance only once
const pool = useRef<NPool | undefined>(undefined); const pool = useRef<NPool | undefined>(undefined);
// Use refs so the pool always has the latest data
const relayUrl = useRef<string>(config.relayUrl);
// Update refs when config changes
useEffect(() => {
relayUrl.current = config.relayUrl;
queryClient.resetQueries();
}, [config.relayUrl, queryClient]);
// Initialize NPool only once
if (!pool.current) { if (!pool.current) {
pool.current = new NPool({ pool.current = new NPool({
open(url: string) { open(url: string) {
return new NRelay1(url); return new NRelay1(url);
}, },
reqRouter(filters) { reqRouter(filters) {
return new Map(relays.map((url) => [url, filters])); return new Map([[relayUrl.current, filters]]);
}, },
eventRouter(_event: NostrEvent) { eventRouter(_event: NostrEvent) {
return relays; // Publish to the selected relay
const allRelays = new Set<string>([relayUrl.current]);
// Also publish to the preset relays, capped to 5
for (const { url } of (presetRelays ?? [])) {
allRelays.add(url);
if (allRelays.size >= 5) {
break;
}
}
return [...allRelays];
}, },
}); });
} }
+136
View File
@@ -0,0 +1,136 @@
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { NoteContent } from './NoteContent';
import type { NostrEvent } from '@nostrify/nostrify';
describe('NoteContent', () => {
it('linkifies URLs in kind 1 events', () => {
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: 'Check out this link: https://example.com',
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
const link = screen.getByRole('link', { name: 'https://example.com' });
expect(link).toBeInTheDocument();
expect(link).toHaveAttribute('href', 'https://example.com');
expect(link).toHaveAttribute('target', '_blank');
});
it('linkifies URLs in kind 1111 events (comments)', () => {
const event: NostrEvent = {
id: 'test-comment-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1111,
tags: [
['a', '30040:pubkey:identifier'],
['k', '30040'],
['p', 'pubkey'],
],
content: 'I think the log events should be different kind numbers instead of having a `log-type` tag. That way you can use normal Nostr filters to filter the log types. Also, the `note` type should just b a kind 1111: https://nostrbook.dev/kinds/1111',
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
const link = screen.getByRole('link', { name: 'https://nostrbook.dev/kinds/1111' });
expect(link).toBeInTheDocument();
expect(link).toHaveAttribute('href', 'https://nostrbook.dev/kinds/1111');
expect(link).toHaveAttribute('target', '_blank');
});
it('handles text without URLs correctly', () => {
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1111,
tags: [],
content: 'This is just plain text without any links.',
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
expect(screen.getByText('This is just plain text without any links.')).toBeInTheDocument();
expect(screen.queryByRole('link')).not.toBeInTheDocument();
});
it('renders hashtags as links', () => {
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: 'This is a post about #nostr and #bitcoin development.',
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
const nostrHashtag = screen.getByRole('link', { name: '#nostr' });
const bitcoinHashtag = screen.getByRole('link', { name: '#bitcoin' });
expect(nostrHashtag).toBeInTheDocument();
expect(bitcoinHashtag).toBeInTheDocument();
expect(nostrHashtag).toHaveAttribute('href', '/t/nostr');
expect(bitcoinHashtag).toHaveAttribute('href', '/t/bitcoin');
});
it('generates deterministic names for users without metadata and styles them differently', () => {
// Use a valid npub for testing
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: `Mentioning nostr:npub1zg69v7ys40x77y352eufp27daufrg4ncjz4ummcjx3t83y9tehhsqepuh0`,
sig: 'test-sig',
};
render(
<TestApp>
<NoteContent event={event} />
</TestApp>
);
// The mention should be rendered with a deterministic name
const mention = screen.getByRole('link');
expect(mention).toBeInTheDocument();
// Should have muted styling for generated names (gray instead of blue)
expect(mention).toHaveClass('text-gray-500');
expect(mention).not.toHaveClass('text-blue-500');
// The text should start with @ and contain a generated name (not a truncated npub)
const linkText = mention.textContent;
expect(linkText).not.toMatch(/^@npub1/); // Should not be a truncated npub
expect(linkText).toEqual("@Swift Falcon");
});
});
+137
View File
@@ -0,0 +1,137 @@
import { useMemo } from 'react';
import { type NostrEvent } from '@nostrify/nostrify';
import { Link } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor';
import { genUserName } from '@/lib/genUserName';
import { cn } from '@/lib/utils';
interface NoteContentProps {
event: NostrEvent;
className?: string;
}
/** Parses content of text note events so that URLs and hashtags are linkified. */
export function NoteContent({
event,
className,
}: NoteContentProps) {
// Process the content to render mentions, links, etc.
const content = useMemo(() => {
const text = event.content;
// Regex to find URLs, Nostr references, and hashtags
const regex = /(https?:\/\/[^\s]+)|nostr:(npub1|note1|nprofile1|nevent1)([023456789acdefghjklmnpqrstuvwxyz]+)|(#\w+)/g;
const parts: React.ReactNode[] = [];
let lastIndex = 0;
let match: RegExpExecArray | null;
let keyCounter = 0;
while ((match = regex.exec(text)) !== null) {
const [fullMatch, url, nostrPrefix, nostrData, hashtag] = match;
const index = match.index;
// Add text before this match
if (index > lastIndex) {
parts.push(text.substring(lastIndex, index));
}
if (url) {
// Handle URLs
parts.push(
<a
key={`url-${keyCounter++}`}
href={url}
target="_blank"
rel="noopener noreferrer"
className="text-blue-500 hover:underline"
>
{url}
</a>
);
} else if (nostrPrefix && nostrData) {
// Handle Nostr references
try {
const nostrId = `${nostrPrefix}${nostrData}`;
const decoded = nip19.decode(nostrId);
if (decoded.type === 'npub') {
const pubkey = decoded.data;
parts.push(
<NostrMention key={`mention-${keyCounter++}`} pubkey={pubkey} />
);
} else {
// For other types, just show as a link
parts.push(
<Link
key={`nostr-${keyCounter++}`}
to={`/${nostrId}`}
className="text-blue-500 hover:underline"
>
{fullMatch}
</Link>
);
}
} catch {
// If decoding fails, just render as text
parts.push(fullMatch);
}
} else if (hashtag) {
// Handle hashtags
const tag = hashtag.slice(1); // Remove the #
parts.push(
<Link
key={`hashtag-${keyCounter++}`}
to={`/t/${tag}`}
className="text-blue-500 hover:underline"
>
{hashtag}
</Link>
);
}
lastIndex = index + fullMatch.length;
}
// Add any remaining text
if (lastIndex < text.length) {
parts.push(text.substring(lastIndex));
}
// If no special content was found, just use the plain text
if (parts.length === 0) {
parts.push(text);
}
return parts;
}, [event]);
return (
<div className={cn("whitespace-pre-wrap break-words", className)}>
{content.length > 0 ? content : event.content}
</div>
);
}
// Helper component to display user mentions
function NostrMention({ pubkey }: { pubkey: string }) {
const author = useAuthor(pubkey);
const npub = nip19.npubEncode(pubkey);
const hasRealName = !!author.data?.metadata?.name;
const displayName = author.data?.metadata?.name ?? genUserName(pubkey);
return (
<Link
to={`/${npub}`}
className={cn(
"font-medium hover:underline",
hasRealName
? "text-blue-500"
: "text-gray-500 hover:text-gray-700"
)}
>
@{displayName}
</Link>
);
}
+174
View File
@@ -0,0 +1,174 @@
import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { useState } from "react";
import { useAppContext } from "@/hooks/useAppContext";
interface RelaySelectorProps {
className?: string;
}
export function RelaySelector(props: RelaySelectorProps) {
const { className } = props;
const { config, updateConfig, presetRelays = [] } = useAppContext();
const selectedRelay = config.relayUrl;
const setSelectedRelay = (relay: string) => {
updateConfig((current) => ({ ...current, relayUrl: relay }));
};
const [open, setOpen] = useState(false);
const [inputValue, setInputValue] = useState("");
const selectedOption = presetRelays.find((option) => option.url === selectedRelay);
// Function to normalize relay URL by adding wss:// if no protocol is present
const normalizeRelayUrl = (url: string): string => {
const trimmed = url.trim();
if (!trimmed) return trimmed;
// Check if it already has a protocol
if (trimmed.includes('://')) {
return trimmed;
}
// Add wss:// prefix
return `wss://${trimmed}`;
};
// Handle adding a custom relay
const handleAddCustomRelay = (url: string) => {
setSelectedRelay?.(normalizeRelayUrl(url));
setOpen(false);
setInputValue("");
};
// Check if input value looks like a valid relay URL
const isValidRelayInput = (value: string): boolean => {
const trimmed = value.trim();
if (!trimmed) return false;
// Basic validation - should contain at least a domain-like structure
const normalized = normalizeRelayUrl(trimmed);
try {
new URL(normalized);
return true;
} catch {
return false;
}
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={open}
className={cn("justify-between", className)}
>
<div className="flex items-center gap-2">
<Wifi className="h-4 w-4" />
<span className="truncate">
{selectedOption
? selectedOption.name
: selectedRelay
? selectedRelay.replace(/^wss?:\/\//, '')
: "Select relay..."
}
</span>
</div>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[300px] p-0">
<Command>
<CommandInput
placeholder="Search relays or type URL..."
value={inputValue}
onValueChange={setInputValue}
/>
<CommandList>
<CommandEmpty>
{inputValue && isValidRelayInput(inputValue) ? (
<CommandItem
onSelect={() => handleAddCustomRelay(inputValue)}
className="cursor-pointer"
>
<Plus className="mr-2 h-4 w-4" />
<div className="flex flex-col">
<span className="font-medium">Add custom relay</span>
<span className="text-xs text-muted-foreground">
{normalizeRelayUrl(inputValue)}
</span>
</div>
</CommandItem>
) : (
<div className="py-6 text-center text-sm text-muted-foreground">
{inputValue ? "Invalid relay URL" : "No relay found."}
</div>
)}
</CommandEmpty>
<CommandGroup>
{presetRelays
.filter((option) =>
!inputValue ||
option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
option.url.toLowerCase().includes(inputValue.toLowerCase())
)
.map((option) => (
<CommandItem
key={option.url}
value={option.url}
onSelect={(currentValue) => {
setSelectedRelay(normalizeRelayUrl(currentValue));
setOpen(false);
setInputValue("");
}}
>
<Check
className={cn(
"mr-2 h-4 w-4",
selectedRelay === option.url ? "opacity-100" : "opacity-0"
)}
/>
<div className="flex flex-col">
<span className="font-medium">{option.name}</span>
<span className="text-xs text-muted-foreground">{option.url}</span>
</div>
</CommandItem>
))}
{inputValue && isValidRelayInput(inputValue) && (
<CommandItem
onSelect={() => handleAddCustomRelay(inputValue)}
className="cursor-pointer border-t"
>
<Plus className="mr-2 h-4 w-4" />
<div className="flex flex-col">
<span className="font-medium">Add custom relay</span>
<span className="text-xs text-muted-foreground">
{normalizeRelayUrl(inputValue)}
</span>
</div>
</CommandItem>
)}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
+12
View File
@@ -0,0 +1,12 @@
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
export function ScrollToTop() {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
}, [pathname]);
return null;
}
+19 -11
View File
@@ -1,8 +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 React from 'react'; import { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react';
import { ChevronDown, LogOut, UserPlus } from 'lucide-react';
import { import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
@@ -11,7 +10,9 @@ import {
DropdownMenuTrigger, DropdownMenuTrigger,
} 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 { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts'; import { RelaySelector } from '@/components/RelaySelector';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
interface AccountSwitcherProps { interface AccountSwitcherProps {
onAddAccountClick: () => void; onAddAccountClick: () => void;
@@ -22,21 +23,28 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
if (!currentUser) return null; if (!currentUser) return null;
const getDisplayName = (account: Account): string => {
return account.metadata.name ?? genUserName(account.pubkey);
}
return ( return (
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<button className='flex items-center gap-3 p-3 rounded-full hover:bg-accent transition-all w-full text-foreground'> <button className='flex items-center gap-3 p-3 rounded-full hover:bg-accent transition-all w-full text-foreground'>
<Avatar className='w-10 h-10'> <Avatar className='w-10 h-10'>
<AvatarImage src={currentUser.metadata.picture} alt={currentUser.metadata.name} /> <AvatarImage src={currentUser.metadata.picture} alt={getDisplayName(currentUser)} />
<AvatarFallback>{currentUser.metadata.name?.charAt(0)}</AvatarFallback> <AvatarFallback>{getDisplayName(currentUser).charAt(0)}</AvatarFallback>
</Avatar> </Avatar>
<div className='flex-1 text-left hidden md:block'> <div className='flex-1 text-left hidden md:block truncate'>
<p className='font-medium text-sm'>{currentUser.metadata.name}</p> <p className='font-medium text-sm truncate'>{getDisplayName(currentUser)}</p>
</div> </div>
<ChevronDown className='w-4 h-4 text-muted-foreground' /> <ChevronDown className='w-4 h-4 text-muted-foreground' />
</button> </button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent className='w-56 p-2 animate-scale-in'> <DropdownMenuContent className='w-56 p-2 animate-scale-in'>
<div className='font-medium text-sm px-2 py-1.5'>Switch Relay</div>
<RelaySelector className="w-full" />
<DropdownMenuSeparator />
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div> <div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
{otherUsers.map((user) => ( {otherUsers.map((user) => (
<DropdownMenuItem <DropdownMenuItem
@@ -45,11 +53,11 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
className='flex items-center gap-2 cursor-pointer p-2 rounded-md' className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
> >
<Avatar className='w-8 h-8'> <Avatar className='w-8 h-8'>
<AvatarImage src={user.metadata.picture} alt={user.metadata.name} /> <AvatarImage src={user.metadata.picture} alt={getDisplayName(user)} />
<AvatarFallback>{user.metadata.name?.charAt(0)}</AvatarFallback> <AvatarFallback>{getDisplayName(user)?.charAt(0) || <UserIcon />}</AvatarFallback>
</Avatar> </Avatar>
<div className='flex-1'> <div className='flex-1 truncate'>
<p className='text-sm font-medium'>{user.metadata.name}</p> <p className='text-sm font-medium'>{getDisplayName(user)}</p>
</div> </div>
{user.id === currentUser.id && <div className='w-2 h-2 rounded-full bg-primary'></div>} {user.id === currentUser.id && <div className='w-2 h-2 rounded-full bg-primary'></div>}
</DropdownMenuItem> </DropdownMenuItem>
+14 -15
View File
@@ -1,26 +1,29 @@
// 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 { useState } from 'react';
import { User } from 'lucide-react'; import { User } 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 { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts'; import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
import { AccountSwitcher } from './AccountSwitcher'; import { AccountSwitcher } from './AccountSwitcher';
import { cn } from '@/lib/utils';
export function LoginArea() { export interface LoginAreaProps {
className?: string;
}
export function LoginArea({ className }: LoginAreaProps) {
const { currentUser } = useLoggedInAccounts(); const { currentUser } = useLoggedInAccounts();
const [loginDialogOpen, setLoginDialogOpen] = useState(false); const [loginDialogOpen, setLoginDialogOpen] = useState(false);
const [signupDialogOpen, setSignupDialogOpen] = useState(false);
const handleLogin = () => { const handleLogin = () => {
setLoginDialogOpen(false); setLoginDialogOpen(false);
setSignupDialogOpen(false);
}; };
return ( return (
<> <div className={cn("inline-flex items-center justify-center", className)}>
{currentUser ? ( {currentUser ? (
<AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} /> <AccountSwitcher onAddAccountClick={() => setLoginDialogOpen(true)} />
) : ( ) : (
@@ -29,21 +32,17 @@ export function LoginArea() {
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' 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' /> <User className='w-4 h-4' />
<span>Log in</span> <span className='truncate'>Log in</span>
</Button> </Button>
)} )}
<LoginDialog <LoginDialog
isOpen={loginDialogOpen} isOpen={loginDialogOpen}
onClose={() => setLoginDialogOpen(false)} onClose={() => setLoginDialogOpen(false)}
onLogin={handleLogin} onLogin={handleLogin}
onSignup={() => setSignupDialogOpen(true)}
/> />
<SignupDialog
isOpen={signupDialogOpen} </div>
onClose={() => setSignupDialogOpen(false)}
/>
</>
); );
} }
+108 -129
View File
@@ -1,7 +1,4 @@
// NOTE: This file is stable and usually should not be modified. import React, { useRef, useState, useEffect } from 'react';
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useEffect, useRef, useState } from 'react';
import { Shield, Upload } from 'lucide-react'; import { Shield, Upload } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx'; import { Button } from '@/components/ui/button.tsx';
import { Input } from '@/components/ui/input.tsx'; import { Input } from '@/components/ui/input.tsx';
@@ -14,20 +11,32 @@ import {
} from '@/components/ui/dialog.tsx'; } from '@/components/ui/dialog.tsx';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs.tsx'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs.tsx';
import { useLoginActions } from '@/hooks/useLoginActions'; import { useLoginActions } from '@/hooks/useLoginActions';
import { useToast } from '@/hooks/useToast';
import SignupFlow from './SignupFlow';
interface LoginDialogProps { interface LoginDialogProps {
isOpen: boolean; isOpen: boolean;
onClose: () => void; onClose: () => void;
onLogin: () => void; onLogin: () => void;
onSignup?: () => void;
} }
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => { const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin }) => {
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = useState(''); const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState(''); const [bunkerUri, setBunkerUri] = useState('');
const [view, setView] = useState<'login' | 'signup'>('login');
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
const login = useLoginActions(); const login = useLoginActions();
const { toast } = useToast();
useEffect(() => {
if (isOpen) {
setView('login');
setIsLoading(false);
setNsec('');
setBunkerUri('');
}
}, [isOpen]);
const handleExtensionLogin = () => { const handleExtensionLogin = () => {
setIsLoading(true); setIsLoading(true);
@@ -40,6 +49,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
onClose(); onClose();
} catch (error) { } catch (error) {
console.error('Extension login failed:', error); console.error('Extension login failed:', error);
toast({ title: 'Login Failed', description: (error as Error).message, variant: 'destructive' });
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@@ -48,13 +58,13 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
const handleKeyLogin = () => { const handleKeyLogin = () => {
if (!nsec.trim()) return; if (!nsec.trim()) return;
setIsLoading(true); setIsLoading(true);
try { try {
login.nsec(nsec); login.nsec(nsec);
onLogin(); onLogin();
onClose(); onClose();
} catch (error) { } catch (error) {
console.error('Nsec login failed:', error); console.error('Nsec login failed:', error);
toast({ title: 'Login Failed', description: 'Invalid nsec key.', variant: 'destructive' });
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@@ -63,13 +73,13 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
const handleBunkerLogin = () => { const handleBunkerLogin = () => {
if (!bunkerUri.trim() || !bunkerUri.startsWith('bunker://')) return; if (!bunkerUri.trim() || !bunkerUri.startsWith('bunker://')) return;
setIsLoading(true); setIsLoading(true);
try { try {
login.bunker(bunkerUri); login.bunker(bunkerUri);
onLogin(); onLogin();
onClose(); onClose();
} catch (error) { } catch (error) {
console.error('Bunker login failed:', error); console.error('Bunker login failed:', error);
toast({ title: 'Bunker Login Failed', description: 'Could not connect to bunker.', variant: 'destructive' });
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@@ -78,7 +88,6 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => { const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]; const file = e.target.files?.[0];
if (!file) return; if (!file) return;
const reader = new FileReader(); const reader = new FileReader();
reader.onload = (event) => { reader.onload = (event) => {
const content = event.target?.result as string; const content = event.target?.result as string;
@@ -87,130 +96,100 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
reader.readAsText(file); reader.readAsText(file);
}; };
const handleSignupClick = () => { const renderLoginView = () => (
onClose(); <>
if (onSignup) { <DialogHeader className='px-6 pt-6 pb-0 relative'>
onSignup(); <DialogTitle className='text-xl font-semibold text-center'>Log in</DialogTitle>
} <DialogDescription className='text-center text-muted-foreground mt-2'>
}; Access your account securely with your preferred method
</DialogDescription>
</DialogHeader>
<div className='px-6 py-8 space-y-6'>
<div className='text-center'>
<p className='text-sm text-muted-foreground'>New to Nostr?</p>
<Button variant='link' className='text-primary' onClick={() => setView('signup')}>
Create an account
</Button>
</div>
<div className='relative'>
<div className='absolute inset-0 flex items-center' aria-hidden='true'>
<div className='w-full border-t border-border' />
</div>
<div className='relative flex justify-center text-sm'>
<span className='px-2 bg-background text-muted-foreground'>Or log in with</span>
</div>
</div>
<Tabs defaultValue={'nostr' in window ? 'extension' : 'key'} className='w-full'>
<TabsList className='grid grid-cols-3 mb-6'>
<TabsTrigger value='extension'>Extension</TabsTrigger>
<TabsTrigger value='key'>Nsec</TabsTrigger>
<TabsTrigger value='bunker'>Bunker</TabsTrigger>
</TabsList>
<TabsContent value='extension' className='space-y-4'>
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'>
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' />
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
Login with one click using the browser extension
</p>
<Button className='w-full rounded-full py-6' onClick={handleExtensionLogin} disabled={isLoading}>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
</TabsContent>
<TabsContent value='key' className='space-y-4'>
<div className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='nsec' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Enter your nsec
</label>
<Input id='nsec' value={nsec} onChange={(e) => setNsec(e.target.value)} className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary' placeholder='nsec1...' />
</div>
<div className='text-center'>
<p className='text-sm mb-2 text-gray-600 dark:text-gray-400'>Or upload a key file</p>
<input type='file' accept='.txt' className='hidden' ref={fileInputRef} onChange={handleFileUpload} />
<Button variant='outline' className='w-full dark:border-gray-700 dark:bg-gray-800 dark:hover:bg-gray-700' onClick={() => fileInputRef.current?.click()}>
<Upload className='w-4 h-4 mr-2' />
Upload Nsec File
</Button>
</div>
<Button className='w-full rounded-full py-6 mt-4' onClick={handleKeyLogin} disabled={isLoading || !nsec.trim()}>
{isLoading ? 'Verifying...' : 'Login with Nsec'}
</Button>
</div>
</TabsContent>
<TabsContent value='bunker' className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Bunker URI
</label>
<Input id='bunkerUri' value={bunkerUri} onChange={(e) => setBunkerUri(e.target.value)} className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary' placeholder='bunker://' />
{bunkerUri && !bunkerUri.startsWith('bunker://') && (<p className='text-red-500 text-xs'>URI must start with bunker://</p>)}
</div>
<Button className='w-full rounded-full py-6' onClick={handleBunkerLogin} disabled={isLoading || !bunkerUri.trim() || !bunkerUri.startsWith('bunker://')}>
{isLoading ? 'Connecting...' : 'Login with Bunker'}
</Button>
</TabsContent>
</Tabs>
</div>
</>
);
const renderSignupView = () => (
<>
<DialogHeader>
<DialogTitle>Create Account</DialogTitle>
<DialogDescription>Create a new Nostr account.</DialogDescription>
</DialogHeader>
<div className='px-6 py-8'>
<SignupFlow onBack={() => setView('login')} onClose={onClose} />
</div>
</>
);
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 className='sm:max-w-md p-0 overflow-hidden rounded-2xl'>
<DialogHeader className='px-6 pt-6 pb-0 relative'> {view === 'login' ? renderLoginView() : renderSignupView()}
<DialogTitle className='text-xl font-semibold text-center'>Log in</DialogTitle>
<DialogDescription className='text-center text-muted-foreground mt-2'>
Access your account securely with your preferred method
</DialogDescription>
</DialogHeader>
<div className='px-6 py-8 space-y-6'>
<Tabs defaultValue={'nostr' in window ? 'extension' : 'key'} className='w-full'>
<TabsList className='grid grid-cols-3 mb-6'>
<TabsTrigger value='extension'>Extension</TabsTrigger>
<TabsTrigger value='key'>Nsec</TabsTrigger>
<TabsTrigger value='bunker'>Bunker</TabsTrigger>
</TabsList>
<TabsContent value='extension' className='space-y-4'>
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'>
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' />
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
Login with one click using the browser extension
</p>
<Button
className='w-full rounded-full py-6'
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
</TabsContent>
<TabsContent value='key' className='space-y-4'>
<div className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='nsec' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Enter your nsec
</label>
<Input
id='nsec'
value={nsec}
onChange={(e) => setNsec(e.target.value)}
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary'
placeholder='nsec1...'
/>
</div>
<div className='text-center'>
<p className='text-sm mb-2 text-gray-600 dark:text-gray-400'>Or upload a key file</p>
<input
type='file'
accept='.txt'
className='hidden'
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
variant='outline'
className='w-full dark:border-gray-700 dark:bg-gray-800 dark:hover:bg-gray-700'
onClick={() => fileInputRef.current?.click()}
>
<Upload className='w-4 h-4 mr-2' />
Upload Nsec File
</Button>
</div>
<Button
className='w-full rounded-full py-6 mt-4'
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
>
{isLoading ? 'Verifying...' : 'Login with Nsec'}
</Button>
</div>
</TabsContent>
<TabsContent value='bunker' className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Bunker URI
</label>
<Input
id='bunkerUri'
value={bunkerUri}
onChange={(e) => setBunkerUri(e.target.value)}
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary'
placeholder='bunker://'
/>
{bunkerUri && !bunkerUri.startsWith('bunker://') && (
<p className='text-red-500 text-xs'>URI must start with bunker://</p>
)}
</div>
<Button
className='w-full rounded-full py-6'
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim() || !bunkerUri.startsWith('bunker://')}
>
{isLoading ? 'Connecting...' : 'Login with Bunker'}
</Button>
</TabsContent>
</Tabs>
<div className='text-center text-sm'>
<p className='text-gray-600 dark:text-gray-400'>
Don't have an account?{' '}
<button
onClick={handleSignupClick}
className='text-primary hover:underline font-medium'
>
Sign up
</button>
</p>
</div>
</div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
); );
-164
View File
@@ -1,164 +0,0 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useState } from 'react';
import { Download, Key } from 'lucide-react';
import { Button } from '@/components/ui/button.tsx';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog.tsx';
import { toast } from '@/hooks/useToast.ts';
import { generateSecretKey, nip19 } from 'nostr-tools';
interface SignupDialogProps {
isOpen: boolean;
onClose: () => void;
}
const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose }) => {
const [step, setStep] = useState<'generate' | 'download' | 'done'>('generate');
const [isLoading, setIsLoading] = useState(false);
const [nsecKey, setNsecKey] = useState('');
// Generate a proper nsec key using nostr-tools
const generateKey = () => {
setIsLoading(true);
try {
// Generate a new private key
const privateKey = generateSecretKey();
// Convert to nsec format
const nsec = nip19.nsecEncode(privateKey);
setNsecKey(nsec);
setStep('download');
} catch (error) {
console.error('Failed to generate key:', error);
toast({
title: 'Error',
description: 'Failed to generate key. Please try again.',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};
const downloadKey = () => {
// Create a blob with the key text
const blob = new Blob([nsecKey], { type: 'text/plain' });
const url = globalThis.URL.createObjectURL(blob);
// Create a temporary link element and trigger download
const a = document.createElement('a');
a.href = url;
a.download = 'nsec.txt';
document.body.appendChild(a);
a.click();
// Clean up
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
toast({
title: 'Key downloaded',
description: 'Your key has been downloaded. Keep it safe!',
});
};
const finishSignup = () => {
setStep('done');
onClose();
toast({
title: 'Account created',
description: 'You are now logged in.',
});
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className='sm:max-w-md p-0 overflow-hidden rounded-2xl'>
<DialogHeader className='px-6 pt-6 pb-0 relative'>
<DialogTitle className='text-xl font-semibold text-center'>
{step === 'generate' && 'Create Your Account'}
{step === 'download' && 'Download Your Key'}
{step === 'done' && 'Setting Up Your Account'}
</DialogTitle>
<DialogDescription className='text-center text-muted-foreground mt-2'>
{step === 'generate' && 'Generate a secure key for your account'}
{step === 'download' && "Keep your key safe - you'll need it to log in"}
{step === 'done' && 'Finalizing your account setup'}
</DialogDescription>
</DialogHeader>
<div className='px-6 py-8 space-y-6'>
{step === 'generate' && (
<div className='text-center space-y-6'>
<div className='p-4 rounded-lg bg-gray-50 dark:bg-gray-800 flex items-center justify-center'>
<Key className='w-16 h-16 text-primary' />
</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>
)}
{step === 'download' && (
<div className='space-y-6'>
<div className='p-4 rounded-lg border bg-gray-50 dark:bg-gray-800 overflow-auto'>
<code className='text-xs break-all'>{nsecKey}</code>
</div>
<div className='text-sm text-gray-600 dark:text-gray-300 space-y-2'>
<p className='font-medium text-red-500'>Important:</p>
<ul className='list-disc pl-5 space-y-1'>
<li>This is your only way to access your account</li>
<li>Store it somewhere safe</li>
<li>Never share this key with anyone</li>
</ul>
</div>
<div className='flex flex-col space-y-3'>
<Button
variant='outline'
className='w-full'
onClick={downloadKey}
>
<Download className='w-4 h-4 mr-2' />
Download Key
</Button>
<Button
className='w-full rounded-full py-6'
onClick={finishSignup}
>
I've saved my key, continue
</Button>
</div>
</div>
)}
{step === 'done' && (
<div className='flex justify-center items-center py-8'>
<div className='animate-spin rounded-full h-12 w-12 border-b-2 border-primary'></div>
</div>
)}
</div>
</DialogContent>
</Dialog>
);
};
export default SignupDialog;
+212
View File
@@ -0,0 +1,212 @@
import React, { useState, useEffect } from 'react';
import { Download, KeyRound, Lock, CheckCircle, Copy, ArrowRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent } from '@/components/ui/card';
import { useToast } from '@/hooks/useToast';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { generateSecretKey, nip19 } from 'nostr-tools';
interface SignupFlowProps {
onBack: () => void;
onClose: () => void;
}
const SignupFlow: React.FC<SignupFlowProps> = ({ onBack, onClose }) => {
const [signupStep, setSignupStep] = useState<'welcome' | 'generate' | 'download' | 'profile' | 'done'>('welcome');
const [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [keySecured, setKeySecured] = useState<'none' | 'copied' | 'downloaded'>('none');
const [profileData, setProfileData] = useState({ name: '', about: '' });
const { toast } = useToast();
const login = useLoginActions();
const { mutateAsync: publishEvent, isPending: isPublishing } = useNostrPublish();
useEffect(() => {
setSignupStep('welcome');
setIsLoading(false);
setNsec('');
setKeySecured('none');
setProfileData({ name: '', about: '' });
}, []);
const generateKey = () => {
setIsLoading(true);
setTimeout(() => {
try {
const sk = generateSecretKey();
setNsec(nip19.nsecEncode(sk));
setSignupStep('download');
toast({ title: 'New key generated', description: 'Keep it safe.' });
} catch {
toast({ title: 'Error', description: 'Failed to generate key. Please try again.', variant: 'destructive' });
} finally {
setIsLoading(false);
}
}, 1000);
};
const downloadKey = () => {
try {
const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
const filename = 'secret-key.txt';
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
setKeySecured('downloaded');
toast({ title: 'Key Secured', 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 copyKey = () => {
navigator.clipboard.writeText(nsec);
setKeySecured('copied');
toast({ title: 'Copied to clipboard', description: 'Your key has been copied.' });
};
const finishKeySetup = () => {
try {
login.nsec(nsec);
setSignupStep('profile');
} catch {
toast({ title: 'Login Failed', description: 'Failed to login with the generated key. Please try again.', variant: 'destructive' });
}
};
const finishSignup = async (skipProfile = false) => {
try {
if (!skipProfile && (profileData.name || profileData.about)) {
const metadata: Record<string, string> = {};
if (profileData.name) metadata.name = profileData.name;
if (profileData.about) metadata.about = profileData.about;
await publishEvent({ kind: 0, content: JSON.stringify(metadata) });
toast({ title: 'Profile Created', description: 'Your profile has been created.' });
}
setSignupStep('done');
setTimeout(() => {
onClose();
toast({ title: 'Welcome!', description: 'You are now logged in.' });
}, 2000);
} catch {
toast({ title: 'Profile Setup Failed', description: 'Your account was created but profile setup failed. You can update it later.', variant: 'destructive' });
setSignupStep('done');
setTimeout(() => {
onClose();
toast({ title: 'Welcome!', description: 'You are now logged in.' });
}, 2000);
}
};
return (
<div className='space-y-4'>
{signupStep === 'welcome' && (
<div className='text-center space-y-4'>
<div className='flex justify-center items-center h-24'>
<KeyRound className='w-16 h-16 text-primary' />
</div>
<p>Your key is your identity. It's how you log in and how others see you.</p>
<Button className='w-full' onClick={() => setSignupStep('generate')}>
<ArrowRight className='w-5 h-5 mr-2' />
Get Started
</Button>
</div>
)}
{signupStep === 'generate' && (
<div className='text-center space-y-4'>
{isLoading ? (
<div className='space-y-3'>
<div className='relative flex justify-center items-center h-24'>
<KeyRound className='w-20 h-20 mx-auto animate-pulse text-primary' />
</div>
<p className='text-lg font-semibold'>Generating your key...</p>
</div>
) : (
<div className='space-y-3'>
<div className='flex justify-center items-center h-24'>
<KeyRound className='w-16 h-16 mx-auto text-primary' />
</div>
<p className='text-lg font-semibold'>Ready to generate your key?</p>
</div>
)}
{!isLoading && (<Button className='w-full' onClick={generateKey} disabled={isLoading}>Generate My Key</Button>)}
</div>
)}
{signupStep === 'download' && (
<div className='space-y-4'>
<div className='relative p-3 bg-muted rounded-xl border'>
<div className='flex items-center gap-2 mb-2'><Lock className='w-4 h-4' /><span className='text-sm font-medium'>Your Secret Key</span></div>
<div className='p-2 bg-background rounded-lg border'><code className='text-xs break-all font-mono'>{nsec}</code></div>
</div>
<div className='space-y-3'>
<p className='text-sm font-medium text-center'>Choose how to secure your key:</p>
<div className='grid grid-cols-1 gap-2'>
<Card className={`cursor-pointer transition-all duration-200 ${keySecured === 'copied' ? 'ring-2 ring-primary' : 'hover:bg-muted'}`}>
<CardContent className='p-3'>
<Button variant="ghost" className='w-full h-auto p-0 justify-start' onClick={copyKey}>
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${keySecured === 'copied' ? 'bg-primary/20' : 'bg-muted'}`}>
{keySecured === 'copied' ? (<CheckCircle className='w-4 h-4 text-primary' />) : (<Copy className='w-4 h-4' />)}
</div>
<div className='flex-1 text-left'><div className='font-medium text-sm'>Copy to Clipboard</div></div>
{keySecured === 'copied' && (<div className='text-xs font-medium text-primary'>✓ Copied</div>)}
</div>
</Button>
</CardContent>
</Card>
<Card className={`cursor-pointer transition-all duration-200 ${keySecured === 'downloaded' ? 'ring-2 ring-primary' : 'hover:bg-muted'}`}>
<CardContent className='p-3'>
<Button variant="ghost" className='w-full h-auto p-0 justify-start' onClick={downloadKey}>
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${keySecured === 'downloaded' ? 'bg-primary/20' : 'bg-muted'}`}>
{keySecured === 'downloaded' ? (<CheckCircle className='w-4 h-4 text-primary' />) : (<Download className='w-4 h-4' />)}
</div>
<div className='flex-1 text-left'><div className='font-medium text-sm'>Download as File</div></div>
{keySecured === 'downloaded' && (<div className='text-xs font-medium text-primary'>✓ Downloaded</div>)}
</div>
</Button>
</CardContent>
</Card>
</div>
<Button className='w-full' onClick={finishKeySetup} disabled={keySecured === 'none'}><Lock className='w-4 h-4 mr-2' />Continue</Button>
</div>
</div>
)}
{signupStep === 'profile' && (
<div className='space-y-4'>
<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' 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...' rows={3} disabled={isPublishing} />
</div>
</div>
<div className='space-y-3'>
<Button className='w-full' onClick={() => finishSignup(false)} disabled={isPublishing}>{isPublishing ? 'Creating Profile...' : 'Create Profile & Finish'}</Button>
<Button variant='outline' className='w-full' onClick={() => finishSignup(true)} disabled={isPublishing}>Skip for now</Button>
</div>
</div>
)}
{signupStep === '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>
)}
<Button variant='link' onClick={onBack}>Back to login</Button>
</div>
);
};
export default SignupFlow;
+1 -1
View File
@@ -2,7 +2,7 @@ import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog" import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button" import { buttonVariants } from "@/components/ui/button-variants"
const AlertDialog = AlertDialogPrimitive.Root const AlertDialog = AlertDialogPrimitive.Root
+21
View File
@@ -0,0 +1,21 @@
import { cva } from "class-variance-authority"
export const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
+3 -22
View File
@@ -1,27 +1,8 @@
import * as React from "react" import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority" import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { badgeVariants } from "./badge-variants"
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>, extends React.HTMLAttributes<HTMLDivElement>,
@@ -33,4 +14,4 @@ function Badge({ className, variant, ...props }: BadgeProps) {
) )
} }
export { Badge, badgeVariants } export { Badge }
+30
View File
@@ -0,0 +1,30 @@
import { cva } from "class-variance-authority"
export const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
+3 -31
View File
@@ -1,37 +1,9 @@
import * as React from "react" import * as React from "react"
import { Slot } from "@radix-ui/react-slot" import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority" import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { buttonVariants } from "./button-variants"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>, extends React.ButtonHTMLAttributes<HTMLButtonElement>,
@@ -53,4 +25,4 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
) )
Button.displayName = "Button" Button.displayName = "Button"
export { Button, buttonVariants } export { Button }
+1 -1
View File
@@ -3,7 +3,7 @@ import { ChevronLeft, ChevronRight } from "lucide-react";
import { DayPicker } from "react-day-picker"; import { DayPicker } from "react-day-picker";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button"; import { buttonVariants } from "@/components/ui/button-variants";
export type CalendarProps = React.ComponentProps<typeof DayPicker>; export type CalendarProps = React.ComponentProps<typeof DayPicker>;
+1 -1
View File
@@ -21,7 +21,7 @@ const Command = React.forwardRef<
)) ))
Command.displayName = CommandPrimitive.displayName Command.displayName = CommandPrimitive.displayName
interface CommandDialogProps extends DialogProps {} type CommandDialogProps = DialogProps
const CommandDialog = ({ children, ...props }: CommandDialogProps) => { const CommandDialog = ({ children, ...props }: CommandDialogProps) => {
return ( return (
+48
View File
@@ -0,0 +1,48 @@
import * as React from "react"
import {
FieldPath,
FieldValues,
useFormContext,
} from "react-hook-form"
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
export const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
type FormItemContextValue = {
id: string
}
export const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
export const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
+1 -44
View File
@@ -7,25 +7,14 @@ import {
FieldPath, FieldPath,
FieldValues, FieldValues,
FormProvider, FormProvider,
useFormContext,
} from "react-hook-form" } from "react-hook-form"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label" import { Label } from "@/components/ui/label"
import { FormFieldContext, FormItemContext, useFormField } from "./form-utils"
const Form = FormProvider const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = < const FormField = <
TFieldValues extends FieldValues = FieldValues, TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues> TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
@@ -39,37 +28,6 @@ const FormField = <
) )
} }
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
const FormItem = React.forwardRef< const FormItem = React.forwardRef<
HTMLDivElement, HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> React.HTMLAttributes<HTMLDivElement>
@@ -165,7 +123,6 @@ const FormMessage = React.forwardRef<
FormMessage.displayName = "FormMessage" FormMessage.displayName = "FormMessage"
export { export {
useFormField,
Form, Form,
FormItem, FormItem,
FormLabel, FormLabel,
@@ -0,0 +1,5 @@
import { cva } from "class-variance-authority"
export const navigationMenuTriggerStyle = cva(
"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"
)
+1 -6
View File
@@ -1,9 +1,9 @@
import * as React from "react" import * as React from "react"
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu" import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
import { cva } from "class-variance-authority"
import { ChevronDown } from "lucide-react" import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { navigationMenuTriggerStyle } from "./navigation-menu-variants"
const NavigationMenu = React.forwardRef< const NavigationMenu = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Root>, React.ElementRef<typeof NavigationMenuPrimitive.Root>,
@@ -40,10 +40,6 @@ NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName
const NavigationMenuItem = NavigationMenuPrimitive.Item const NavigationMenuItem = NavigationMenuPrimitive.Item
const navigationMenuTriggerStyle = cva(
"group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"
)
const NavigationMenuTrigger = React.forwardRef< const NavigationMenuTrigger = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Trigger>, React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger> React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
@@ -116,7 +112,6 @@ NavigationMenuIndicator.displayName =
NavigationMenuPrimitive.Indicator.displayName NavigationMenuPrimitive.Indicator.displayName
export { export {
navigationMenuTriggerStyle,
NavigationMenu, NavigationMenu,
NavigationMenuList, NavigationMenuList,
NavigationMenuItem, NavigationMenuItem,
+2 -1
View File
@@ -2,7 +2,8 @@ import * as React from "react"
import { ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react" import { ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { ButtonProps, buttonVariants } from "@/components/ui/button" import { ButtonProps } from "@/components/ui/button"
import { buttonVariants } from "@/components/ui/button-variants"
const Pagination = ({ className, ...props }: React.ComponentProps<"nav">) => ( const Pagination = ({ className, ...props }: React.ComponentProps<"nav">) => (
<nav <nav
+52
View File
@@ -0,0 +1,52 @@
import * as React from "react"
import { cva } from "class-variance-authority"
export const SIDEBAR_COOKIE_NAME = "sidebar:state"
export const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
export const SIDEBAR_WIDTH = "16rem"
export const SIDEBAR_WIDTH_MOBILE = "18rem"
export const SIDEBAR_WIDTH_ICON = "3rem"
export const SIDEBAR_KEYBOARD_SHORTCUT = "b"
export type SidebarContext = {
state: "expanded" | "collapsed"
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
export const SidebarContext = React.createContext<SidebarContext | null>(null)
export function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
}
return context
}
export const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
+15 -52
View File
@@ -1,6 +1,6 @@
import * as React from "react" import * as React from "react"
import { Slot } from "@radix-ui/react-slot" import { Slot } from "@radix-ui/react-slot"
import { VariantProps, cva } from "class-variance-authority" import { VariantProps } from "class-variance-authority"
import { PanelLeft } from "lucide-react" import { PanelLeft } from "lucide-react"
import { useIsMobile } from "@/hooks/useIsMobile" import { useIsMobile } from "@/hooks/useIsMobile"
@@ -16,34 +16,18 @@ import {
TooltipProvider, TooltipProvider,
TooltipTrigger, TooltipTrigger,
} from "@/components/ui/tooltip" } from "@/components/ui/tooltip"
import {
const SIDEBAR_COOKIE_NAME = "sidebar:state" SIDEBAR_COOKIE_NAME,
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7 SIDEBAR_COOKIE_MAX_AGE,
const SIDEBAR_WIDTH = "16rem" SIDEBAR_WIDTH,
const SIDEBAR_WIDTH_MOBILE = "18rem" SIDEBAR_WIDTH_MOBILE,
const SIDEBAR_WIDTH_ICON = "3rem" SIDEBAR_WIDTH_ICON,
const SIDEBAR_KEYBOARD_SHORTCUT = "b" SIDEBAR_KEYBOARD_SHORTCUT,
SidebarContext,
type SidebarContext = { useSidebar,
state: "expanded" | "collapsed" sidebarMenuButtonVariants,
open: boolean type SidebarContext as SidebarContextType,
setOpen: (open: boolean) => void } from "./sidebar-utils"
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
const SidebarContext = React.createContext<SidebarContext | null>(null)
function useSidebar() {
const context = React.useContext(SidebarContext)
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
}
return context
}
const SidebarProvider = React.forwardRef< const SidebarProvider = React.forwardRef<
HTMLDivElement, HTMLDivElement,
@@ -114,7 +98,7 @@ const SidebarProvider = React.forwardRef<
// This makes it easier to style the sidebar with Tailwind classes. // This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed" const state = open ? "expanded" : "collapsed"
const contextValue = React.useMemo<SidebarContext>( const contextValue = React.useMemo<SidebarContextType>(
() => ({ () => ({
state, state,
open, open,
@@ -509,27 +493,7 @@ const SidebarMenuItem = React.forwardRef<
)) ))
SidebarMenuItem.displayName = "SidebarMenuItem" SidebarMenuItem.displayName = "SidebarMenuItem"
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
const SidebarMenuButton = React.forwardRef< const SidebarMenuButton = React.forwardRef<
HTMLButtonElement, HTMLButtonElement,
@@ -757,5 +721,4 @@ export {
SidebarRail, SidebarRail,
SidebarSeparator, SidebarSeparator,
SidebarTrigger, SidebarTrigger,
useSidebar,
} }
+1 -2
View File
@@ -2,8 +2,7 @@ import * as React from "react"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
export interface TextareaProps export type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>
extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>( const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => { ({ className, ...props }, ref) => {
+1 -1
View File
@@ -3,7 +3,7 @@ import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"
import { type VariantProps } from "class-variance-authority" import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { toggleVariants } from "@/components/ui/toggle" import { toggleVariants } from "@/components/ui/toggle-variants"
const ToggleGroupContext = React.createContext< const ToggleGroupContext = React.createContext<
VariantProps<typeof toggleVariants> VariantProps<typeof toggleVariants>
+23
View File
@@ -0,0 +1,23 @@
import { cva } from "class-variance-authority"
export const toggleVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
{
variants: {
variant: {
default: "bg-transparent",
outline:
"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-10 px-3",
sm: "h-9 px-2.5",
lg: "h-11 px-5",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
+3 -24
View File
@@ -1,30 +1,9 @@
import * as React from "react" import * as React from "react"
import * as TogglePrimitive from "@radix-ui/react-toggle" import * as TogglePrimitive from "@radix-ui/react-toggle"
import { cva, type VariantProps } from "class-variance-authority" import { type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
import { toggleVariants } from "./toggle-variants"
const toggleVariants = cva(
"inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
{
variants: {
variant: {
default: "bg-transparent",
outline:
"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-10 px-3",
sm: "h-9 px-2.5",
lg: "h-11 px-5",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
const Toggle = React.forwardRef< const Toggle = React.forwardRef<
React.ElementRef<typeof TogglePrimitive.Root>, React.ElementRef<typeof TogglePrimitive.Root>,
@@ -40,4 +19,4 @@ const Toggle = React.forwardRef<
Toggle.displayName = TogglePrimitive.Root.displayName Toggle.displayName = TogglePrimitive.Root.displayName
export { Toggle, toggleVariants } export { Toggle }
+21
View File
@@ -0,0 +1,21 @@
import { createContext } from "react";
export type Theme = "dark" | "light" | "system";
export interface AppConfig {
/** Current theme */
theme: Theme;
/** Selected relay URL */
relayUrl: string;
}
export interface AppContextType {
/** Current application configuration */
config: AppConfig;
/** Update configuration using a callback that receives current config and returns new config */
updateConfig: (updater: (currentConfig: AppConfig) => AppConfig) => void;
/** Optional list of preset relays to display in the RelaySelector */
presetRelays?: { name: string; url: string }[];
}
export const AppContext = createContext<AppContextType | undefined>(undefined);
+14
View File
@@ -0,0 +1,14 @@
import { useContext } from "react";
import { AppContext, type AppContextType } from "@/contexts/AppContext";
/**
* Hook to access and update application configuration
* @returns Application context with config and update methods
*/
export function useAppContext(): AppContextType {
const context = useContext(AppContext);
if (context === undefined) {
throw new Error('useAppContext must be used within an AppProvider');
}
return context;
}
+2 -2
View File
@@ -38,11 +38,11 @@ export function useCurrentUser() {
}, [logins, loginToUser]); }, [logins, loginToUser]);
const user = users[0] as NUser | undefined; const user = users[0] as NUser | undefined;
const data = useAuthor(user?.pubkey); const author = useAuthor(user?.pubkey);
return { return {
user, user,
data,
users, users,
...author.data,
}; };
} }
+54
View File
@@ -0,0 +1,54 @@
import { useState, useEffect } from 'react';
/**
* Generic hook for managing localStorage state
*/
export function useLocalStorage<T>(
key: string,
defaultValue: T,
serializer?: {
serialize: (value: T) => string;
deserialize: (value: string) => T;
}
) {
const serialize = serializer?.serialize || JSON.stringify;
const deserialize = serializer?.deserialize || JSON.parse;
const [state, setState] = useState<T>(() => {
try {
const item = localStorage.getItem(key);
return item ? deserialize(item) : defaultValue;
} catch (error) {
console.warn(`Failed to load ${key} from localStorage:`, error);
return defaultValue;
}
});
const setValue = (value: T | ((prev: T) => T)) => {
try {
const valueToStore = value instanceof Function ? value(state) : value;
setState(valueToStore);
localStorage.setItem(key, serialize(valueToStore));
} catch (error) {
console.warn(`Failed to save ${key} to localStorage:`, error);
}
};
// Sync with localStorage changes from other tabs
useEffect(() => {
const handleStorageChange = (e: StorageEvent) => {
if (e.key === key && e.newValue !== null) {
try {
setState(deserialize(e.newValue));
} catch (error) {
console.warn(`Failed to sync ${key} from localStorage:`, error);
}
}
};
window.addEventListener('storage', handleStorageChange);
return () => window.removeEventListener('storage', handleStorageChange);
}, [key, deserialize]);
return [state, setValue] as const;
}
+6
View File
@@ -0,0 +1,6 @@
// This file exists because LLMs get confused and try to create this file if it doesn't exist.
// The `useNostr` hook should be imported directly from `@nostrify/react`, not from this file.
// This file SHOULD NOT be edited or removed.
export { useNostr } from "@nostrify/react";
+14 -10
View File
@@ -1,29 +1,33 @@
import { useNostr } from "@nostrify/react"; import { useNostr } from "@nostrify/react";
import { useMutation } from "@tanstack/react-query"; import { useMutation, type UseMutationResult } from "@tanstack/react-query";
import { useCurrentUser } from "./useCurrentUser"; import { useCurrentUser } from "./useCurrentUser";
interface EventTemplate { import type { NostrEvent } from "@nostrify/nostrify";
kind: number;
content?: string;
tags?: string[][];
created_at?: number;
}
export function useNostrPublish() { export function useNostrPublish(): UseMutationResult<NostrEvent> {
const { nostr } = useNostr(); const { nostr } = useNostr();
const { user } = useCurrentUser(); const { user } = useCurrentUser();
return useMutation({ return useMutation({
mutationFn: async (t: EventTemplate) => { mutationFn: async (t: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>) => {
if (user) { if (user) {
const tags = t.tags ?? [];
// Add the client tag if it doesn't exist
if (location.protocol === "https:" && !tags.some(([name]) => name === "client")) {
tags.push(["client", location.hostname]);
}
const event = await user.signer.signEvent({ const event = await user.signer.signEvent({
kind: t.kind, kind: t.kind,
content: t.content ?? "", content: t.content ?? "",
tags: t.tags ?? [], tags,
created_at: t.created_at ?? Math.floor(Date.now() / 1000), created_at: t.created_at ?? Math.floor(Date.now() / 1000),
}); });
await nostr.event(event, { signal: AbortSignal.timeout(5000) }); await nostr.event(event, { signal: AbortSignal.timeout(5000) });
return event;
} else { } else {
throw new Error("User is not logged in"); throw new Error("User is not logged in");
} }
+20
View File
@@ -0,0 +1,20 @@
import { type Theme } from "@/contexts/AppContext";
import { useAppContext } from "@/hooks/useAppContext";
/**
* Hook to get and set the active theme
* @returns Theme context with theme and setTheme
*/
export function useTheme(): { theme: Theme; setTheme: (theme: Theme) => void } {
const { config, updateConfig } = useAppContext();
return {
theme: config.theme,
setTheme: (theme: Theme) => {
updateConfig((currentConfig) => ({
...currentConfig,
theme,
}));
}
}
}
+4 -13
View File
@@ -15,13 +15,6 @@ type ToasterToast = ToastProps & {
action?: ToastActionElement action?: ToastActionElement
} }
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0 let count = 0
function genId() { function genId() {
@@ -29,23 +22,21 @@ function genId() {
return count.toString() return count.toString()
} }
type ActionType = typeof actionTypes
type Action = type Action =
| { | {
type: ActionType["ADD_TOAST"] type: "ADD_TOAST";
toast: ToasterToast toast: ToasterToast
} }
| { | {
type: ActionType["UPDATE_TOAST"] type: "UPDATE_TOAST";
toast: Partial<ToasterToast> toast: Partial<ToasterToast>
} }
| { | {
type: ActionType["DISMISS_TOAST"] type: "DISMISS_TOAST";
toastId?: ToasterToast["id"] toastId?: ToasterToast["id"]
} }
| { | {
type: ActionType["REMOVE_TOAST"] type: "REMOVE_TOAST";
toastId?: ToasterToast["id"] toastId?: ToasterToast["id"]
} }
+26
View File
@@ -0,0 +1,26 @@
import { useMutation } from "@tanstack/react-query";
import { BlossomUploader } from '@nostrify/nostrify/uploaders';
import { useCurrentUser } from "./useCurrentUser";
export function useUploadFile() {
const { user } = useCurrentUser();
return useMutation({
mutationFn: async (file: File) => {
if (!user) {
throw new Error('Must be logged in to upload files');
}
const uploader = new BlossomUploader({
servers: [
'https://blossom.primal.net/',
],
signer: user.signer,
});
const tags = await uploader.upload(file);
return tags;
},
});
}
+33
View File
@@ -0,0 +1,33 @@
import { describe, it, expect } from 'vitest';
import { genUserName } from './genUserName';
describe('genUserName', () => {
it('generates a deterministic name from a seed', () => {
const seed = 'test-seed-123';
const name1 = genUserName(seed);
const name2 = genUserName(seed);
expect(name1).toEqual('Brave Whale');
expect(name1).toEqual(name2);
});
it('generates different names for different seeds', () => {
const name1 = genUserName('seed1');
const name2 = genUserName('seed2');
const name3 = genUserName('seed3');
// While it's theoretically possible for different seeds to generate the same name,
// it's very unlikely with our word lists
expect(name1).not.toBe(name2);
expect(name2).not.toBe(name3);
expect(name1).not.toBe(name3);
});
it('handles typical Nostr pubkey format', () => {
// Typical hex pubkey (64 characters)
const pubkey = 'e4690a13290739da123aa17d553851dec4cdd0e9d89aa18de3741c446caf8761';
const name = genUserName(pubkey);
expect(name).toEqual('Gentle Hawk');
});
});
+29
View File
@@ -0,0 +1,29 @@
/** Generate a deterministic user display name based on a string seed. */
export function genUserName(seed: string): string {
// Use a simple hash of the pubkey to generate consistent adjective + noun combinations
const adjectives = [
'Swift', 'Bright', 'Calm', 'Bold', 'Wise', 'Kind', 'Quick', 'Brave',
'Cool', 'Sharp', 'Clear', 'Strong', 'Smart', 'Fast', 'Keen', 'Pure',
'Noble', 'Gentle', 'Fierce', 'Steady', 'Clever', 'Proud', 'Silent', 'Wild'
];
const nouns = [
'Fox', 'Eagle', 'Wolf', 'Bear', 'Lion', 'Tiger', 'Hawk', 'Owl',
'Deer', 'Raven', 'Falcon', 'Lynx', 'Otter', 'Whale', 'Shark', 'Dolphin',
'Phoenix', 'Dragon', 'Panther', 'Jaguar', 'Cheetah', 'Leopard', 'Puma', 'Cobra'
];
// Create a simple hash from the pubkey
let hash = 0;
for (let i = 0; i < seed.length; i++) {
const char = seed.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32-bit integer
}
// Use absolute value to ensure positive index
const adjIndex = Math.abs(hash) % adjectives.length;
const nounIndex = Math.abs(hash >> 8) % nouns.length;
return [adjectives[adjIndex], nouns[nounIndex]].join(' ');
}
+78
View File
@@ -0,0 +1,78 @@
/**
* Polyfill for AbortSignal.any()
*
* AbortSignal.any() creates an AbortSignal that will be aborted when any of the
* provided signals are aborted. This is useful for combining multiple abort signals.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static
*/
// Check if AbortSignal.any is already available
if (!AbortSignal.any) {
AbortSignal.any = function(signals: AbortSignal[]): AbortSignal {
// If no signals provided, return a signal that never aborts
if (signals.length === 0) {
return new AbortController().signal;
}
// If only one signal, return it directly for efficiency
if (signals.length === 1) {
return signals[0];
}
// Check if any signal is already aborted
for (const signal of signals) {
if (signal.aborted) {
// Create an already-aborted signal with the same reason
const controller = new AbortController();
controller.abort(signal.reason);
return controller.signal;
}
}
// Create a new controller for the combined signal
const controller = new AbortController();
// Function to abort the combined signal
const onAbort = (event: Event) => {
const target = event.target as AbortSignal;
controller.abort(target.reason);
};
// Listen for abort events on all input signals
for (const signal of signals) {
signal.addEventListener('abort', onAbort, { once: true });
}
// Clean up listeners when the combined signal is aborted
controller.signal.addEventListener('abort', () => {
for (const signal of signals) {
signal.removeEventListener('abort', onAbort);
}
}, { once: true });
return controller.signal;
};
}
/**
* Polyfill for AbortSignal.timeout()
*
* AbortSignal.timeout() creates an AbortSignal that will be aborted after a
* specified number of milliseconds.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static
*/
// Check if AbortSignal.timeout is already available
if (!AbortSignal.timeout) {
AbortSignal.timeout = function(milliseconds: number): AbortSignal {
const controller = new AbortController();
setTimeout(() => {
controller.abort(new DOMException('The operation was aborted due to timeout', 'TimeoutError'));
}, milliseconds);
return controller.signal;
};
}
+9 -3
View File
@@ -1,6 +1,12 @@
import { createRoot } from 'react-dom/client' import { createRoot } from 'react-dom/client';
import App from './App.tsx' // Import polyfills first
import './index.css' import './lib/polyfills.ts';
import App from './App.tsx';
import './index.css';
// FIXME: a custom font should be used. Eg:
// import '@fontsource-variable/<font-name>';
createRoot(document.getElementById("root")!).render(<App />); createRoot(document.getElementById("root")!).render(<App />);
+15 -4
View File
@@ -1,11 +1,22 @@
// Update this page (the content is just a fallback if you fail to update the page) import { useSeoMeta } from '@unhead/react';
// FIXME: Update this page (the content is just a fallback if you fail to update the page)
const Index = () => { const Index = () => {
useSeoMeta({
title: 'Welcome to Your Blank App',
description: 'A modern Nostr client application built with React, TailwindCSS, and Nostrify.',
});
return ( return (
<div className="min-h-screen flex items-center justify-center bg-gray-100"> <div className="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-900">
<div className="text-center"> <div className="text-center">
<h1 className="text-4xl font-bold mb-4">Welcome to Your Blank App</h1> <h1 className="text-4xl font-bold mb-4 text-gray-900 dark:text-gray-100">
<p className="text-xl text-gray-600">Start building your amazing project here!</p> Welcome to Your Blank App
</h1>
<p className="text-xl text-gray-600 dark:text-gray-400">
Start building your amazing project here!
</p>
</div> </div>
</div> </div>
); );
+10 -4
View File
@@ -1,9 +1,15 @@
import { useSeoMeta } from "@unhead/react";
import { useLocation } from "react-router-dom"; import { useLocation } from "react-router-dom";
import { useEffect } from "react"; import { useEffect } from "react";
const NotFound = () => { const NotFound = () => {
const location = useLocation(); const location = useLocation();
useSeoMeta({
title: "404 - Page Not Found",
description: "The page you are looking for could not be found. Return to the home page to continue browsing.",
});
useEffect(() => { useEffect(() => {
console.error( console.error(
"404 Error: User attempted to access non-existent route:", "404 Error: User attempted to access non-existent route:",
@@ -12,11 +18,11 @@ const NotFound = () => {
}, [location.pathname]); }, [location.pathname]);
return ( return (
<div className="min-h-screen flex items-center justify-center bg-gray-100"> <div className="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-900">
<div className="text-center"> <div className="text-center">
<h1 className="text-4xl font-bold mb-4">404</h1> <h1 className="text-4xl font-bold mb-4 text-gray-900 dark:text-gray-100">404</h1>
<p className="text-xl text-gray-600 mb-4">Oops! Page not found</p> <p className="text-xl text-gray-600 dark:text-gray-400 mb-4">Oops! Page not found</p>
<a href="/" className="text-blue-500 hover:text-blue-700 underline"> <a href="/" className="text-blue-500 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 underline">
Return to Home Return to Home
</a> </a>
</div> </div>
+45
View File
@@ -0,0 +1,45 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createHead, UnheadProvider } from '@unhead/react/client';
import { BrowserRouter } from 'react-router-dom';
import { NostrLoginProvider } from '@nostrify/react/login';
import NostrProvider from '@/components/NostrProvider';
import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
interface TestAppProps {
children: React.ReactNode;
}
export function TestApp({ children }: TestAppProps) {
const head = createHead();
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
});
const defaultConfig: AppConfig = {
theme: 'light',
relayUrl: 'wss://relay.nostr.band',
};
return (
<UnheadProvider head={head}>
<AppProvider storageKey='test-app-config' defaultConfig={defaultConfig}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='test-login'>
<NostrProvider>
<BrowserRouter>
{children}
</BrowserRouter>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
</AppProvider>
</UnheadProvider>
);
}
export default TestApp;
+40
View File
@@ -0,0 +1,40 @@
import '@testing-library/jest-dom';
import { vi } from 'vitest';
// Mock window.matchMedia
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(), // deprecated
removeListener: vi.fn(), // deprecated
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
// Mock window.scrollTo
Object.defineProperty(window, 'scrollTo', {
writable: true,
value: vi.fn(),
});
// Mock IntersectionObserver
global.IntersectionObserver = vi.fn().mockImplementation((_callback) => ({
observe: vi.fn(),
unobserve: vi.fn(),
disconnect: vi.fn(),
root: null,
rootMargin: '',
thresholds: [],
}));
// Mock ResizeObserver
global.ResizeObserver = vi.fn().mockImplementation((_callback) => ({
observe: vi.fn(),
unobserve: vi.fn(),
disconnect: vi.fn(),
}));
+19
View File
@@ -0,0 +1,19 @@
{
"name": "mkstack",
"title": "MKStack",
"description": "Build Nostr apps in minutes with this React framework",
"uri": "git+https://gitlab.com/soapbox-pub/mkstack.git",
"image": "https://gitlab.com/-/project/69048882/uploads/0a9e3a19f2901d5c772952c1de10ce4f/image.png",
"commands": [
"npm",
"npx"
],
"tech": [
"react",
"typescript",
"tailwind",
"shadcn-ui",
"nostrify",
"vite"
]
}
+2 -1
View File
@@ -1,4 +1,5 @@
import type { Config } from "tailwindcss"; import type { Config } from "tailwindcss";
import tailwindcssAnimate from "tailwindcss-animate";
export default { export default {
darkMode: ["class"], darkMode: ["class"],
@@ -92,5 +93,5 @@ export default {
} }
} }
}, },
plugins: [require("tailwindcss-animate")], plugins: [tailwindcssAnimate],
} satisfies Config; } satisfies Config;
+15 -4
View File
@@ -1,17 +1,28 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import path from "node:path"; import path from "node:path";
import react from "@vitejs/plugin-react-swc";
import { defineConfig } from "vitest/config";
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig(() => ({ export default defineConfig(() => ({
server: { server: {
host: "::", host: "::",
port: 8080, port: 8080,
}, },
plugins: [react()], plugins: [
react(),
],
test: {
globals: true,
environment: 'jsdom',
setupFiles: './src/test/setup.ts',
onConsoleLog(log) {
return !log.includes("React Router Future Flag Warning");
},
},
resolve: { resolve: {
alias: { alias: {
"@": path.resolve(__dirname, "./src"), "@": path.resolve(__dirname, "./src"),
}, },
}, },
})); }));