Author SHA1 Message Date
lemonknowsall 4c21a4147c added push notification hook 2025-09-22 21:01:06 -07:00
Alex Gleason be71f350fc Remove bg-background from "outline" button variant 2025-09-20 11:20:44 -05:00
Alex Gleason 03578ab05d Add information about connecting to multiple relays 2025-09-15 20:27:51 -05:00
Alex Gleason a26a755505 Give useIsMobile an initial state 2025-09-13 18:35:08 -05:00
Alex Gleason 849693416a Add git commit requirement to validation process
- Include creating a git commit as step 5 in validation priority order
- Add git commit to minimum requirements for completing changes
- Ensures work is properly saved after validation
2025-09-11 22:12:20 -05:00
Alex Gleason 58322d237e vitest dot reporter 2025-09-08 15:24:51 -05:00
Alex Gleason 976164b480 Minimize build and test output 2025-09-08 14:49:10 -05:00
Alex Gleason 36756f56a9 Remove non-standard context files 2025-09-08 13:46:10 -05:00
Alex Gleason 3701c14c37 AGENTS.md: make "validating your changes" more flexible to different environments 2025-09-08 13:44:59 -05:00
Alex Gleason 33614b1ddd Add improved README 2025-09-08 12:15:01 -05:00
Alex Gleason ca9c88b5ea AGENTS.md: generalize tool names 2025-09-08 03:22:35 -05:00
Alex Gleason 95881bb09f Merge branch 'simplify-tsconfig' into 'main'
Simplify tsconfig

See merge request soapbox-pub/mkstack!18
2025-09-03 01:37:50 +00:00
Alex Gleason ba1a7871a0 Simplify tsconfig 2025-09-02 20:17:44 -05:00
Chad Curtis a98151688d Fix linter 2025-09-02 16:23:14 +00:00
Chad Curtis d1744b7d71 Merge branch 'infiniteScroll' into 'main'
Add context for pagination (i.e., infinite feed scroll)

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

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

See merge request soapbox-pub/mkstack!11
2025-07-26 00:12:25 +00:00
Chad Curtis 0c039bfbcf revert gitlab-ci to upstream version for now 2025-07-26 00:09:58 +00:00
Chad Curtis 36237fd5b6 attempt to isolate gitlab logic to mainline mkstack 2025-07-25 23:51:13 +00:00
Chad Curtis 1de668785f CONTEXT update per review feedback 2025-07-25 23:47:46 +00:00
Chad Curtis c231ee40ac Merge branch 'main' of gitlab.com:soapbox-pub/mkstack into zapSupport 2025-07-25 23:45:15 +00:00
Alex Gleason fbbf7f8c39 npm audit fix 2025-07-23 16:30:18 -05:00
Chad Curtis 23508f361b clean up mobile drawer height fix 2025-07-17 23:37:19 +00:00
Chad Curtis 612aacb00b Merge branch 'main' of gitlab.com:soapbox-pub/mkstack into zapSupport 2025-07-17 22:38:39 +00:00
Chad Curtis 21540d251f reduce unused functions, consolidate uri check 2025-07-14 15:20:34 +00:00
Chad Curtis 97a493c218 fix redraw issue for wallet configuration 2025-07-14 14:21:57 +00:00
Chad Curtis 6845e6cf7c Fallback to manual payment if webln fails - might be due to user intentionally closing out of it v2 2025-07-14 13:50:22 +00:00
Chad Curtis 3101532a2b Fallback to manual payment if webln fails - might be due to user intentionally closing out of it 2025-07-14 13:50:02 +00:00
Chad Curtis 7c9f3cb797 functional fix for drawer height bug on mobile 2025-07-14 13:01:49 +00:00
Chad Curtis 4c129251c7 more potential mobile sizing fixes for vh 2025-07-14 07:44:12 +00:00
Chad Curtis 0484b10a96 fix state issue which resulted in text edits causing repeated focus loss 2025-07-14 07:23:33 +00:00
Chad Curtis 230183bd0c more mobile fixes 2025-07-14 07:09:15 +00:00
Chad Curtis a92f80b6e3 small styling fixes + fix potential memory leaks 2025-07-14 06:27:29 +00:00
Chad Curtis a51094e157 update gitlab ci to expect template failures in the default state 2025-07-14 04:04:50 +00:00
Chad Curtis ab54efba47 merge in from upstream and resolve conflicts 2025-07-14 03:58:49 +00:00
Chad Curtis 0a2474d2f5 mobile enhancements 2025-07-14 03:06:17 +00:00
Chad Curtis 661a5e1eac shorten empty state text to one line 2025-07-14 02:23:20 +00:00
Chad Curtis 9d8b5a3f43 another set of context + zap button fixes 2025-07-14 02:11:23 +00:00
Chad Curtis 8f51db5a49 nwc icon change + context fix 2025-07-14 02:01:30 +00:00
Chad Curtis c98a6bbf64 scrollable manual zap, handle undef target 2025-07-14 01:51:48 +00:00
Chad Curtis 9ed8676d17 context updae + app nwccontext 2025-07-14 01:40:04 +00:00
Chad Curtis 8183e3cc5a cleanup + shakespeare-like manual zap modal 2025-07-14 01:16:31 +00:00
Chad Curtis 0bc03017bb further refinement 2025-07-14 01:03:04 +00:00
Chad Curtis 7eecec7506 tidying 2025-07-13 20:12:42 +00:00
Chad Curtis 8c34dbc8d5 further refinement for new app builds 2025-07-13 19:52:58 +00:00
Chad Curtis 45ff37e752 messy, nwc support +_wallet fixes 2025-07-13 17:53:30 +00:00
Chad Curtis 11ac73776c zap in context.md 2025-07-13 06:51:24 +00:00
Chad Curtis 14eccbcb6f wallet configuration settings + nwc baseline support 2025-07-13 06:47:45 +00:00
Chad Curtis 55bf545646 cleanup + icons 2025-07-13 05:59:56 +00:00
Chad Curtis ec1a9777de use event directly 2025-07-13 04:09:32 +00:00
Chad Curtis 7fdcb658b3 use single zaps component 2025-07-12 19:23:50 +00:00
Chad Curtis c37df875b9 user fix 2025-07-12 19:20:34 +00:00
Chad Curtis d68f2d8486 minimal zap support 2025-07-12 19:19:41 +00:00
34 changed files with 3230 additions and 567 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
CONTEXT.md
-1
View File
@@ -1 +0,0 @@
../CONTEXT.md
+1
View File
@@ -11,6 +11,7 @@ node_modules
dist
dist-ssr
*.local
.ai/
# Editor directories and files
.idea
-1
View File
@@ -1 +0,0 @@
CONTEXT.md
-16
View File
@@ -1,16 +0,0 @@
# jsr registry should not be edited or removed
.npmrc
# vite client types are needed
src/vite-env.d.ts
# tsconfig is stable and working correctly, so should not be edited
tsconfig.json
tsconfig.app.json
tsconfig.node.json
# postcss config for Tailwind is stable and working correctly, so should not be edited unless upgrading Tailwind to v4
postcss.config.js
# vite config is stable and usually should not need to be edited
vite.config.ts
+6 -1
View File
@@ -1,9 +1,14 @@
{
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "xjsr", "@nostrbook/mcp"]
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
+6 -1
View File
@@ -1,9 +1,14 @@
{
"servers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "xjsr", "@nostrbook/mcp"]
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
+228 -20
View File
@@ -18,6 +18,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `/src/components/`: UI components including NostrProvider for Nostr integration
- `/src/components/ui/`: shadcn/ui components (48+ components available)
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
- `useAuthor`: Fetch user profile data by pubkey
@@ -31,9 +32,14 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useLoggedInAccounts`: Manage multiple accounts
- `useLoginActions`: Authentication actions
- `useIsMobile`: Responsive design helper
- `useZaps`: Lightning zap functionality with payment processing
- `useWallet`: Unified wallet detection (WebLN + NWC)
- `useNWC`: Nostr Wallet Connect connection management
- `useNWCContext`: Access NWC context provider
- `usePush`: Push notifications via Nostr RPC
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
- `/src/contexts/`: React context providers (AppContext)
- `/src/contexts/`: React context providers (AppContext, NWCContext)
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
@@ -81,7 +87,6 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
- **Sidebar**: Navigation sidebar component
- **Skeleton**: Loading placeholder
- **Slider**: Input for selecting a value from a range
- **Sonner**: Toast notification manager
- **Switch**: Toggle switch control
- **Table**: Data table with headers and rows
- **Tabs**: Tabbed interface component
@@ -95,9 +100,9 @@ These components follow a consistent pattern using React's `forwardRef` and use
## 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:
The AI assistant's behavior and knowledge is defined by the AGENTS.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
1. Edit AGENTS.md directly
2. The changes take effect in the next session
## "Vibed with MKStack"
@@ -110,9 +115,9 @@ This project comes with custom hooks for querying and publishing events on the N
### 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.
- Always check the full list of existing NIPs 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, read the relevant NIPs to investigate thoroughly. Several NIPs may need to be read before making a decision.
- Only generate new kind numbers 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.
@@ -120,7 +125,7 @@ Knowing when to create a new kind versus reusing an existing kind requires caref
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.
1. **Thorough NIP Review**: Before considering a new kind, always perform a comprehensive review of existing NIPs and their associated kinds. Get an overview of all NIPs, and then read specific NIPs and kind documentation 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.
@@ -138,7 +143,7 @@ When implementing features that could use existing NIPs, follow this decision fr
- The data structure is fundamentally different from existing patterns
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
6. **Custom Kind Publishing**: When publishing events with custom kinds generated by `nostr__generate_kind`, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
6. **Custom Kind Publishing**: When publishing events with custom generated kinds, always include a NIP-31 "alt" tag with a human-readable description of the event's purpose.
**Example Decision Process**:
```
@@ -277,6 +282,85 @@ function useCustomHook() {
}
```
### Connecting to Multiple Nostr Relays
By default, the `nostr` object from `useNostr` uses a pool configuration that reads data from 1 relay and publishes to all configured relays. However, you can connect to specific relays or groups of relays for more granular control:
#### Single Relay Connection
To read and publish from one specific relay, use `nostr.relay()` with a WebSocket URL:
```typescript
import { useNostr } from '@nostrify/react';
function useSpecificRelay() {
const { nostr } = useNostr();
// Connect to a specific relay
const relay = nostr.relay('wss://relay.damus.io');
// Query from this specific relay only
const events = await relay.query([{ kinds: [1], limit: 20 }], { signal });
// Publish to this specific relay only
await relay.event({ kind: 1, content: 'Hello from specific relay!' });
}
```
#### Multiple Relay Group
To read and publish from a specific set of relays, use `nostr.group()` with an array of relay URLs:
```typescript
import { useNostr } from '@nostrify/react';
function useRelayGroup() {
const { nostr } = useNostr();
// Create a group of specific relays
const relayGroup = nostr.group([
'wss://relay.damus.io',
'wss://relay.nostr.band',
'wss://nos.lol'
]);
// Query from all relays in the group
const events = await relayGroup.query([{ kinds: [1], limit: 20 }], { signal });
// Publish to all relays in the group
await relayGroup.event({ kind: 1, content: 'Hello from relay group!' });
}
```
#### API Consistency
Both `relay` and `group` objects have the same API as the main `nostr` object, including:
- `.query()` - Query events with filters
- `.req()` - Create subscriptions
- `.event()` - Publish events
- All other Nostr protocol methods
#### Use Cases
**Single Relay (`nostr.relay()`):**
- Testing specific relay behavior
- Querying relay-specific content
- Debugging connectivity issues
- Working with specialized relays
**Relay Group (`nostr.group()`):**
- Querying from trusted relay sets
- Publishing to specific communities
- Load balancing across relay subsets
- Geographic relay optimization
**Default Pool (`nostr`):**
- General application queries
- Maximum reach for publishing
- Default user experience
- Simplified relay management
### Query Nostr Data with `useNostr` and Tanstack Query
When querying Nostr, the best practice is to create custom hooks that combine `useNostr` and `useQuery` to get the required data.
@@ -299,6 +383,70 @@ function usePosts() {
}
```
### Infinite Scroll for Feeds
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
```typescript
import { useNostr } from '@nostrify/react';
import { useInfiniteQuery } from '@tanstack/react-query';
export function useGlobalFeed() {
const { nostr } = useNostr();
return useInfiniteQuery({
queryKey: ['global-feed'],
queryFn: async ({ pageParam, signal }) => {
const filter = { kinds: [1], limit: 20 };
if (pageParam) filter.until = pageParam;
const events = await nostr.query([filter], {
signal: AbortSignal.any([signal, AbortSignal.timeout(1500)])
});
return events;
},
getNextPageParam: (lastPage) => {
if (lastPage.length === 0) return undefined;
return lastPage[lastPage.length - 1].created_at - 1; // Subtract 1 since 'until' is inclusive
},
initialPageParam: undefined,
});
}
```
Example usage with intersection observer for automatic loading:
```tsx
import { useInView } from 'react-intersection-observer';
function GlobalFeed() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
const { ref, inView } = useInView();
useEffect(() => {
if (inView && hasNextPage) {
fetchNextPage();
}
}, [inView, hasNextPage, fetchNextPage]);
const posts = data?.pages.flat() || [];
return (
<div className="space-y-4">
{posts.map((post) => (
<PostCard key={post.id} post={post} />
))}
{hasNextPage && (
<div ref={ref} className="py-4">
{isFetchingNextPage && <Skeleton className="h-20 w-full" />}
</div>
)}
</div>
);
}
```
#### Efficient Query Design
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
@@ -494,6 +642,8 @@ The `LoginArea` component handles all the login-related UI and interactions, inc
`LoginArea` displays both "Log in" and "Sign Up" buttons 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.
**Important**: Social applications should include a profile menu button in the main interface (typically in headers/navigation) to provide access to account settings, profile editing, and logout functionality. Don't only show `LoginArea` in logged-out states.
### `npub`, `naddr`, and other Nostr addresses
Nostr defines a set of bech32-encoded identifiers in NIP-19. Their prefixes and purposes:
@@ -693,6 +843,48 @@ const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
```
### Push Notifications
The project includes `usePush` hook for managing push notifications via Nostr RPC. This enables users to receive browser notifications for Nostr events.
#### Basic Usage
```tsx
import { usePush } from '@/hooks/usePush';
function NotificationButton({ authorPubkey }: { authorPubkey: string }) {
const { subscribeToAuthor, isLoading, error } = usePush();
const handleEnableNotifications = async () => {
try {
await subscribeToAuthor(authorPubkey);
} catch (error) {
console.error('Failed to enable notifications:', error);
}
};
return (
<Button onClick={handleEnableNotifications} disabled={isLoading}>
{isLoading ? 'Enabling...' : 'Enable Notifications'}
</Button>
);
}
```
#### Available Methods
- **`subscribeToAuthor`**: Get notifications for new posts from a specific user
- **`subscribeToMentions`**: Get notifications when mentioned in posts
- **`subscribeToHashtag`**: Get notifications for posts with specific hashtags
- **`registerSubscription`**: Create custom notification subscriptions
- **`deleteSubscription`**: Remove notification subscriptions
#### Requirements
- User must be logged in with NIP-44 encryption support
- Browser must support push notifications
- VAPID public key is included by default
### 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:
@@ -868,14 +1060,14 @@ import { Card, CardContent } from '@/components/ui/card';
To add custom fonts, follow these steps:
1. **Install a font package** using the `js-dev__npm_add_package` tool:
1. **Install a font package** using npm:
**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" })`
- For Inter Variable: `@fontsource-variable/inter`
- For Roboto: `@fontsource/roboto`
- For Outfit Variable: `@fontsource-variable/outfit`
- For Poppins: `@fontsource/poppins`
- For Open Sans: `@fontsource/open-sans`
**Format**: `@fontsource/[font-name]` or `@fontsource-variable/[font-name]` (for variable fonts)
@@ -948,7 +1140,7 @@ There is an important distinction between **writing new tests** and **running ex
### Running Tests (Executing the Test Suite)
**ALWAYS run the test script** after making any code changes. This is mandatory regardless of whether you wrote new tests or not.
- **You must run the test script** using `js-dev__run_script` tool with the "test" parameter
- **You must run the test script** to validate your changes
- **Your task is not complete** until the test script passes without errors
- **This applies to all changes** - bug fixes, new features, refactoring, or any code modifications
- **The test script includes** TypeScript compilation, ESLint checks, and existing test validation
@@ -982,10 +1174,26 @@ describe('MyComponent', () => {
});
```
## Testing Your Changes
## Validating Your Changes
**CRITICAL**: Whenever you are finished modifying code, you must run the **test** script using the **js-dev__run_script** tool.
**CRITICAL**: After making any code changes, you must validate your work by running available validation tools.
**Your task is not considered finished until this test passes without errors.**
**Your task is not considered finished until the code successfully type-checks and builds without errors.**
**This requirement applies regardless of whether you wrote new tests or not.** The test script validates the entire codebase, including TypeScript compilation, ESLint rules, and existing test suite.
### Validation Priority Order
Run available tools in this priority order:
1. **Type Checking** (Required): Ensure TypeScript compilation succeeds
2. **Building/Compilation** (Required): Verify the project builds successfully
3. **Linting** (Recommended): Check code style and catch potential issues
4. **Tests** (If Available): Run existing test suite
5. **Git Commit** (Required): Create a commit with your changes when finished
**Minimum Requirements:**
- Code must type-check without errors
- Code must build/compile successfully
- Fix any critical linting errors that would break functionality
- Create a git commit when your changes are complete
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
-1
View File
@@ -1 +0,0 @@
CONTEXT.md
-1
View File
@@ -1 +0,0 @@
CONTEXT.md
+236 -1
View File
@@ -1,3 +1,238 @@
# MKStack
Template for building Nostr client application with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify.
**The Complete Framework for Building Nostr Clients with AI**
MKStack is an AI-powered framework for building Nostr applications with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify. Build powerful Nostr applications with AI-first development - from social feeds to private messaging, MKStack provides everything you need to create decentralized apps on the Nostr protocol.
## 🚀 Quick Start
Build your Nostr app in 3 simple steps:
### 1. Install & Create
```bash
npm install -g @getstacks/stacks
stacks mkstack
```
### 2. Build with AI
```bash
stacks agent
# Tell Dork AI what you want: "Build a group chat application"
```
### 3. Deploy Instantly
```bash
npm run deploy
# ✅ App deployed to NostrDeploy.com!
```
## ✨ What Makes MKStack Special
- **🤖 AI-First Development**: Build complete Nostr apps with just one prompt using Dork AI agent
- **⚡ 8 Minutes Average**: From idea to deployed application in minutes, not months
- **🔗 50+ NIPs Supported**: Comprehensive Nostr protocol implementation
- **🎨 Beautiful UI**: 48+ shadcn/ui components with light/dark theme support
- **🔐 Built-in Security**: NIP-07 browser signing, NIP-44 encryption, event validation
- **💰 Payments Ready**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Wallet Connect (NIP-47)
- **📱 Production Ready**: TypeScript, testing, deployment, and responsive design included
## 🛠 Technology Stack
- **React 18.x**: Stable version with hooks, concurrent rendering, and improved performance
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
- **Vite**: Fast build tool and development server
- **shadcn/ui**: 48+ unstyled, accessible UI components built with Radix UI
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: Client-side routing with BrowserRouter
- **TanStack Query**: Data fetching, caching, and state management
- **TypeScript**: Type-safe JavaScript development
## 🎯 Real-World Examples
### Built with One Prompt
Each of these applications was created with just a single prompt to Dork AI:
- **Group Chat Application**: `"Build me a group chat application"`
- [Live Demo](https://groupchat-74z9j26wq-mks-projects-1f1254c4.vercel.app/)
- **Decentralized Goodreads**: `"Build a decentralized goodreads alternative. Use OpenLibrary API for book data."`
- [Live Demo](https://bookstr123-87phkwjcy-mks-projects-1f1254c4.vercel.app/)
- **Chess Game**: `"Build a chess game with NIP 64"`
- [Live Demo](https://chess-l0d7ms7m3-mks-projects-1f1254c4.vercel.app/chess)
### Production Apps
Real Nostr applications built using MKStack:
- **[Chorus](https://chorus.community/)**: Facebook-style groups on Nostr with built-in eCash wallet
- **[Blobbi](https://www.blobbi.pet/)**: Digital pet companions that live forever on the decentralized web
- **[Treasures](https://treasures.to/)**: Decentralized geocaching adventure powered by Nostr
[Browse more apps made with MKStack →](https://nostrhub.io/apps/t/mkstack/)
## 🔧 Core Features
### Authentication & Users
- `LoginArea` component with account switching
- `useCurrentUser` hook for authentication state
- `useAuthor` hook for fetching user profiles
- NIP-07 browser signing support
- Multi-account management
### Nostr Protocol Support
- **Social Features**: User profiles (NIP-01), follow lists (NIP-02), reactions (NIP-25), reposts (NIP-18)
- **Messaging**: Private DMs (NIP-17), public chat (NIP-28), group chat (NIP-29), encryption (NIP-44)
- **Payments**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Nutzaps (NIP-61), Wallet Connect (NIP-47)
- **Content**: Long-form articles (NIP-23), file metadata (NIP-94), live events (NIP-53), calendars (NIP-52)
### Data Management
- `useNostr` hook for querying and publishing
- `useNostrPublish` hook with automatic client tagging
- Event validation and filtering
- Infinite scroll with TanStack Query
- Multi-relay support
### UI Components
- 48+ shadcn/ui components (buttons, forms, dialogs, etc.)
- `NoteContent` component for rich text rendering
- `EditProfileForm` for profile management
- `RelaySelector` for relay switching
- `CommentsSection` for threaded discussions
- Light/dark theme system
### Media & Files
- `useUploadFile` hook with Blossom server integration
- NIP-94 compatible file metadata
- Image and video support
- File attachment to events
### Advanced Features
- NIP-19 identifier routing (`npub1`, `note1`, `nevent1`, `naddr1`)
- Cryptographic operations (encryption/decryption)
- Lightning payments and zaps
- Real-time event subscriptions
- Responsive design with mobile support
## 🤖 AI Development with Dork
MKStack includes Dork, a built-in AI agent that understands your codebase and Nostr protocols:
### Supported AI Providers
Configure your AI provider with `stacks configure`:
- **OpenRouter** ([openrouter.ai](https://openrouter.ai/)): Enter your API key from settings
- **Routstr** ([routstr.com](https://www.routstr.com/)): Use Cashu tokens for payment
- **PayPerQ** ([ppq.ai](https://ppq.ai/)): OpenAI-compatible API
### How Dork Works
- **Context-Aware**: Understands your entire codebase and project structure
- **Nostr Expert**: Built-in knowledge of 50+ NIPs and best practices
- **Instant Implementation**: Makes changes directly to your code following React/TypeScript best practices
Example prompts:
```bash
"Add user profiles with avatars and bio"
"Implement NIP-17 private messaging"
"Add a dark mode toggle"
"Create a marketplace with NIP-15"
```
## 📁 Project Structure
```
src/
├── components/ # UI components
│ ├── ui/ # shadcn/ui components (48+ available)
│ ├── auth/ # Authentication components
│ └── comments/ # Comment system components
├── hooks/ # Custom React hooks
│ ├── useNostr # Core Nostr integration
│ ├── useAuthor # User profile data
│ ├── useCurrentUser # Authentication state
│ ├── useNostrPublish # Event publishing
│ ├── useUploadFile # File uploads
│ └── useZaps # Lightning payments
├── pages/ # Page components
├── lib/ # Utility functions
├── contexts/ # React context providers
└── test/ # Testing utilities
```
## 🎨 UI Components
MKStack includes 48+ shadcn/ui components:
**Layout**: Card, Separator, Sheet, Sidebar, ScrollArea, Resizable
**Navigation**: Breadcrumb, NavigationMenu, Menubar, Tabs, Pagination
**Forms**: Button, Input, Textarea, Select, Checkbox, RadioGroup, Switch, Slider
**Feedback**: Alert, AlertDialog, Toast, Progress, Skeleton
**Overlay**: Dialog, Popover, HoverCard, Tooltip, ContextMenu, DropdownMenu
**Data Display**: Table, Avatar, Badge, Calendar, Chart, Carousel
**And many more...
## 🔐 Security & Best Practices
- **Never use `any` type**: Always use proper TypeScript types
- **Event validation**: Filter events through validator functions for custom kinds
- **Efficient queries**: Minimize separate queries to avoid rate limiting
- **Proper error handling**: Graceful handling of invalid NIP-19 identifiers
- **Secure authentication**: Use signer interface, never request private keys directly
## 📱 Responsive Design
- Mobile-first approach with Tailwind breakpoints
- `useIsMobile` hook for responsive behavior
- Touch-friendly interactions
- Optimized for all screen sizes
## 🧪 Testing
- Vitest with jsdom environment
- React Testing Library with jest-dom matchers
- `TestApp` component provides all necessary context providers
- Mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
## 🚀 Deployment
Built-in deployment to NostrDeploy.com:
```bash
npm run deploy
```
Your app goes live instantly with:
- Automatic builds
- CDN distribution
- HTTPS support
- Custom domains available
## 📚 Documentation
For detailed documentation on building Nostr applications with MKStack:
- [Tutorial](https://soapbox.pub/blog/mkstack-tutorial)
- [Nostr Protocol Documentation](https://nostr.com)
- [shadcn/ui Components](https://ui.shadcn.com)
## 🤝 Contributing
MKStack is open source and welcomes contributions. The framework is designed to be:
- **Extensible**: Easy to add new NIPs and features
- **Maintainable**: Clean architecture with TypeScript
- **Testable**: Comprehensive testing setup included
- **Documented**: Clear patterns and examples
## 📄 License
Open source - build amazing Nostr applications and help grow the decentralized web!
---
**"Vibed with MKStack"** - [Learn more about MKStack](https://soapbox.pub/mkstack)
*Build your Nostr app in minutes, not months. Start with AI, deploy instantly.*
-16
View File
@@ -1,16 +0,0 @@
{
"model": "claude-sonnet-4",
"temperature": 0.2,
"mcpServers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
-1
View File
@@ -1 +0,0 @@
CONTEXT.md
+456 -296
View File
File diff suppressed because it is too large. Load diff
+9 -5
View File
@@ -4,12 +4,14 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "npm i && vite",
"build": "npm i && vite build && cp dist/index.html dist/404.html",
"test": "npm i && tsc -p tsconfig.app.json --noEmit && eslint && vitest run && vite build",
"dev": "npm i --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
},
"dependencies": {
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
@@ -50,19 +52,20 @@
"embla-carousel-react": "^8.3.0",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"next-themes": "^0.3.0",
"nostr-tools": "^2.13.0",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.0",
"react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2",
"recharts": "^2.12.7",
"sonner": "^1.5.0",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3",
"webln": "^0.3.2",
"zod": "^3.25.71"
},
"devDependencies": {
@@ -73,6 +76,7 @@
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@types/node": "^22.5.5",
"@types/qrcode": "^1.5.5",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react-swc": "^3.5.0",
+9 -8
View File
@@ -7,10 +7,10 @@ import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense } from 'react';
import NostrProvider from '@/components/NostrProvider';
import { Toaster } from "@/components/ui/toaster";
import { Toaster as Sonner } from "@/components/ui/sonner";
import { TooltipProvider } from "@/components/ui/tooltip";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { NWCProvider } from '@/contexts/NWCContext';
import { AppConfig } from '@/contexts/AppContext';
import AppRouter from './AppRouter';
@@ -49,13 +49,14 @@ export function App() {
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<TooltipProvider>
<Toaster />
<Sonner />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
<NWCProvider>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</NWCProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
+395
View File
@@ -0,0 +1,395 @@
import { useState, forwardRef } from 'react';
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
DrawerClose,
} from '@/components/ui/drawer';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { useNWC } from '@/hooks/useNWCContext';
import { useWallet } from '@/hooks/useWallet';
import { useToast } from '@/hooks/useToast';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
interface WalletModalProps {
children?: React.ReactNode;
className?: string;
}
// Extracted AddWalletContent to prevent re-renders
const AddWalletContent = forwardRef<HTMLDivElement, {
alias: string;
setAlias: (value: string) => void;
connectionUri: string;
setConnectionUri: (value: string) => void;
}>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (
<div className="space-y-4 px-4" ref={ref}>
<div>
<Label htmlFor="alias">Wallet Name (optional)</Label>
<Input
id="alias"
placeholder="My Lightning Wallet"
value={alias}
onChange={(e) => setAlias(e.target.value)}
/>
</div>
<div>
<Label htmlFor="connection-uri">Connection URI</Label>
<Textarea
id="connection-uri"
placeholder="nostr+walletconnect://..."
value={connectionUri}
onChange={(e) => setConnectionUri(e.target.value)}
rows={3}
/>
</div>
</div>
));
AddWalletContent.displayName = 'AddWalletContent';
// Extracted WalletContent to prevent re-renders
const WalletContent = forwardRef<HTMLDivElement, {
hasWebLN: boolean;
isDetecting: boolean;
hasNWC: boolean;
connections: NWCConnection[];
connectionInfo: Record<string, NWCInfo>;
activeConnection: string | null;
handleSetActive: (cs: string) => void;
handleRemoveConnection: (cs: string) => void;
setAddDialogOpen: (open: boolean) => void;
}>(({
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen
}, ref) => (
<div className="space-y-6 px-4 pb-4" ref={ref}>
{/* Current Status */}
<div className="space-y-3">
<h3 className="font-medium">Current Status</h3>
<div className="grid gap-3">
{/* WebLN */}
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<Globe className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">WebLN</p>
<p className="text-xs text-muted-foreground">Browser extension</p>
</div>
</div>
<div className="flex items-center gap-2">
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
</Badge>
</div>
</div>
{/* NWC */}
<div className="flex items-center justify-between p-3 border rounded-lg">
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Nostr Wallet Connect</p>
<p className="text-xs text-muted-foreground">
{connections.length > 0
? `${connections.length} wallet${connections.length !== 1 ? 's' : ''} connected`
: "Remote wallet connection"
}
</p>
</div>
</div>
<div className="flex items-center gap-2">
{hasNWC && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasNWC ? "default" : "secondary"} className="text-xs">
{hasNWC ? "Ready" : "None"}
</Badge>
</div>
</div>
</div>
</div>
<Separator />
{/* NWC Management */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="font-medium">Nostr Wallet Connect</h3>
<Button size="sm" variant="outline" onClick={() => setAddDialogOpen(true)}>
<Plus className="h-4 w-4 mr-1" />
Add
</Button>
</div>
{/* Connected Wallets List */}
{connections.length === 0 ? (
<div className="text-center py-6 text-muted-foreground">
<p className="text-sm">No wallets connected</p>
</div>
) : (
<div className="space-y-2">
{connections.map((connection) => {
const info = connectionInfo[connection.connectionString];
const isActive = activeConnection === connection.connectionString;
return (
<div key={connection.connectionString} className={`flex items-center justify-between p-3 border rounded-lg ${isActive ? 'ring-2 ring-primary' : ''}`}>
<div className="flex items-center gap-3">
<WalletMinimal className="h-4 w-4 text-muted-foreground" />
<div>
<p className="text-sm font-medium">
{connection.alias || info?.alias || 'Lightning Wallet'}
</p>
<p className="text-xs text-muted-foreground">
NWC Connection
</p>
</div>
</div>
<div className="flex items-center gap-2">
{isActive && <CheckCircle className="h-4 w-4 text-green-600" />}
{!isActive && (
<Button
size="sm"
variant="ghost"
onClick={() => handleSetActive(connection.connectionString)}
>
<Zap className="h-3 w-3" />
</Button>
)}
<Button
size="sm"
variant="ghost"
onClick={() => handleRemoveConnection(connection.connectionString)}
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
</div>
);
})}
</div>
)}
</div>
{/* Help */}
{!hasWebLN && connections.length === 0 && (
<>
<Separator />
<div className="text-center py-4 space-y-2">
<p className="text-sm text-muted-foreground">
Install a WebLN extension or connect a NWC wallet for zaps.
</p>
</div>
</>
)}
</div>
));
WalletContent.displayName = 'WalletContent';
export function WalletModal({ children, className }: WalletModalProps) {
const [open, setOpen] = useState(false);
const [addDialogOpen, setAddDialogOpen] = useState(false);
const [connectionUri, setConnectionUri] = useState('');
const [alias, setAlias] = useState('');
const [isConnecting, setIsConnecting] = useState(false);
const isMobile = useIsMobile();
const {
connections,
activeConnection,
connectionInfo,
addConnection,
removeConnection,
setActiveConnection
} = useNWC();
const { hasWebLN, isDetecting } = useWallet();
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
const { toast } = useToast();
const handleAddConnection = async () => {
if (!connectionUri.trim()) {
toast({
title: 'Connection URI required',
description: 'Please enter a valid NWC connection URI.',
variant: 'destructive',
});
return;
}
setIsConnecting(true);
try {
const success = await addConnection(connectionUri.trim(), alias.trim() || undefined);
if (success) {
setConnectionUri('');
setAlias('');
setAddDialogOpen(false);
}
} finally {
setIsConnecting(false);
}
};
const handleRemoveConnection = (connectionString: string) => {
removeConnection(connectionString);
};
const handleSetActive = (connectionString: string) => {
setActiveConnection(connectionString);
toast({
title: 'Active wallet changed',
description: 'The selected wallet is now active for zaps.',
});
};
const walletContentProps = {
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen,
};
const addWalletDialog = (
<Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Connect NWC Wallet</DialogTitle>
<DialogDescription>
Enter your connection string from a compatible wallet.
</DialogDescription>
</DialogHeader>
<AddWalletContent
alias={alias}
setAlias={setAlias}
connectionUri={connectionUri}
setConnectionUri={setConnectionUri}
/>
<DialogFooter className="px-4">
<Button
onClick={handleAddConnection}
disabled={isConnecting || !connectionUri.trim()}
className="w-full"
>
{isConnecting ? 'Connecting...' : 'Connect'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
if (isMobile) {
return (
<>
<Drawer open={open} onOpenChange={setOpen}>
<DrawerTrigger asChild>
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Wallet Settings
</Button>
)}
</DrawerTrigger>
<DrawerContent className="h-full">
<DrawerHeader className="text-center relative">
<DrawerClose asChild>
<Button variant="ghost" size="sm" className="absolute right-4 top-4">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</Button>
</DrawerClose>
<DrawerTitle className="flex items-center justify-center gap-2 pt-2">
<Wallet className="h-5 w-5" />
Lightning Wallet
</DrawerTitle>
<DrawerDescription>
Connect your lightning wallet to send zaps instantly.
</DrawerDescription>
</DrawerHeader>
<div className="overflow-y-auto">
<WalletContent {...walletContentProps} />
</div>
</DrawerContent>
</Drawer>
{/* Render Add Wallet as a separate Drawer for mobile */}
<Drawer open={addDialogOpen} onOpenChange={setAddDialogOpen}>
<DrawerContent>
<DrawerHeader>
<DrawerTitle>Connect NWC Wallet</DrawerTitle>
<DrawerDescription>
Enter your connection string from a compatible wallet.
</DrawerDescription>
</DrawerHeader>
<AddWalletContent
alias={alias}
setAlias={setAlias}
connectionUri={connectionUri}
setConnectionUri={setConnectionUri}
/>
<div className="p-4">
<Button
onClick={handleAddConnection}
disabled={isConnecting || !connectionUri.trim()}
className="w-full"
>
{isConnecting ? 'Connecting...' : 'Connect'}
</Button>
</div>
</DrawerContent>
</Drawer>
</>
);
}
return (
<>
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
{children || (
<Button variant="outline" size="sm" className={className}>
<Wallet className="h-4 w-4 mr-2" />
Wallet Settings
</Button>
)}
</DialogTrigger>
<DialogContent className="sm:max-w-[500px] max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Wallet className="h-5 w-5" />
Lightning Wallet
</DialogTitle>
<DialogDescription>
Connect your lightning wallet to send zaps instantly.
</DialogDescription>
</DialogHeader>
<WalletContent {...walletContentProps} />
</DialogContent>
</Dialog>
{addWalletDialog}
</>
);
}
+58
View File
@@ -0,0 +1,58 @@
import { ZapDialog } from '@/components/ZapDialog';
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { Zap } from 'lucide-react';
import type { Event } from 'nostr-tools';
interface ZapButtonProps {
target: Event;
className?: string;
showCount?: boolean;
zapData?: { count: number; totalSats: number; isLoading?: boolean };
}
export function ZapButton({
target,
className = "text-xs ml-1",
showCount = true,
zapData: externalZapData
}: ZapButtonProps) {
const { user } = useCurrentUser();
const { data: author } = useAuthor(target?.pubkey || '');
const { webln, activeNWC } = useWallet();
// Only fetch data if not provided externally
const { totalSats: fetchedTotalSats, isLoading } = useZaps(
externalZapData ? [] : target ?? [], // Empty array prevents fetching if external data provided
webln,
activeNWC
);
// Don't show zap button if user is not logged in, is the author, or author has no lightning address
if (!user || !target || user.pubkey === target.pubkey || (!author?.metadata?.lud16 && !author?.metadata?.lud06)) {
return null;
}
// Use external data if provided, otherwise use fetched data
const totalSats = externalZapData?.totalSats ?? fetchedTotalSats;
const showLoading = externalZapData?.isLoading || isLoading;
return (
<ZapDialog target={target}>
<div className={`flex items-center gap-1 ${className}`}>
<Zap className="h-4 w-4" />
<span className="text-xs">
{showLoading ? (
'...'
) : showCount && totalSats > 0 ? (
`${totalSats.toLocaleString()}`
) : (
'Zap'
)}
</span>
</div>
</ZapDialog>
);
}
+470
View File
@@ -0,0 +1,470 @@
import { useState, useEffect, useRef, forwardRef } from 'react';
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
DrawerClose,
} from '@/components/ui/drawer';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { useToast } from '@/hooks/useToast';
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
interface ZapDialogProps {
target: Event;
children?: React.ReactNode;
className?: string;
}
const presetAmounts = [
{ amount: 1, icon: Sparkle },
{ amount: 50, icon: Sparkles },
{ amount: 100, icon: Zap },
{ amount: 250, icon: Star },
{ amount: 1000, icon: Rocket },
];
interface ZapContentProps {
invoice: string | null;
amount: number | string;
comment: string;
isZapping: boolean;
qrCodeUrl: string;
copied: boolean;
hasWebLN: boolean;
handleZap: () => void;
handleCopy: () => void;
openInWallet: () => void;
setAmount: (amount: number | string) => void;
setComment: (comment: string) => void;
inputRef: React.RefObject<HTMLInputElement>;
zap: (amount: number, comment: string) => void;
}
// Moved ZapContent outside of ZapDialog to prevent re-renders causing focus loss
const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
invoice,
amount,
comment,
isZapping,
qrCodeUrl,
copied,
hasWebLN,
handleZap,
handleCopy,
openInWallet,
setAmount,
setComment,
inputRef,
zap,
}, ref) => (
<div ref={ref}>
{invoice ? (
<div className="flex flex-col h-full min-h-0">
{/* Payment amount display */}
<div className="text-center pt-4">
<div className="text-2xl font-bold">{amount} sats</div>
</div>
<Separator className="my-4" />
<div className="flex flex-col justify-center min-h-0 flex-1 px-2">
{/* QR Code */}
<div className="flex justify-center">
<Card className="p-3 [@media(max-height:680px)]:max-w-[65vw] max-w-[95vw] mx-auto">
<CardContent className="p-0 flex justify-center">
{qrCodeUrl ? (
<img
src={qrCodeUrl}
alt="Lightning Invoice QR Code"
className="w-full h-auto aspect-square max-w-full object-contain"
/>
) : (
<div className="w-full aspect-square bg-muted animate-pulse rounded" />
)}
</CardContent>
</Card>
</div>
{/* Invoice input */}
<div className="space-y-2 mt-4">
<Label htmlFor="invoice">Lightning Invoice</Label>
<div className="flex gap-2 min-w-0">
<Input
id="invoice"
value={invoice}
readOnly
className="font-mono text-xs min-w-0 flex-1 overflow-hidden text-ellipsis"
onClick={(e) => e.currentTarget.select()}
/>
<Button
variant="outline"
size="icon"
onClick={handleCopy}
className="shrink-0"
>
{copied ? (
<Check className="h-4 w-4 text-green-600" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</div>
{/* Payment buttons */}
<div className="space-y-3 mt-4">
{hasWebLN && (
<Button
onClick={() => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
}}
disabled={isZapping}
className="w-full"
size="lg"
>
<Zap className="h-4 w-4 mr-2" />
{isZapping ? "Processing..." : "Pay with WebLN"}
</Button>
)}
<Button
variant="outline"
onClick={openInWallet}
className="w-full"
size="lg"
>
<ExternalLink className="h-4 w-4 mr-2" />
Open in Lightning Wallet
</Button>
<div className="text-xs sm:text-[.65rem] text-muted-foreground text-center">
Scan the QR code or copy the invoice to pay with any Lightning wallet.
</div>
</div>
</div>
</div>
) : (
<>
<div className="grid gap-3 px-4 py-4 w-full overflow-hidden">
<ToggleGroup
type="single"
value={String(amount)}
onValueChange={(value) => {
if (value) {
setAmount(parseInt(value, 10));
}
}}
className="grid grid-cols-5 gap-1 w-full"
>
{presetAmounts.map(({ amount: presetAmount, icon: Icon }) => (
<ToggleGroupItem
key={presetAmount}
value={String(presetAmount)}
className="flex flex-col h-auto min-w-0 text-xs px-1 py-2"
>
<Icon className="h-4 w-4 mb-1" />
<span className="truncate">{presetAmount}</span>
</ToggleGroupItem>
))}
</ToggleGroup>
<div className="flex items-center gap-2">
<div className="h-px flex-1 bg-muted" />
<span className="text-xs text-muted-foreground">OR</span>
<div className="h-px flex-1 bg-muted" />
</div>
<Input
ref={inputRef}
id="custom-amount"
type="number"
placeholder="Custom amount"
value={amount}
onChange={(e) => setAmount(e.target.value)}
className="w-full text-sm"
/>
<Textarea
id="custom-comment"
placeholder="Add a comment (optional)"
value={comment}
onChange={(e) => setComment(e.target.value)}
className="w-full resize-none text-sm"
rows={2}
/>
</div>
<div className="px-4 pb-4">
<Button onClick={handleZap} className="w-full" disabled={isZapping} size="default">
{isZapping ? (
'Creating invoice...'
) : (
<>
<Zap className="h-4 w-4 mr-2" />
Zap {amount} sats
</>
)}
</Button>
</div>
</>
)}
</div>
));
ZapContent.displayName = 'ZapContent';
export function ZapDialog({ target, children, className }: ZapDialogProps) {
const [open, setOpen] = useState(false);
const { user } = useCurrentUser();
const { data: author } = useAuthor(target.pubkey);
const { toast } = useToast();
const { webln, activeNWC, hasWebLN, detectWebLN } = useWallet();
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
const [amount, setAmount] = useState<number | string>(100);
const [comment, setComment] = useState<string>('');
const [copied, setCopied] = useState(false);
const [qrCodeUrl, setQrCodeUrl] = useState<string>('');
const inputRef = useRef<HTMLInputElement>(null);
const isMobile = useIsMobile();
useEffect(() => {
if (target) {
setComment('Zapped with MKStack!');
}
}, [target]);
// Detect WebLN when dialog opens
useEffect(() => {
if (open && !hasWebLN) {
detectWebLN();
}
}, [open, hasWebLN, detectWebLN]);
// Generate QR code
useEffect(() => {
let isCancelled = false;
const generateQR = async () => {
if (!invoice) {
setQrCodeUrl('');
return;
}
try {
const url = await QRCode.toDataURL(invoice.toUpperCase(), {
width: 512,
margin: 2,
color: {
dark: '#000000',
light: '#FFFFFF',
},
});
if (!isCancelled) {
setQrCodeUrl(url);
}
} catch (err) {
if (!isCancelled) {
console.error('Failed to generate QR code:', err);
}
}
};
generateQR();
return () => {
isCancelled = true;
};
}, [invoice]);
const handleCopy = async () => {
if (invoice) {
await navigator.clipboard.writeText(invoice);
setCopied(true);
toast({
title: 'Invoice copied',
description: 'Lightning invoice copied to clipboard',
});
setTimeout(() => setCopied(false), 2000);
}
};
const openInWallet = () => {
if (invoice) {
const lightningUrl = `lightning:${invoice}`;
window.open(lightningUrl, '_blank');
}
};
useEffect(() => {
if (open) {
setAmount(100);
setInvoice(null);
setCopied(false);
setQrCodeUrl('');
} else {
// Clean up state when dialog closes
setAmount(100);
setInvoice(null);
setCopied(false);
setQrCodeUrl('');
}
}, [open, setInvoice]);
const handleZap = () => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
zap(finalAmount, comment);
};
const contentProps = {
invoice,
amount,
comment,
isZapping,
qrCodeUrl,
copied,
hasWebLN,
handleZap,
handleCopy,
openInWallet,
setAmount,
setComment,
inputRef,
zap,
};
if (!user || user.pubkey === target.pubkey || !author?.metadata?.lud06 && !author?.metadata?.lud16) {
return null;
}
if (isMobile) {
// Use drawer for entire mobile flow, make it full-screen when showing invoice
return (
<Drawer
open={open}
onOpenChange={(newOpen) => {
// Reset invoice when closing
if (!newOpen) {
setInvoice(null);
setQrCodeUrl('');
}
setOpen(newOpen);
}}
dismissible={true} // Always allow dismissal via drag
snapPoints={invoice ? [0.5, 0.75, 0.98] : [0.98]}
activeSnapPoint={invoice ? 0.98 : 0.98}
modal={true}
shouldScaleBackground={false}
fadeFromIndex={0}
>
<DrawerTrigger asChild>
<div className={`cursor-pointer ${className || ''}`}>
{children}
</div>
</DrawerTrigger>
<DrawerContent
key={invoice ? 'payment' : 'form'}
className={cn(
"transition-all duration-300",
invoice ? "h-full max-h-screen" : "max-h-[98vh]"
)}
data-testid="zap-modal"
>
<DrawerHeader className="text-center relative">
{/* Back button when showing invoice */}
{invoice && (
<Button
variant="ghost"
size="sm"
onClick={() => {
setInvoice(null);
setQrCodeUrl('');
}}
className="absolute left-4 top-4 flex items-center gap-2"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{/* Close button */}
<DrawerClose asChild>
<Button
variant="ghost"
size="sm"
className="absolute right-4 top-4"
>
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</Button>
</DrawerClose>
<DrawerTitle className="text-lg break-words pt-2">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DrawerTitle>
<DrawerDescription className="text-sm break-words text-center">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
'Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!'
)}
</DrawerDescription>
</DrawerHeader>
<div className="flex-1 overflow-y-auto px-4 pb-4">
<ZapContent {...contentProps} />
</div>
</DrawerContent>
</Drawer>
);
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<div className={`cursor-pointer ${className || ''}`}>
{children}
</div>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px] max-h-[95vh] overflow-hidden" data-testid="zap-modal">
<DialogHeader>
<DialogTitle className="text-lg break-words">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DialogTitle>
<DialogDescription className="text-sm text-center break-words">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
<>
Zaps are small Bitcoin payments that support the creator of this item. If you enjoyed this, consider sending a zap!
</>
)}
</DialogDescription>
</DialogHeader>
<div className="overflow-y-auto">
<ZapContent {...contentProps} />
</div>
</DialogContent>
</Dialog>
);
}
+11 -1
View File
@@ -1,7 +1,7 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import { ChevronDown, LogOut, UserIcon, UserPlus } from 'lucide-react';
import { ChevronDown, LogOut, UserIcon, UserPlus, Wallet } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
@@ -11,6 +11,7 @@ import {
} from '@/components/ui/dropdown-menu.tsx';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
import { RelaySelector } from '@/components/RelaySelector';
import { WalletModal } from '@/components/WalletModal';
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
import { genUserName } from '@/lib/genUserName';
@@ -63,6 +64,15 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<WalletModal>
<DropdownMenuItem
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
onSelect={(e) => e.preventDefault()}
>
<Wallet className='w-4 h-4' />
<span>Wallet Settings</span>
</DropdownMenuItem>
</WalletModal>
<DropdownMenuItem
onClick={onAddAccountClick}
className='flex items-center gap-2 cursor-pointer p-2 rounded-md'
+10 -85
View File
@@ -2,11 +2,11 @@
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useState, useEffect, useRef } from 'react';
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, Lock, CheckCircle, Copy, Upload, Globe, FileSignature, Wand2 } from 'lucide-react';
import { Download, Key, UserPlus, FileText, Shield, User, Sparkles, LogIn, CheckCircle, Upload, Globe } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Card, CardContent } from '@/components/ui/card';
import { toast } from '@/hooks/useToast';
import { useLoginActions } from '@/hooks/useLoginActions';
@@ -30,7 +30,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
const [isLoading, setIsLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [showSparkles, setShowSparkles] = useState(false);
const [keySecured, setKeySecured] = useState<'none' | 'copied' | 'downloaded'>('none');
const [keySecured, setKeySecured] = useState<'none' | 'downloaded'>('none');
const [profileData, setProfileData] = useState({
name: '',
about: '',
@@ -80,7 +80,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
const url = globalThis.URL.createObjectURL(blob);
// Sanitize filename
const filename = sanitizeFilename('secret-key.txt');
const filename = sanitizeFilename('nostr-nsec-key.txt');
// Create a temporary link element and trigger download
const a = document.createElement('a');
@@ -110,14 +110,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
}
};
const copyKey = () => {
navigator.clipboard.writeText(nsec);
setKeySecured('copied');
toast({
title: 'Copied to clipboard!',
description: 'Key copied to clipboard.',
});
};
const finishKeySetup = () => {
try {
@@ -251,44 +244,31 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
const getTitle = () => {
if (step === 'welcome') return (
<span className="flex items-center justify-center gap-2">
<UserPlus className="w-5 h-5 text-primary" />
Create Your Account
</span>
);
if (step === 'generate') return (
<span className="flex items-center justify-center gap-2">
<Wand2 className="w-5 h-5 text-primary" />
Generating Your Key
</span>
);
if (step === 'download') return (
<span className="flex items-center justify-center gap-2">
<Lock className="w-5 h-5 text-primary" />
Secret Key
</span>
);
if (step === 'profile') return (
<span className="flex items-center justify-center gap-2">
<FileSignature className="w-5 h-5 text-primary" />
Create Your Profile
</span>
);
return (
<span className="flex items-center justify-center gap-2">
<User className="w-5 h-5 text-primary" />
Welcome!
</span>
);
};
const getDescription = () => {
if (step === 'welcome') return 'Ready to join the Nostr network?';
if (step === 'generate') return 'Creating your secret key to access Nostr.';
if (step === 'profile') return 'Tell others about yourself.';
return 'Your account is ready!';
};
// Reset state when dialog opens
useEffect(() => {
if (isOpen) {
@@ -320,9 +300,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
<DialogTitle className={cn('font-semibold text-center text-lg')}>
{getTitle()}
</DialogTitle>
<DialogDescription className={cn(`text-muted-foreground text-center ${step === 'download' && 'hidden'}`)}>
{getDescription()}
</DialogDescription>
</DialogHeader>
<div className='px-6 pt-2 pb-4 space-y-4 overflow-y-scroll flex-1'>
{/* Welcome Step - New engaging introduction */}
@@ -360,11 +337,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
</div>
<div className='space-y-3'>
<p className='text-muted-foreground px-5'>
Join the Nostr network and take control of your social media experience.
Your journey begins by generating a secret key.
</p>
<Button
className='w-full rounded-full py-6 text-lg font-semibold bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 transform transition-all duration-200 hover:scale-105 shadow-lg'
onClick={() => setStep('generate')}
@@ -372,10 +344,6 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
<LogIn className='w-5 h-5 mr-2' />
Get Started
</Button>
<p className='text-xs text-muted-foreground'>
Free forever • Decentralized • Your data, your control
</p>
</div>
</div>
)}
@@ -533,7 +501,7 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
Download as File
</div>
<div className='text-xs text-muted-foreground'>
Save as secret-key.txt file
Save as nostr-nsec-key.txt file
</div>
</div>
{keySecured === 'downloaded' && (
@@ -546,67 +514,24 @@ const SignupDialog: React.FC<SignupDialogProps> = ({ isOpen, onClose, onComplete
</CardContent>
</Card>
{/* Copy Option */}
<Card className={`cursor-pointer transition-all duration-200 ${
keySecured === 'copied'
? 'ring-2 ring-green-500 bg-green-50 dark:bg-green-950/20'
: 'hover:bg-primary/5 hover:border-primary/20'
}`}>
<CardContent className='p-3'>
<Button
variant="ghost"
className='w-full h-auto p-0 justify-start hover:bg-transparent'
onClick={copyKey}
>
<div className='flex items-center gap-3 w-full'>
<div className={`p-1.5 rounded-lg ${
keySecured === 'copied'
? 'bg-green-100 dark:bg-green-900'
: 'bg-primary/10'
}`}>
{keySecured === 'copied' ? (
<CheckCircle className='w-4 h-4 text-green-600' />
) : (
<Copy className='w-4 h-4 text-primary' />
)}
</div>
<div className='flex-1 text-left'>
<div className='font-medium text-sm'>
Copy to Clipboard
</div>
<div className='text-xs text-muted-foreground'>
Save to password manager
</div>
<div className='text-[.7rem] text-muted-foreground'>
{nsec.slice(0,16)}...
</div>
</div>
{keySecured === 'copied' && (
<div className='text-xs font-medium text-green-600'>
✓ Copied
</div>
)}
</div>
</Button>
</CardContent>
</Card>
</div>
{/* Continue button */}
<Button
className={`w-full rounded-full py-4 text-base font-semibold transform transition-all duration-200 shadow-lg ${
keySecured !== 'none'
keySecured === 'downloaded'
? 'bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 dark:from-blue-950/50 dark:to-purple-950/50 hover:scale-105'
: 'bg-gradient-to-r from-blue-600/60 to-indigo-600/60 text-muted cursor-not-allowed'
}`}
onClick={finishKeySetup}
disabled={keySecured === 'none'}
disabled={keySecured !== 'downloaded'}
>
<LogIn className='w-4 h-4 mr-2 flex-shrink-0' />
<span className="text-center leading-tight">
{keySecured === 'none' ? (
<>
Please secure your key first
Please download your key first
</>
) : (
<>
+1 -1
View File
@@ -9,7 +9,7 @@ export const buttonVariants = cva(
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
"border border-input 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",
-29
View File
@@ -1,29 +0,0 @@
import { useTheme } from "next-themes"
import { Toaster as Sonner } from "sonner"
type ToasterProps = React.ComponentProps<typeof Sonner>
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton:
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
)
}
export { Toaster }
+8
View File
@@ -0,0 +1,8 @@
import { ReactNode } from 'react';
import { useNWCInternal as useNWCHook } from '@/hooks/useNWC';
import { NWCContext } from '@/hooks/useNWCContext';
export function NWCProvider({ children }: { children: ReactNode }) {
const nwc = useNWCHook();
return <NWCContext.Provider value={nwc}>{children}</NWCContext.Provider>;
}
+12 -12
View File
@@ -1,19 +1,19 @@
import * as React from "react"
import { useEffect, useState } from "react"
const MOBILE_BREAKPOINT = 768
const MOBILE_BREAKPOINT = 768;
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
export function useIsMobile(): boolean {
const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT);
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
}
mql.addEventListener("change", onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener("change", onChange)
}, [])
mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener("change", onChange);
}, []);
return !!isMobile
return !!isMobile;
}
+221
View File
@@ -0,0 +1,221 @@
import { useState, useCallback } from 'react';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useToast } from '@/hooks/useToast';
import { LN } from '@getalby/sdk';
export interface NWCConnection {
connectionString: string;
alias?: string;
isConnected: boolean;
client?: LN;
}
export interface NWCInfo {
alias?: string;
color?: string;
pubkey?: string;
network?: string;
methods?: string[];
notifications?: string[];
}
export function useNWCInternal() {
const { toast } = useToast();
const [connections, setConnections] = useLocalStorage<NWCConnection[]>('nwc-connections', []);
const [activeConnection, setActiveConnection] = useLocalStorage<string | null>('nwc-active-connection', null);
const [connectionInfo, setConnectionInfo] = useState<Record<string, NWCInfo>>({});
// Add new connection
const addConnection = async (uri: string, alias?: string): Promise<boolean> => {
const parseNWCUri = (uri: string): { connectionString: string } | null => {
try {
if (!uri.startsWith('nostr+walletconnect://') && !uri.startsWith('nostrwalletconnect://')) {
console.error('Invalid NWC URI protocol:', { protocol: uri.split('://')[0] });
return null;
}
return { connectionString: uri };
} catch (error) {
console.error('Failed to parse NWC URI:', error);
return null;
}
};
const parsed = parseNWCUri(uri);
if (!parsed) {
toast({
title: 'Invalid NWC URI',
description: 'Please check the connection string and try again.',
variant: 'destructive',
});
return false;
}
const existingConnection = connections.find(c => c.connectionString === parsed.connectionString);
if (existingConnection) {
toast({
title: 'Connection already exists',
description: 'This wallet is already connected.',
variant: 'destructive',
});
return false;
}
try {
let timeoutId: NodeJS.Timeout | undefined;
const testPromise = new Promise((resolve, reject) => {
try {
const client = new LN(parsed.connectionString);
resolve(client);
} catch (error) {
reject(error);
}
});
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => reject(new Error('Connection test timeout')), 10000);
});
try {
await Promise.race([testPromise, timeoutPromise]) as LN;
if (timeoutId) clearTimeout(timeoutId);
} catch (error) {
if (timeoutId) clearTimeout(timeoutId);
throw error;
}
const connection: NWCConnection = {
connectionString: parsed.connectionString,
alias: alias || 'NWC Wallet',
isConnected: true,
};
setConnectionInfo(prev => ({
...prev,
[parsed.connectionString]: {
alias: connection.alias,
methods: ['pay_invoice'],
},
}));
const newConnections = [...connections, connection];
setConnections(newConnections);
if (connections.length === 0 || !activeConnection)
setActiveConnection(parsed.connectionString);
toast({
title: 'Wallet connected',
description: `Successfully connected to ${connection.alias}.`,
});
return true;
} catch (error) {
console.error('NWC connection failed:', error);
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
toast({
title: 'Connection failed',
description: `Could not connect to the wallet: ${errorMessage}`,
variant: 'destructive',
});
return false;
}
};
// Remove connection
const removeConnection = (connectionString: string) => {
const filtered = connections.filter(c => c.connectionString !== connectionString);
setConnections(filtered);
if (activeConnection === connectionString) {
const newActive = filtered.length > 0 ? filtered[0].connectionString : null;
setActiveConnection(newActive);
}
setConnectionInfo(prev => {
const newInfo = { ...prev };
delete newInfo[connectionString];
return newInfo;
});
toast({
title: 'Wallet disconnected',
description: 'The wallet connection has been removed.',
});
};
// Get active connection
const getActiveConnection = useCallback((): NWCConnection | null => {
if (!activeConnection && connections.length > 0) {
setActiveConnection(connections[0].connectionString);
return connections[0];
}
if (!activeConnection) return null;
const found = connections.find(c => c.connectionString === activeConnection);
return found || null;
}, [activeConnection, connections, setActiveConnection]);
// Send payment using the SDK
const sendPayment = useCallback(async (
connection: NWCConnection,
invoice: string
): Promise<{ preimage: string }> => {
if (!connection.connectionString) {
throw new Error('Invalid connection: missing connection string');
}
let client: LN;
try {
client = new LN(connection.connectionString);
} catch (error) {
console.error('Failed to create NWC client:', error);
throw new Error(`Failed to create NWC client: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
try {
let timeoutId: NodeJS.Timeout | undefined;
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => reject(new Error('Payment timeout after 15 seconds')), 15000);
});
const paymentPromise = client.pay(invoice);
try {
const response = await Promise.race([paymentPromise, timeoutPromise]) as { preimage: string };
if (timeoutId) clearTimeout(timeoutId);
return response;
} catch (error) {
if (timeoutId) clearTimeout(timeoutId);
throw error;
}
} catch (error) {
console.error('NWC payment failed:', error);
if (error instanceof Error) {
if (error.message.includes('timeout')) {
throw new Error('Payment timed out. Please try again.');
} else if (error.message.includes('insufficient')) {
throw new Error('Insufficient balance in connected wallet.');
} else if (error.message.includes('invalid')) {
throw new Error('Invalid invoice or connection. Please check your wallet.');
} else {
throw new Error(`Payment failed: ${error.message}`);
}
}
throw new Error('Payment failed with unknown error');
}
}, []);
return {
connections,
activeConnection,
connectionInfo,
addConnection,
removeConnection,
setActiveConnection,
getActiveConnection,
sendPayment,
};
}
+15
View File
@@ -0,0 +1,15 @@
import { useContext } from 'react';
import { createContext } from 'react';
import { useNWCInternal } from '@/hooks/useNWC';
type NWCContextType = ReturnType<typeof useNWCInternal>;
export const NWCContext = createContext<NWCContextType | null>(null);
export function useNWC(): NWCContextType {
const context = useContext(NWCContext);
if (!context) {
throw new Error('useNWC must be used within a NWCProvider');
}
return context;
}
+615
View File
@@ -0,0 +1,615 @@
import { useState, useCallback } from 'react';
import { useNostr } from '@nostrify/react';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/hooks/useToast';
import { nip19 } from 'nostr-tools';
// Your VAPID public key
const VAPID_PUBLIC_KEY = 'BIur4J9v796yU2ZUhaka6exwLAKUhAnDv0zJhrf_T1yuFs4jh4g8IaYygGAJ7u1KxZdu2Dwxh1ae5ob8yClHamc';
/**
* Push subscription configuration for Web Push API
*/
export interface PushSubscription {
endpoint: string;
p256dh_key: string;
auth_key: string;
}
/**
* Nostr event filter for push notifications
*/
export interface NotificationFilter {
kinds?: number[];
authors?: string[];
"#p"?: string[];
"#t"?: string[];
since?: number;
until?: number;
limit?: number;
}
/**
* Notification content configuration
*/
export interface NotificationConfig {
title: string;
body: string;
icon?: string;
badge?: string;
data?: Record<string, unknown>;
}
/**
* Complete subscription object for push notifications
*/
export interface PushNotificationSubscription {
subscription_id: string;
domain: string;
filter: NotificationFilter;
notification: NotificationConfig;
push_subscription: PushSubscription;
}
/**
* RPC request structure for push notification server
*/
interface RPCRequest {
method: 'register_subscription' | 'update_subscription' | 'delete_subscription' | 'list_subscriptions' | 'get_subscription';
params: Record<string, unknown>;
request_id: string;
}
/**
* Hook for managing push notifications via Nostr RPC
* Sends encrypted RPC events to a push notification worker
*/
export function usePush(workerPubkey?: string) {
const { nostr } = useNostr();
const { user } = useCurrentUser();
const { toast } = useToast();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Default worker pubkey - your actual push notification server
const defaultWorkerPubkey = workerPubkey || '7c3be2769c76eecd6c6e27276722dfae0d8ad201825253452153b90093c41654';
const clearError = useCallback(() => {
setError(null);
}, []);
/**
* Send an encrypted RPC request to the push notification worker
*/
const sendRPCRequest = useCallback(async (
method: RPCRequest['method'],
params: Record<string, unknown>
): Promise<void> => {
if (!user?.signer) {
throw new Error('User must be logged in to manage push notifications');
}
if (!user.signer.nip44) {
throw new Error('Signer must support NIP-44 encryption for push notifications');
}
// Decode worker pubkey if it's in npub format
let workerHex = defaultWorkerPubkey;
if (defaultWorkerPubkey.startsWith('npub1')) {
const decoded = nip19.decode(defaultWorkerPubkey);
if (decoded.type !== 'npub') {
throw new Error('Invalid worker pubkey format');
}
workerHex = decoded.data;
}
const requestId = `req_${crypto.randomUUID().replace(/-/g, "").slice(0, 8)}`;
const request: RPCRequest = {
method,
params,
request_id: requestId,
};
try {
// Encrypt the request using NIP-44
const payload = JSON.stringify(request);
console.log('Encrypting RPC request payload:', payload);
const encryptedRequest = await user.signer.nip44.encrypt(workerHex, payload);
console.log('Encrypted request:', encryptedRequest);
// Create unsigned RPC event (kind 25742)
const unsignedEvent = {
kind: 25742,
content: encryptedRequest,
tags: [
['p', workerHex],
['rpc', requestId],
['method', method],
],
created_at: Math.floor(Date.now() / 1000),
};
console.log('Signing RPC event:', unsignedEvent);
console.log('Target worker pubkey:', workerHex);
// Sign the event using the user's signer
const signedEvent = await user.signer.signEvent(unsignedEvent);
console.log('Signed RPC event:', signedEvent);
// Send the signed RPC event
const result = await nostr.event(signedEvent);
console.log('RPC event sent result:', result);
return;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
console.error('RPC send error:', err);
throw new Error(`Failed to send push notification request: ${errorMessage}`);
}
}, [user, nostr, defaultWorkerPubkey]);
/**
* Register a new push notification subscription
*/
const registerSubscription = useCallback(async (
subscriptionId: string,
domain: string,
filter: NotificationFilter,
notification: NotificationConfig,
pushSubscription: PushSubscription
): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('register_subscription', {
subscription_id: subscriptionId,
domain,
filter,
notification,
push_subscription: pushSubscription,
});
toast({
title: 'Push notifications enabled',
description: 'You will now receive push notifications for this content.',
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to register subscription';
setError(errorMessage);
toast({
title: 'Failed to enable notifications',
description: errorMessage,
variant: 'destructive',
});
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest, toast]);
/**
* Update an existing push notification subscription
*/
const updateSubscription = useCallback(async (
subscriptionId: string,
domain: string,
updates: Partial<Pick<PushNotificationSubscription, 'filter' | 'notification' | 'push_subscription'> & { is_active: boolean }>
): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('update_subscription', {
subscription_id: subscriptionId,
domain,
updates,
});
toast({
title: 'Subscription updated',
description: 'Your push notification settings have been updated.',
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to update subscription';
setError(errorMessage);
toast({
title: 'Failed to update notifications',
description: errorMessage,
variant: 'destructive',
});
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest, toast]);
/**
* Delete a push notification subscription
*/
const deleteSubscription = useCallback(async (
subscriptionId: string,
domain: string
): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('delete_subscription', {
subscription_id: subscriptionId,
domain,
});
toast({
title: 'Push notifications disabled',
description: 'You will no longer receive push notifications for this content.',
});
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to delete subscription';
setError(errorMessage);
toast({
title: 'Failed to disable notifications',
description: errorMessage,
variant: 'destructive',
});
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest, toast]);
/**
* List all subscriptions for a domain
*/
const listSubscriptions = useCallback(async (domain: string): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('list_subscriptions', { domain });
// Note: This is a fire-and-forget operation - the worker logs the results
// In a full implementation, you might want to listen for response events
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to list subscriptions';
setError(errorMessage);
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest]);
/**
* Get a specific subscription
*/
const getSubscription = useCallback(async (subscriptionId: string): Promise<void> => {
setIsLoading(true);
setError(null);
try {
await sendRPCRequest('get_subscription', { subscription_id: subscriptionId });
// Note: This is a fire-and-forget operation - the worker logs the results
// In a full implementation, you might want to listen for response events
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Failed to get subscription';
setError(errorMessage);
throw err;
} finally {
setIsLoading(false);
}
}, [sendRPCRequest]);
/**
* Request browser permission for push notifications
*/
const requestNotificationPermission = useCallback(async (): Promise<NotificationPermission> => {
if (!('Notification' in window)) {
throw new Error('This browser does not support push notifications');
}
if (Notification.permission === 'granted') {
return 'granted';
}
if (Notification.permission === 'denied') {
throw new Error('Push notifications are blocked. Please enable them in your browser settings.');
}
const permission = await Notification.requestPermission();
if (permission !== 'granted') {
throw new Error('Push notification permission was denied');
}
return permission;
}, []);
/**
* Convert npub to hex format for use in filters
*/
const convertNpubToHex = useCallback((pubkey: string): string => {
if (pubkey.startsWith('npub1')) {
try {
const decoded = nip19.decode(pubkey);
if (decoded.type !== 'npub') {
throw new Error('Invalid npub format');
}
return decoded.data;
} catch (error) {
throw new Error(`Failed to decode npub: ${error instanceof Error ? error.message : String(error)}`);
}
}
// If it's already hex format, return as-is
return pubkey;
}, []);
/**
* Convert VAPID key from base64url string to Uint8Array (matches working implementation)
*/
const convertVapidKey = useCallback((key: string): Uint8Array => {
try {
// Add padding if needed
const padding = '='.repeat((4 - (key.length % 4)) % 4);
const base64 = (key + padding).replace(/-/g, '+').replace(/_/g, '/');
// Decode base64 to binary string
const rawData = window.atob(base64);
// Convert binary string to Uint8Array
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
console.log('VAPID key converted:', {
originalLength: key.length,
base64Length: base64.length,
outputLength: outputArray.length,
firstBytes: Array.from(outputArray.slice(0, 10))
});
return outputArray;
} catch (err) {
throw new Error(`Invalid VAPID key format: ${err instanceof Error ? err.message : String(err)}`);
}
}, []);
/**
* Subscribe to browser push notifications and get subscription details
*/
const subscribeToPush = useCallback(async (vapidPublicKey: string = VAPID_PUBLIC_KEY): Promise<PushSubscription> => {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
throw new Error('Push notifications are not supported in this browser');
}
await requestNotificationPermission();
// Register service worker and wait for it to be ready
const registration = await navigator.serviceWorker.ready;
console.log('Service worker ready:', registration);
console.log('Service worker scope:', registration.scope);
console.log('Service worker active:', !!registration.active);
// Check if already subscribed
const existingSubscription = await registration.pushManager.getSubscription();
console.log('Existing subscription:', existingSubscription);
// Convert VAPID key to proper format
console.log('VAPID public key (base64):', vapidPublicKey);
const applicationServerKey = convertVapidKey(vapidPublicKey);
console.log('VAPID key converted to Uint8Array, length:', applicationServerKey.length);
let subscription;
try {
console.log('Attempting to subscribe to push manager...');
// Subscribe to push notifications
subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey,
});
console.log('Push subscription successful:', subscription);
} catch (pushError: any) {
console.error('Push subscription failed with error:', pushError);
console.error('Error name:', pushError.name);
console.error('Error message:', pushError.message);
// Provide specific error messages based on error type
if (pushError.name === 'InvalidStateError') {
throw new Error('Push subscription failed: Invalid state (possibly already subscribed)');
} else if (pushError.name === 'NotAllowedError') {
throw new Error('Push subscription failed: Permission denied by user');
} else if (pushError.name === 'NotSupportedError') {
throw new Error('Push subscription failed: Push not supported by this browser/service');
} else if (pushError.name === 'AbortError') {
throw new Error('Push subscription failed: Request was aborted (VAPID key mismatch?)');
} else {
throw new Error(`Push subscription failed: ${pushError.name} - ${pushError.message}`);
}
}
// Extract keys safely
const subscriptionJson = subscription.toJSON();
const keys = subscriptionJson.keys;
if (!keys?.p256dh || !keys?.auth) {
throw new Error('Invalid subscription keys received');
}
// Convert to our format
return {
endpoint: subscription.endpoint,
p256dh_key: keys.p256dh,
auth_key: keys.auth,
};
}, [requestNotificationPermission, convertVapidKey]);
/**
* Helper function to create a subscription for following an author
*/
const subscribeToAuthor = useCallback(async (
authorPubkey: string,
vapidPublicKey: string = VAPID_PUBLIC_KEY,
domain: string = window.location.hostname,
customNotification?: Partial<NotificationConfig>
): Promise<void> => {
const pushSubscription = await subscribeToPush(vapidPublicKey);
// Convert npub to hex format for the filter
const authorHex = convertNpubToHex(authorPubkey);
const subscriptionId = `follow-${authorHex.slice(0, 16)}-${Date.now()}`;
const filter: NotificationFilter = {
kinds: [1], // Text notes
authors: [authorHex], // Use hex format
limit: 50,
};
const notification: NotificationConfig = {
title: '{{author_name}} posted something!',
body: '{{content}}',
icon: '/icon-192x192.png',
badge: '/badge-72x72.png',
data: {
type: 'new_post',
author: authorHex, // Store hex format in data as well
},
...customNotification,
};
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
}, [subscribeToPush, registerSubscription, convertNpubToHex]);
/**
* Helper function to create a subscription for mentions
*/
const subscribeToMentions = useCallback(async (
userPubkey: string,
vapidPublicKey: string = VAPID_PUBLIC_KEY,
domain: string = window.location.hostname,
customNotification?: Partial<NotificationConfig>
): Promise<void> => {
const pushSubscription = await subscribeToPush(vapidPublicKey);
// Convert npub to hex format for the filter
const userHex = convertNpubToHex(userPubkey);
const subscriptionId = `mentions-${userHex.slice(0, 16)}-${Date.now()}`;
const filter: NotificationFilter = {
kinds: [1], // Text notes
"#p": [userHex], // Mentions of the user (use hex format)
limit: 50,
};
const notification: NotificationConfig = {
title: '{{author_name}} mentioned you!',
body: '{{content}}',
icon: '/icon-192x192.png',
badge: '/badge-72x72.png',
data: {
type: 'mention',
user: userHex, // Store hex format in data as well
},
...customNotification,
};
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
}, [subscribeToPush, registerSubscription, convertNpubToHex]);
/**
* Helper function to create a subscription for hashtags
*/
const subscribeToHashtag = useCallback(async (
hashtag: string,
vapidPublicKey: string = VAPID_PUBLIC_KEY,
domain: string = window.location.hostname,
customNotification?: Partial<NotificationConfig>
): Promise<void> => {
const pushSubscription = await subscribeToPush(vapidPublicKey);
const subscriptionId = `hashtag-${hashtag}-${Date.now()}`;
const filter: NotificationFilter = {
kinds: [1], // Text notes
"#t": [hashtag], // Posts with the hashtag
limit: 50,
};
const notification: NotificationConfig = {
title: `{{author_name}} posted about #${hashtag}`,
body: `{{content}}`,
icon: '/icon-192x192.png',
badge: '/badge-72x72.png',
data: {
type: 'hashtag',
hashtag,
},
...customNotification,
};
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
}, [subscribeToPush, registerSubscription]);
return {
// Core RPC methods
registerSubscription,
updateSubscription,
deleteSubscription,
listSubscriptions,
getSubscription,
// Browser push notification helpers
requestNotificationPermission,
subscribeToPush,
// Convenience methods for common use cases
subscribeToAuthor,
subscribeToMentions,
subscribeToHashtag,
// State
isLoading,
error,
clearError,
// Config
workerPubkey: defaultWorkerPubkey,
};
}
/**
* Example usage:
*
* ```tsx
* import { usePush } from '@/hooks/usePush';
*
* function MyComponent() {
* const {
* subscribeToAuthor,
* subscribeToMentions,
* isLoading,
* error
* } = usePush('npub1yourpushworkerpubkey');
*
* const handleFollowNotifications = async (authorPubkey: string) => {
* try {
* await subscribeToAuthor(authorPubkey, 'myapp.com');
* } catch (error) {
* console.error('Failed to enable notifications:', error);
* }
* };
*
* return (
* <Button
* onClick={() => handleFollowNotifications('npub1author...')}
* disabled={isLoading}
* >
* {isLoading ? 'Enabling...' : 'Enable Notifications'}
* </Button>
* );
* }
* ```
*/
+94
View File
@@ -0,0 +1,94 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
import { useNWC } from '@/hooks/useNWCContext';
import type { WebLNProvider } from 'webln';
import { requestProvider } from 'webln';
export interface WalletStatus {
hasWebLN: boolean;
hasNWC: boolean;
webln: WebLNProvider | null;
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
isDetecting: boolean;
preferredMethod: 'nwc' | 'webln' | 'manual';
}
export function useWallet() {
const [webln, setWebln] = useState<WebLNProvider | null>(null);
const [isDetecting, setIsDetecting] = useState(false);
const [hasAttemptedDetection, setHasAttemptedDetection] = useState(false);
const { connections, getActiveConnection } = useNWC();
// Get the active connection directly - no memoization to avoid stale state
const activeNWC = getActiveConnection();
// Detect WebLN
const detectWebLN = useCallback(async () => {
if (webln || isDetecting) return webln;
setIsDetecting(true);
try {
const provider = await requestProvider();
setWebln(provider);
setHasAttemptedDetection(true);
return provider;
} catch (error) {
// Only log the error if it's not the common "no provider" error
if (error instanceof Error && !error.message.includes('no WebLN provider')) {
console.warn('WebLN detection error:', error);
}
setWebln(null);
setHasAttemptedDetection(true);
return null;
} finally {
setIsDetecting(false);
}
}, [webln, isDetecting]);
// Only auto-detect once on mount
useEffect(() => {
if (!hasAttemptedDetection) {
detectWebLN();
}
}, [detectWebLN, hasAttemptedDetection]);
// Test WebLN connection
const testWebLN = useCallback(async (): Promise<boolean> => {
if (!webln) return false;
try {
await webln.enable();
return true;
} catch (error) {
console.error('WebLN test failed:', error);
return false;
}
}, [webln]);
// Calculate status values reactively
const hasNWC = useMemo(() => {
return connections.length > 0 && connections.some(c => c.isConnected);
}, [connections]);
// Determine preferred payment method
const preferredMethod: WalletStatus['preferredMethod'] = activeNWC
? 'nwc'
: webln
? 'webln'
: 'manual';
const status: WalletStatus = {
hasWebLN: !!webln,
hasNWC,
webln,
activeNWC,
isDetecting,
preferredMethod,
};
return {
...status,
hasAttemptedDetection,
detectWebLN,
testWebLN,
};
}
+338
View File
@@ -0,0 +1,338 @@
import { useState, useMemo, useEffect, useCallback } from 'react';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAuthor } from '@/hooks/useAuthor';
import { useAppContext } from '@/hooks/useAppContext';
import { useToast } from '@/hooks/useToast';
import { useNWC } from '@/hooks/useNWCContext';
import type { NWCConnection } from '@/hooks/useNWC';
import { nip57 } from 'nostr-tools';
import type { Event } from 'nostr-tools';
import type { WebLNProvider } from 'webln';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import type { NostrEvent } from '@nostrify/nostrify';
export function useZaps(
target: Event | Event[],
webln: WebLNProvider | null,
_nwcConnection: NWCConnection | null,
onZapSuccess?: () => void
) {
const { nostr } = useNostr();
const { toast } = useToast();
const { user } = useCurrentUser();
const { config } = useAppContext();
const queryClient = useQueryClient();
// Handle the case where an empty array is passed (from ZapButton when external data is provided)
const actualTarget = Array.isArray(target) ? (target.length > 0 ? target[0] : null) : target;
const author = useAuthor(actualTarget?.pubkey);
const { sendPayment, getActiveConnection } = useNWC();
const [isZapping, setIsZapping] = useState(false);
const [invoice, setInvoice] = useState<string | null>(null);
// Cleanup state when component unmounts
useEffect(() => {
return () => {
setIsZapping(false);
setInvoice(null);
};
}, []);
const { data: zapEvents, ...query } = useQuery<NostrEvent[], Error>({
queryKey: ['zaps', actualTarget?.id],
staleTime: 30000, // 30 seconds
refetchInterval: (query) => {
// Only refetch if the query is currently being observed (component is mounted)
return query.getObserversCount() > 0 ? 60000 : false;
},
queryFn: async (c) => {
if (!actualTarget) return [];
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
// Query for zap receipts for this specific event
if (actualTarget.kind >= 30000 && actualTarget.kind < 40000) {
// Addressable event
const identifier = actualTarget.tags.find((t) => t[0] === 'd')?.[1] || '';
const events = await nostr.query([{
kinds: [9735],
'#a': [`${actualTarget.kind}:${actualTarget.pubkey}:${identifier}`],
}], { signal });
return events;
} else {
// Regular event
const events = await nostr.query([{
kinds: [9735],
'#e': [actualTarget.id],
}], { signal });
return events;
}
},
enabled: !!actualTarget?.id,
});
// Process zap events into simple counts and totals
const { zapCount, totalSats, zaps } = useMemo(() => {
if (!zapEvents || !Array.isArray(zapEvents) || !actualTarget) {
return { zapCount: 0, totalSats: 0, zaps: [] };
}
let count = 0;
let sats = 0;
zapEvents.forEach(zap => {
count++;
// Try multiple methods to extract the amount:
// Method 1: amount tag (from zap request, sometimes copied to receipt)
const amountTag = zap.tags.find(([name]) => name === 'amount')?.[1];
if (amountTag) {
const millisats = parseInt(amountTag);
sats += Math.floor(millisats / 1000);
return;
}
// Method 2: Extract from bolt11 invoice
const bolt11Tag = zap.tags.find(([name]) => name === 'bolt11')?.[1];
if (bolt11Tag) {
try {
const invoiceSats = nip57.getSatoshisAmountFromBolt11(bolt11Tag);
sats += invoiceSats;
return;
} catch (error) {
console.warn('Failed to parse bolt11 amount:', error);
}
}
// Method 3: Parse from description (zap request JSON)
const descriptionTag = zap.tags.find(([name]) => name === 'description')?.[1];
if (descriptionTag) {
try {
const zapRequest = JSON.parse(descriptionTag);
const requestAmountTag = zapRequest.tags?.find(([name]: string[]) => name === 'amount')?.[1];
if (requestAmountTag) {
const millisats = parseInt(requestAmountTag);
sats += Math.floor(millisats / 1000);
return;
}
} catch (error) {
console.warn('Failed to parse description JSON:', error);
}
}
console.warn('Could not extract amount from zap receipt:', zap.id);
});
return { zapCount: count, totalSats: sats, zaps: zapEvents };
}, [zapEvents, actualTarget]);
const zap = async (amount: number, comment: string) => {
if (amount <= 0) {
return;
}
setIsZapping(true);
setInvoice(null); // Clear any previous invoice at the start
if (!user) {
toast({
title: 'Login required',
description: 'You must be logged in to send a zap.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
if (!actualTarget) {
toast({
title: 'Event not found',
description: 'Could not find the event to zap.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
try {
if (!author.data || !author.data?.metadata || !author.data?.event ) {
toast({
title: 'Author not found',
description: 'Could not find the author of this item.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
const { lud06, lud16 } = author.data.metadata;
if (!lud06 && !lud16) {
toast({
title: 'Lightning address not found',
description: 'The author does not have a lightning address configured.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
// Get zap endpoint using the old reliable method
const zapEndpoint = await nip57.getZapEndpoint(author.data.event);
if (!zapEndpoint) {
toast({
title: 'Zap endpoint not found',
description: 'Could not find a zap endpoint for the author.',
variant: 'destructive',
});
setIsZapping(false);
return;
}
// Create zap request - use appropriate event format based on kind
// For addressable events (30000-39999), pass the object to get 'a' tag
// For all other events, pass the ID string to get 'e' tag
const event = (actualTarget.kind >= 30000 && actualTarget.kind < 40000)
? actualTarget
: actualTarget.id;
const zapAmount = amount * 1000; // convert to millisats
const zapRequest = nip57.makeZapRequest({
profile: actualTarget.pubkey,
event: event,
amount: zapAmount,
relays: [config.relayUrl],
comment
});
// Sign the zap request (but don't publish to relays - only send to LNURL endpoint)
if (!user.signer) {
throw new Error('No signer available');
}
const signedZapRequest = await user.signer.signEvent(zapRequest);
try {
const res = await fetch(`${zapEndpoint}?amount=${zapAmount}&nostr=${encodeURI(JSON.stringify(signedZapRequest))}`);
const responseData = await res.json();
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${responseData.reason || 'Unknown error'}`);
}
const newInvoice = responseData.pr;
if (!newInvoice || typeof newInvoice !== 'string') {
throw new Error('Lightning service did not return a valid invoice');
}
// Get the current active NWC connection dynamically
const currentNWCConnection = getActiveConnection();
// Try NWC first if available and properly connected
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
try {
await sendPayment(currentNWCConnection, newInvoice);
// Clear states immediately on success
setIsZapping(false);
setInvoice(null);
toast({
title: 'Zap successful!',
description: `You sent ${amount} sats via NWC to the author.`,
});
// Invalidate zap queries to refresh counts
queryClient.invalidateQueries({ queryKey: ['zaps'] });
// Close dialog last to ensure clean state
onZapSuccess?.();
return;
} catch (nwcError) {
console.error('NWC payment failed, falling back:', nwcError);
// Show specific NWC error to user for debugging
const errorMessage = nwcError instanceof Error ? nwcError.message : 'Unknown NWC error';
toast({
title: 'NWC payment failed',
description: `${errorMessage}. Falling back to other payment methods...`,
variant: 'destructive',
});
}
}
if (webln) { // Try WebLN next
try {
await webln.sendPayment(newInvoice);
// Clear states immediately on success
setIsZapping(false);
setInvoice(null);
toast({
title: 'Zap successful!',
description: `You sent ${amount} sats to the author.`,
});
// Invalidate zap queries to refresh counts
queryClient.invalidateQueries({ queryKey: ['zaps'] });
// Close dialog last to ensure clean state
onZapSuccess?.();
} catch (weblnError) {
console.error('webln payment failed, falling back:', weblnError);
// Show specific WebLN error to user for debugging
const errorMessage = weblnError instanceof Error ? weblnError.message : 'Unknown WebLN error';
toast({
title: 'WebLN payment failed',
description: `${errorMessage}. Falling back to other payment methods...`,
variant: 'destructive',
});
setInvoice(newInvoice);
setIsZapping(false);
}
} else { // Default - show QR code and manual Lightning URI
setInvoice(newInvoice);
setIsZapping(false);
}
} catch (err) {
console.error('Zap error:', err);
toast({
title: 'Zap failed',
description: (err as Error).message,
variant: 'destructive',
});
setIsZapping(false);
}
} catch (err) {
console.error('Zap error:', err);
toast({
title: 'Zap failed',
description: (err as Error).message,
variant: 'destructive',
});
setIsZapping(false);
}
};
const resetInvoice = useCallback(() => {
setInvoice(null);
}, []);
return {
zaps,
zapCount,
totalSats,
...query,
zap,
isZapping,
invoice,
setInvoice,
resetInvoice,
};
}
+6 -3
View File
@@ -4,6 +4,7 @@ import { BrowserRouter } from 'react-router-dom';
import { NostrLoginProvider } from '@nostrify/react/login';
import NostrProvider from '@/components/NostrProvider';
import { AppProvider } from '@/components/AppProvider';
import { NWCProvider } from '@/contexts/NWCContext';
import { AppConfig } from '@/contexts/AppContext';
interface TestAppProps {
@@ -31,9 +32,11 @@ export function TestApp({ children }: TestAppProps) {
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='test-login'>
<NostrProvider>
<BrowserRouter>
{children}
</BrowserRouter>
<NWCProvider>
<BrowserRouter>
{children}
</BrowserRouter>
</NWCProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
-31
View File
@@ -1,31 +0,0 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": false,
"strictNullChecks": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noImplicitAny": false,
"noFallthroughCasesInSwitch": false,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"]
}
+25 -13
View File
@@ -1,19 +1,31 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
],
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": false,
"strictNullChecks": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noImplicitAny": false,
"noFallthroughCasesInSwitch": false,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"noImplicitAny": false,
"noUnusedParameters": false,
"skipLibCheck": true,
"allowJs": true,
"noUnusedLocals": false,
"strictNullChecks": true
}
}
},
"include": ["src"]
}
-22
View File
@@ -1,22 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}