mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 16:33:36 +00:00
Compare commits
104
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a4f97beba | ||
|
|
ac88a3a5c1 | ||
|
|
86d3d67eef | ||
|
|
2f6994f1e2 | ||
|
|
ca1b0cd303 | ||
|
|
413aa93e4f | ||
|
|
6941aad2f5 | ||
|
|
28aba4b3a4 | ||
|
|
e5b3f249f8 | ||
|
|
12e6465912 | ||
|
|
722d138f35 | ||
|
|
84a15aa077 | ||
|
|
8c7b595d22 | ||
|
|
0bf1e0e85e | ||
|
|
6534c5fcea | ||
|
|
e4ee998500 | ||
|
|
000be63075 | ||
|
|
5f14ac11fc | ||
|
|
0b7d86a16f | ||
|
|
8496cb99e5 | ||
|
|
386d664a33 | ||
|
|
0a5e8fc9e0 | ||
|
|
2ba510c54f | ||
|
|
eb0fd14e33 | ||
|
|
0532d23b57 | ||
|
|
8eddf49e61 | ||
|
|
d7dee81b1c | ||
|
|
fbafc52992 | ||
|
|
6d9e1816ee | ||
|
|
44b264e4b4 | ||
|
|
cc393a266c | ||
|
|
7eca8f850b | ||
|
|
f37b97630f | ||
|
|
14db9f59d0 | ||
|
|
701067fa8f | ||
|
|
ea791d405e | ||
|
|
35ad8cfa1b | ||
|
|
0fd52feabb | ||
|
|
440e02ff0e | ||
|
|
6380b1980c | ||
|
|
79980ded70 | ||
|
|
0562cb8ee2 | ||
|
|
1b4c27d17d | ||
|
|
9d7f5e48df | ||
|
|
dbacdbc8ac | ||
|
|
1c23b6bafc | ||
|
|
1dc91bd978 | ||
|
|
69b314c831 | ||
|
|
50ed58730c | ||
|
|
69252a7526 | ||
|
|
d1ef321e38 | ||
|
|
8d14062d14 | ||
|
|
61763d04c8 | ||
|
|
211d303301 | ||
|
|
5ad2d7fabc | ||
|
|
76cb50f2da | ||
|
|
7e24b0c347 | ||
|
|
6c48e7c684 | ||
|
|
d8b195e624 | ||
|
|
e6acf05e8d | ||
|
|
e8ef8f02ab | ||
|
|
e218305799 | ||
|
|
8bbb247ba8 | ||
|
|
ed80d74824 | ||
|
|
92eb50f8d2 | ||
|
|
f379a95548 | ||
|
|
9bafd29ec9 | ||
|
|
d7d6f8d6d5 | ||
|
|
381fdaf977 | ||
|
|
15ec6c69e7 | ||
|
|
7a52562926 | ||
|
|
5d8a4d4ace | ||
|
|
cb50cbe137 | ||
|
|
79b03dee38 | ||
|
|
04ae3d89c0 | ||
|
|
1ffe78c80c | ||
|
|
04c5a84ca9 | ||
|
|
71b9c9d380 | ||
|
|
cb231c7770 | ||
|
|
d72b28cf77 | ||
|
|
19ecfee4bf | ||
|
|
67658eb446 | ||
|
|
d8e2e62736 | ||
|
|
f37d86b8d3 | ||
|
|
d3866ae0af | ||
|
|
f6e149893b | ||
|
|
dcffee03af | ||
|
|
9d3ead4428 | ||
|
|
9e222850ce | ||
|
|
114eb13ce6 | ||
|
|
d72fc80cc5 | ||
|
|
68031244a5 | ||
|
|
53ac562d10 | ||
|
|
51be437219 | ||
|
|
b132e4847d | ||
|
|
1d42551b36 | ||
|
|
49abb22471 | ||
|
|
a974da9f88 | ||
|
|
16837284fb | ||
|
|
3f21df473b | ||
|
|
cec3b7f7d2 | ||
|
|
df0cc7c6aa | ||
|
|
629c350300 | ||
|
|
998bf4fc47 |
No files matched your search
@@ -1 +0,0 @@
|
|||||||
../.mcp.json
|
|
||||||
@@ -7,11 +7,13 @@ yarn-error.log*
|
|||||||
pnpm-debug.log*
|
pnpm-debug.log*
|
||||||
lerna-debug.log*
|
lerna-debug.log*
|
||||||
|
|
||||||
|
|
||||||
node_modules
|
node_modules
|
||||||
dist
|
dist
|
||||||
dist-ssr
|
dist-ssr
|
||||||
*.local
|
*.local
|
||||||
.ai/
|
.ai/
|
||||||
|
yarn.lock
|
||||||
|
|
||||||
# Editor directories and files
|
# Editor directories and files
|
||||||
.idea
|
.idea
|
||||||
|
|||||||
@@ -19,6 +19,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 components including NostrProvider for Nostr integration
|
||||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||||
|
- `/src/components/dm/`: Direct messaging UI components (DMMessagingInterface, DMConversationList, DMChatArea)
|
||||||
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
|
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
|
||||||
- `/src/hooks/`: Custom hooks including:
|
- `/src/hooks/`: Custom hooks including:
|
||||||
- `useNostr`: Core Nostr protocol integration
|
- `useNostr`: Core Nostr protocol integration
|
||||||
@@ -40,12 +41,16 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
|||||||
- `useShakespeare`: AI chat completions with Shakespeare AI API
|
- `useShakespeare`: AI chat completions with Shakespeare AI API
|
||||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||||
- `/src/lib/`: Utility functions and shared logic
|
- `/src/lib/`: Utility functions and shared logic
|
||||||
- `/src/contexts/`: React context providers (AppContext, NWCContext)
|
- `/src/contexts/`: React context providers (AppContext, NWCContext, DMContext)
|
||||||
|
- `useDMContext`: Hook exported from DMContext for direct messaging (NIP-04 & NIP-17)
|
||||||
|
- `useConversationMessages`: Hook exported from DMContext for paginated messages
|
||||||
- `/src/test/`: Testing utilities including TestApp component
|
- `/src/test/`: Testing utilities including TestApp component
|
||||||
- `/public/`: Static assets
|
- `/public/`: Static assets
|
||||||
- `App.tsx`: Main app component with provider setup
|
- `App.tsx`: Main app component with provider setup (**CRITICAL**: this file is **already configured** with `QueryClientProvider`, `NostrProvider`, `UnheadProvider` and other important providers - **read this file before making changes**. Changes are usually not necessary unless adding new providers. Changing this file may break the application)
|
||||||
- `AppRouter.tsx`: React Router configuration
|
- `AppRouter.tsx`: React Router configuration
|
||||||
|
|
||||||
|
**CRITICAL**: Always read the files mentioned above before making changes, as they contain important setup and configuration for the application. Never directly write to these files without first reading their contents.
|
||||||
|
|
||||||
## UI Components
|
## UI Components
|
||||||
|
|
||||||
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
The project uses shadcn/ui components located in `@/components/ui`. These are unstyled, accessible components built with Radix UI and styled with Tailwind CSS. Available components include:
|
||||||
@@ -109,6 +114,8 @@ The project includes a **`docs/`** directory containing specialized documentatio
|
|||||||
|
|
||||||
- **`docs/NOSTR_INFINITE_SCROLL.md`**: Read when building feed interfaces, implementing pagination for Nostr events, or creating social media-style infinite scroll experiences.
|
- **`docs/NOSTR_INFINITE_SCROLL.md`**: Read when building feed interfaces, implementing pagination for Nostr events, or creating social media-style infinite scroll experiences.
|
||||||
|
|
||||||
|
- **`docs/NOSTR_DIRECT_MESSAGES.md`**: Read when implementing direct messaging features, building chat interfaces, or working with encrypted peer-to-peer communication (NIP-04 and NIP-17).
|
||||||
|
|
||||||
## System Prompt Management
|
## System Prompt Management
|
||||||
|
|
||||||
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:
|
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:
|
||||||
@@ -116,10 +123,6 @@ The AI assistant's behavior and knowledge is defined by the AGENTS.md file, whic
|
|||||||
1. Edit AGENTS.md directly
|
1. Edit AGENTS.md directly
|
||||||
2. The changes take effect in the next session
|
2. The changes take effect in the next session
|
||||||
|
|
||||||
## "Vibed with MKStack"
|
|
||||||
|
|
||||||
When building the site for the first time, include "Vibed with MKStack" somewhere in the UI, linked to this URL: https://soapbox.pub/mkstack
|
|
||||||
|
|
||||||
## Nostr Protocol Integration
|
## Nostr Protocol Integration
|
||||||
|
|
||||||
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
This project comes with custom hooks for querying and publishing events on the Nostr network.
|
||||||
@@ -153,6 +156,7 @@ When implementing features that could use existing NIPs, follow this decision fr
|
|||||||
- No existing NIP covers the core functionality
|
- No existing NIP covers the core functionality
|
||||||
- The data structure is fundamentally different from existing patterns
|
- The data structure is fundamentally different from existing patterns
|
||||||
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
- The use case requires different storage characteristics (regular vs replaceable vs addressable)
|
||||||
|
- If you have a tool available to generate a kind, you **MUST** call the tool to generate a new kind rather than picking an arbitrary number
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -744,6 +748,20 @@ function EditProfilePage() {
|
|||||||
|
|
||||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||||
|
|
||||||
|
### Direct Messaging (NIP-04 & NIP-17)
|
||||||
|
|
||||||
|
The project includes a complete direct messaging system with real-time updates, encrypted storage, and support for both NIP-04 (legacy) and NIP-17 (modern private messaging) protocols. **The system is disabled by default** - enable it by passing `enabled: true` in the `DMProvider` config.
|
||||||
|
|
||||||
|
For complete implementation guide including:
|
||||||
|
- Setup and configuration
|
||||||
|
- Sending messages and file attachments
|
||||||
|
- Using the `DMMessagingInterface` component
|
||||||
|
- Building custom messaging UIs
|
||||||
|
- Protocol comparison (NIP-04 vs NIP-17)
|
||||||
|
- Advanced features and architecture
|
||||||
|
|
||||||
|
See **`docs/NOSTR_DIRECT_MESSAGES.md`**
|
||||||
|
|
||||||
### Uploading Files on Nostr
|
### Uploading Files on Nostr
|
||||||
|
|
||||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||||
@@ -812,16 +830,46 @@ export function Post(/* ...props */) {
|
|||||||
|
|
||||||
## App Configuration
|
## App Configuration
|
||||||
|
|
||||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
The project includes an `AppProvider` that manages global application state including theme and NIP-65 relay configuration. The default configuration includes:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
const defaultConfig: AppConfig = {
|
const defaultConfig: AppConfig = {
|
||||||
theme: "light",
|
theme: "light",
|
||||||
relayUrl: "wss://relay.nostr.band",
|
relayMetadata: {
|
||||||
|
relays: [
|
||||||
|
{ url: 'wss://relay.ditto.pub', read: true, write: true },
|
||||||
|
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
||||||
|
{ url: 'wss://relay.damus.io', read: true, write: true },
|
||||||
|
],
|
||||||
|
updatedAt: 0,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
|
The app uses NIP-65 compatible relay management with automatic sync when users log in. Local storage persists user preferences and relay configurations.
|
||||||
|
|
||||||
|
### Relay Management
|
||||||
|
|
||||||
|
The project includes a complete NIP-65 relay management system:
|
||||||
|
|
||||||
|
- **RelayListManager**: Component for managing multiple relays with read/write permissions
|
||||||
|
- **NostrSync**: Automatically syncs user's NIP-65 relay list when they log in
|
||||||
|
- **Automatic Publishing**: Changes to relay configuration are automatically published as NIP-65 events when the user is logged in
|
||||||
|
|
||||||
|
Use the `RelayListManager` component to provide relay management interfaces:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { RelayListManager } from '@/components/RelayListManager';
|
||||||
|
|
||||||
|
function SettingsPage() {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<h2>Relay Settings</h2>
|
||||||
|
<RelayListManager />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Routing
|
## Routing
|
||||||
|
|
||||||
@@ -875,10 +923,9 @@ The router includes automatic scroll-to-top functionality and a 404 NotFound pag
|
|||||||
|
|
||||||
### Empty States and No Content Found
|
### Empty States and No Content Found
|
||||||
|
|
||||||
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
|
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with helpful messaging. The application uses NIP-65 relay management, so users can manage their relays through the settings or relay management interface.
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
import { RelaySelector } from '@/components/RelaySelector';
|
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
|
||||||
// Empty state example
|
// Empty state example
|
||||||
@@ -887,24 +934,61 @@ import { Card, CardContent } from '@/components/ui/card';
|
|||||||
<CardContent className="py-12 px-8 text-center">
|
<CardContent className="py-12 px-8 text-center">
|
||||||
<div className="max-w-sm mx-auto space-y-6">
|
<div className="max-w-sm mx-auto space-y-6">
|
||||||
<p className="text-muted-foreground">
|
<p className="text-muted-foreground">
|
||||||
No results found. Try another relay?
|
No results found. Try checking your relay connections or wait a moment for content to load.
|
||||||
</p>
|
</p>
|
||||||
<RelaySelector className="w-full" />
|
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
```
|
```
|
||||||
|
|
||||||
## Design Customization
|
## CRITICAL Design Standards
|
||||||
|
|
||||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
- Create breathtaking, immersive designs that feel like bespoke masterpieces, rivaling the polish of Apple, Stripe, or luxury brands
|
||||||
|
- Designs must be production-ready, fully featured, with no placeholders unless explicitly requested, ensuring every element serves a functional and aesthetic purpose
|
||||||
|
- Avoid generic or templated aesthetics at all costs; every design must have a unique, brand-specific visual signature that feels custom-crafted
|
||||||
|
- Headers must be dynamic, immersive, and storytelling-driven, using layered visuals, motion, and symbolic elements to reflect the brand’s identity—never use simple “icon and text” combos
|
||||||
|
- Incorporate purposeful, lightweight animations for scroll reveals, micro-interactions (e.g., hover, click, transitions), and section transitions to create a sense of delight and fluidity
|
||||||
|
|
||||||
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
|
### Design Principles
|
||||||
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
|
|
||||||
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
|
- Achieve Apple-level refinement with meticulous attention to detail, ensuring designs evoke strong emotions (e.g., wonder, inspiration, energy) through color, motion, and composition
|
||||||
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
|
- Deliver fully functional interactive components with intuitive feedback states, ensuring every element has a clear purpose and enhances user engagement
|
||||||
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
|
- **Generate custom images liberally** when image generation tools are available - this is ALWAYS preferred over stock photography for creating unique, brand-specific visuals that perfectly match the design intent
|
||||||
|
- Ensure designs feel alive and modern with dynamic elements like gradients, glows, or parallax effects, avoiding static or flat aesthetics
|
||||||
|
- Before finalizing, ask: "Would this design make Apple or Stripe designers pause and take notice?" If not, iterate until it does
|
||||||
|
|
||||||
|
### Avoid Generic Design
|
||||||
|
|
||||||
|
- No basic layouts (e.g., text-on-left, image-on-right) without significant custom polish, such as dynamic backgrounds, layered visuals, or interactive elements
|
||||||
|
- No simplistic headers; they must be immersive, animated, and reflective of the brand’s core identity and mission
|
||||||
|
- No designs that could be mistaken for free templates or overused patterns; every element must feel intentional and tailored
|
||||||
|
|
||||||
|
### Interaction Patterns
|
||||||
|
|
||||||
|
- Use progressive disclosure for complex forms or content to guide users intuitively and reduce cognitive load
|
||||||
|
- Incorporate contextual menus, smart tooltips, and visual cues to enhance navigation and usability
|
||||||
|
- Implement drag-and-drop, hover effects, and transitions with clear, dynamic visual feedback to elevate the user experience
|
||||||
|
- Support power users with keyboard shortcuts, ARIA labels, and focus states for accessibility and efficiency
|
||||||
|
- Add subtle parallax effects or scroll-triggered animations to create depth and engagement without overwhelming the user
|
||||||
|
|
||||||
|
### Technical Requirements
|
||||||
|
|
||||||
|
- Curated color FRpalette (3-5 evocative colors + neutrals) that aligns with the brand’s emotional tone and creates a memorable impact
|
||||||
|
- Ensure a minimum 4.5:1 contrast ratio for all text and interactive elements to meet accessibility standards
|
||||||
|
- Use expressive, readable fonts (18px+ for body text, 40px+ for headlines) with a clear hierarchy; pair a modern sans-serif (e.g., Inter) with an elegant serif (e.g., Playfair Display) for personality
|
||||||
|
- Design for full responsiveness, ensuring flawless performance and aesthetics across all screen sizes (mobile, tablet, desktop)
|
||||||
|
- Adhere to WCAG 2.1 AA guidelines, including keyboard navigation, screen reader support, and reduced motion options
|
||||||
|
- Follow an 8px grid system for consistent spacing, padding, and alignment to ensure visual harmony
|
||||||
|
- Add depth with subtle shadows, gradients, glows, and rounded corners (e.g., 16px radius) to create a polished, modern aesthetic
|
||||||
|
- Optimize animations and interactions to be lightweight and performant, ensuring smooth experiences across devices
|
||||||
|
|
||||||
|
### Components
|
||||||
|
|
||||||
|
- Design reusable, modular components with consistent styling, behavior, and feedback states (e.g., hover, active, focus, error)
|
||||||
|
- Include purposeful animations (e.g., scale-up on hover, fade-in on scroll) to guide attention and enhance interactivity without distraction
|
||||||
|
- Ensure full accessibility support with keyboard navigation, ARIA labels, and visible focus states (e.g., a glowing outline in an accent color)
|
||||||
|
- Use custom icons or illustrations for components to reinforce the brand’s visual identity
|
||||||
|
|
||||||
### Adding Fonts
|
### Adding Fonts
|
||||||
|
|
||||||
@@ -975,6 +1059,7 @@ When users specify color schemes:
|
|||||||
There is an important distinction between **writing new tests** and **running existing tests**:
|
There is an important distinction between **writing new tests** and **running existing tests**:
|
||||||
|
|
||||||
### Writing Tests (Creating New Test Files)
|
### Writing Tests (Creating New Test Files)
|
||||||
|
|
||||||
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
**Do not write tests** unless the user explicitly requests them in plain language. Writing unnecessary tests wastes significant time and money. Only create tests when:
|
||||||
|
|
||||||
1. **The user explicitly asks for tests** to be written in their message
|
1. **The user explicitly asks for tests** to be written in their message
|
||||||
@@ -988,6 +1073,7 @@ There is an important distinction between **writing new tests** and **running ex
|
|||||||
- Existing functionality needs verification
|
- Existing functionality needs verification
|
||||||
|
|
||||||
### Running Tests (Executing the Test Suite)
|
### 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.
|
**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** to validate your changes
|
- **You must run the test script** to validate your changes
|
||||||
@@ -1047,3 +1133,9 @@ Run available tools in this priority order:
|
|||||||
- Create a git commit when your changes are complete
|
- Create a git commit when your changes are complete
|
||||||
|
|
||||||
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
|
The validation ensures code quality and catches errors before deployment, regardless of the development environment.
|
||||||
|
|
||||||
|
### Using Git
|
||||||
|
|
||||||
|
If git is available in your environment (through a `shell` tool, or other git-specific tools), you should utilize `git log` to understand project history. Use `git status` and `git diff` to check the status of your changes, and if you make a mistake use `git checkout` to restore files.
|
||||||
|
|
||||||
|
When your changes are complete and validated, create a git commit with a descriptive message summarizing your changes.
|
||||||
+157
-28
@@ -1,11 +1,82 @@
|
|||||||
### AI Integration with Shakespeare API
|
### AI Integration with Shakespeare API
|
||||||
|
|
||||||
Use the `useShakespeare` hook for AI chat completions with Nostr authentication.
|
Use the `useShakespeare` hook for AI chat completions with Nostr authentication. The API dynamically provides available models, so you should query them at runtime rather than hardcoding model names.
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
import { useShakespeare, type ChatMessage } from '@/hooks/useShakespeare';
|
import { useShakespeare, type ChatMessage, type Model } from '@/hooks/useShakespeare';
|
||||||
|
|
||||||
const { sendChatMessage, sendStreamingMessage, isLoading, error, isAuthenticated } = useShakespeare();
|
const {
|
||||||
|
sendChatMessage,
|
||||||
|
sendStreamingMessage,
|
||||||
|
getAvailableModels,
|
||||||
|
isLoading,
|
||||||
|
error,
|
||||||
|
isAuthenticated
|
||||||
|
} = useShakespeare();
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Model Selector Component
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
function ModelSelector({ onModelSelect }: { onModelSelect: (modelId: string) => void }) {
|
||||||
|
const { getAvailableModels, isLoading } = useShakespeare();
|
||||||
|
const [models, setModels] = useState<Model[]>([]);
|
||||||
|
const [selectedModel, setSelectedModel] = useState<string>('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const fetchModels = async () => {
|
||||||
|
try {
|
||||||
|
const response = await getAvailableModels();
|
||||||
|
// Sort models by total cost (cheapest first)
|
||||||
|
const sortedModels = response.data.sort((a, b) => {
|
||||||
|
const costA = parseFloat(a.pricing.prompt) + parseFloat(a.pricing.completion);
|
||||||
|
const costB = parseFloat(b.pricing.prompt) + parseFloat(b.pricing.completion);
|
||||||
|
return costA - costB;
|
||||||
|
});
|
||||||
|
setModels(sortedModels);
|
||||||
|
|
||||||
|
// Select the cheapest model by default
|
||||||
|
if (sortedModels.length > 0) {
|
||||||
|
const cheapestModel = sortedModels[0];
|
||||||
|
setSelectedModel(cheapestModel.id);
|
||||||
|
onModelSelect(cheapestModel.id);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to fetch models:', err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
fetchModels();
|
||||||
|
}, [getAvailableModels, onModelSelect]);
|
||||||
|
|
||||||
|
const handleModelChange = (modelId: string) => {
|
||||||
|
setSelectedModel(modelId);
|
||||||
|
onModelSelect(modelId);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<label htmlFor="model-select">Choose Model:</label>
|
||||||
|
<select
|
||||||
|
id="model-select"
|
||||||
|
value={selectedModel}
|
||||||
|
onChange={(e) => handleModelChange(e.target.value)}
|
||||||
|
disabled={isLoading}
|
||||||
|
>
|
||||||
|
<option value="">Select a model...</option>
|
||||||
|
{models.map((model, index) => {
|
||||||
|
const totalCost = parseFloat(model.pricing.prompt) + parseFloat(model.pricing.completion);
|
||||||
|
const isCheapest = index === 0;
|
||||||
|
return (
|
||||||
|
<option key={model.id} value={model.id}>
|
||||||
|
{model.name} - {isCheapest ? "Cheapest" : `$${totalCost.toFixed(6)}/token`}
|
||||||
|
</option>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Basic Chat Example
|
#### Basic Chat Example
|
||||||
@@ -15,19 +86,24 @@ function AIChat() {
|
|||||||
const { sendChatMessage, isLoading, error, isAuthenticated } = useShakespeare();
|
const { sendChatMessage, isLoading, error, isAuthenticated } = useShakespeare();
|
||||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||||
const [input, setInput] = useState('');
|
const [input, setInput] = useState('');
|
||||||
|
const [selectedModel, setSelectedModel] = useState<string>('');
|
||||||
|
|
||||||
const handleSend = async () => {
|
const handleSend = async () => {
|
||||||
if (!input.trim()) return;
|
if (!input.trim() || !selectedModel) return;
|
||||||
|
|
||||||
const newMessages = [...messages, { role: 'user', content: input }];
|
const newMessages = [...messages, { role: 'user', content: input }];
|
||||||
setMessages(newMessages);
|
setMessages(newMessages);
|
||||||
setInput('');
|
setInput('');
|
||||||
|
|
||||||
const response = await sendChatMessage(newMessages, 'tybalt'); // Free model
|
try {
|
||||||
setMessages(prev => [...prev, {
|
const response = await sendChatMessage(newMessages, selectedModel);
|
||||||
role: 'assistant',
|
setMessages(prev => [...prev, {
|
||||||
content: response.choices[0].message.content as string
|
role: 'assistant',
|
||||||
}]);
|
content: response.choices[0].message.content as string
|
||||||
|
}]);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Chat error:', err);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!isAuthenticated) return <div>Please log in to use AI</div>;
|
if (!isAuthenticated) return <div>Please log in to use AI</div>;
|
||||||
@@ -36,6 +112,11 @@ function AIChat() {
|
|||||||
<div className="max-w-2xl mx-auto p-4">
|
<div className="max-w-2xl mx-auto p-4">
|
||||||
{error && <div className="text-red-500 mb-4">{error}</div>}
|
{error && <div className="text-red-500 mb-4">{error}</div>}
|
||||||
|
|
||||||
|
{/* Model Selection */}
|
||||||
|
<div className="mb-4">
|
||||||
|
<ModelSelector onModelSelect={setSelectedModel} />
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2 mb-4">
|
<div className="space-y-2 mb-4">
|
||||||
{messages.map((msg, i) => (
|
{messages.map((msg, i) => (
|
||||||
<div key={i} className={`p-2 rounded ${msg.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'}`}>
|
<div key={i} className={`p-2 rounded ${msg.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'}`}>
|
||||||
@@ -50,9 +131,14 @@ function AIChat() {
|
|||||||
onChange={(e) => setInput(e.target.value)}
|
onChange={(e) => setInput(e.target.value)}
|
||||||
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
|
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
|
||||||
className="flex-1 p-2 border rounded"
|
className="flex-1 p-2 border rounded"
|
||||||
disabled={isLoading}
|
disabled={isLoading || !selectedModel}
|
||||||
|
placeholder={!selectedModel ? "Select a model first..." : "Type your message..."}
|
||||||
/>
|
/>
|
||||||
<button onClick={handleSend} disabled={isLoading} className="px-4 py-2 bg-blue-500 text-white rounded">
|
<button
|
||||||
|
onClick={handleSend}
|
||||||
|
disabled={isLoading || !selectedModel}
|
||||||
|
className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
|
||||||
|
>
|
||||||
Send
|
Send
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -61,30 +147,73 @@ function AIChat() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Streaming Chat
|
#### Streaming Chat Example
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
const [currentResponse, setCurrentResponse] = useState('');
|
function StreamingChat() {
|
||||||
|
const { sendStreamingMessage } = useShakespeare();
|
||||||
|
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||||
|
const [currentResponse, setCurrentResponse] = useState('');
|
||||||
|
const [selectedModel, setSelectedModel] = useState<string>('');
|
||||||
|
|
||||||
const handleStreaming = async (content: string) => {
|
const handleStreaming = async (content: string) => {
|
||||||
setCurrentResponse('');
|
if (!selectedModel) return;
|
||||||
await sendStreamingMessage(messages, 'shakespeare', (chunk) => {
|
|
||||||
setCurrentResponse(prev => prev + chunk);
|
setCurrentResponse('');
|
||||||
});
|
const newMessages = [...messages, { role: 'user', content }];
|
||||||
};
|
setMessages(newMessages);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await sendStreamingMessage(newMessages, selectedModel, (chunk) => {
|
||||||
|
setCurrentResponse(prev => prev + chunk);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Add the complete response to messages
|
||||||
|
if (currentResponse.trim()) {
|
||||||
|
setMessages(prev => [...prev, {
|
||||||
|
role: 'assistant',
|
||||||
|
content: currentResponse
|
||||||
|
}]);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Streaming error:', err);
|
||||||
|
} finally {
|
||||||
|
setCurrentResponse('');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{/* Model selection UI */}
|
||||||
|
<div className="mb-4">
|
||||||
|
<ModelSelector onModelSelect={setSelectedModel} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Chat interface */}
|
||||||
|
{/* ... rest of your chat UI */}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Models
|
#### Model Information
|
||||||
|
|
||||||
- **`tybalt`**: Free model for development
|
Models are dynamically fetched from the Shakespeare API and include:
|
||||||
- **`shakespeare`**: Premium model (requires credits)
|
|
||||||
|
- **Model ID**: Unique identifier for the model
|
||||||
|
- **Name**: Human-readable model name
|
||||||
|
- **Description**: Model capabilities and use cases
|
||||||
|
- **Context Window**: Maximum token limit for conversations
|
||||||
|
- **Pricing**: Cost per token for prompt and completion
|
||||||
|
- **Free Models**: Models with `pricing.prompt === "0"` and `pricing.completion === "0"`
|
||||||
|
|
||||||
#### Key Points
|
#### Key Points
|
||||||
|
|
||||||
- User must be logged in with Nostr account
|
- **Dynamic Model Discovery**: Always fetch available models using `getAvailableModels()`
|
||||||
- Use `tybalt` for free testing
|
- **Authentication Required**: User must be logged in with Nostr account
|
||||||
- Handle `isLoading` and `error` states
|
- **Free vs Premium**: Check pricing to determine if model requires credits
|
||||||
- Check `isAuthenticated` before API calls
|
- **Error Handling**: Handle `isLoading` and `error` states appropriately
|
||||||
|
- **Model Selection**: Provide UI for users to choose between available models
|
||||||
|
|
||||||
## Implementation Patterns and Best Practices
|
## Implementation Patterns and Best Practices
|
||||||
|
|
||||||
@@ -182,9 +311,9 @@ function AIChatWithErrorBoundary() {
|
|||||||
function useAIWithErrorHandling() {
|
function useAIWithErrorHandling() {
|
||||||
const { sendChatMessage, error, clearError } = useShakespeare();
|
const { sendChatMessage, error, clearError } = useShakespeare();
|
||||||
|
|
||||||
const sendMessage = async (messages: ChatMessage[]) => {
|
const sendMessage = async (messages: ChatMessage[], modelId: string) => {
|
||||||
try {
|
try {
|
||||||
await sendChatMessage(messages, 'tybalt');
|
await sendChatMessage(messages, modelId);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Handle specific error types with user-friendly messages
|
// Handle specific error types with user-friendly messages
|
||||||
if (err.message.includes('401')) {
|
if (err.message.includes('401')) {
|
||||||
|
|||||||
@@ -0,0 +1,473 @@
|
|||||||
|
### Direct Messaging on Nostr
|
||||||
|
|
||||||
|
This project includes a complete direct messaging system supporting both NIP-04 (legacy) and NIP-17 (modern, more private) encrypted messages with real-time subscriptions, optimistic updates, and a persistent cache-first local storage.
|
||||||
|
|
||||||
|
**The DM system is not enabled by default** - follow the setup instructions below to add messaging functionality to your application.
|
||||||
|
|
||||||
|
## Setup Instructions
|
||||||
|
|
||||||
|
### 1. Add DMProvider to Your App
|
||||||
|
|
||||||
|
First, add the `DMProvider` to your app's provider tree in `src/App.tsx`:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
// Add these imports at the top of src/App.tsx
|
||||||
|
import { DMProvider, type DMConfig } from '@/components/DMProvider';
|
||||||
|
import { PROTOCOL_MODE } from '@/lib/dmConstants';
|
||||||
|
|
||||||
|
// Add this configuration before your App component
|
||||||
|
const dmConfig: DMConfig = {
|
||||||
|
// Enable or disable DMs entirely
|
||||||
|
enabled: true, // Set to true to enable messaging functionality
|
||||||
|
|
||||||
|
// Choose one protocol mode:
|
||||||
|
// PROTOCOL_MODE.NIP04_ONLY - Force NIP-04 (legacy) only
|
||||||
|
// PROTOCOL_MODE.NIP17_ONLY - Force NIP-17 (private) only
|
||||||
|
// PROTOCOL_MODE.NIP04_OR_NIP17 - Allow users to choose between NIP-04 and NIP-17 (defaults to NIP-17)
|
||||||
|
protocolMode: PROTOCOL_MODE.NIP17_ONLY, // Recommended for new apps
|
||||||
|
};
|
||||||
|
|
||||||
|
// Then wrap your app components with DMProvider:
|
||||||
|
export function App() {
|
||||||
|
return (
|
||||||
|
<UnheadProvider head={head}>
|
||||||
|
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
|
||||||
|
<QueryClientProvider client={queryClient}>
|
||||||
|
<NostrLoginProvider storageKey='nostr:login'>
|
||||||
|
<NostrProvider>
|
||||||
|
<NostrSync />
|
||||||
|
<DMProvider config={dmConfig}>
|
||||||
|
<TooltipProvider>
|
||||||
|
<Toaster />
|
||||||
|
<Suspense>
|
||||||
|
<AppRouter />
|
||||||
|
</Suspense>
|
||||||
|
</TooltipProvider>
|
||||||
|
</DMProvider>
|
||||||
|
</NostrProvider>
|
||||||
|
</NostrLoginProvider>
|
||||||
|
</QueryClientProvider>
|
||||||
|
</AppProvider>
|
||||||
|
</UnheadProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Configure DM Settings
|
||||||
|
|
||||||
|
The `DMConfig` object supports the following options:
|
||||||
|
|
||||||
|
- `enabled` (boolean, default: `false`) - Enable/disable entire DM system. When false, no messages are loaded, stored, or processed.
|
||||||
|
- `protocolMode` (ProtocolMode, default: `PROTOCOL_MODE.NIP17_ONLY`) - Which protocols to support:
|
||||||
|
- `PROTOCOL_MODE.NIP04_ONLY` - Legacy encryption only
|
||||||
|
- `PROTOCOL_MODE.NIP17_ONLY` - Modern private messages (recommended)
|
||||||
|
- `PROTOCOL_MODE.NIP04_OR_NIP17` - Support both protocols (for backwards compatibility)
|
||||||
|
|
||||||
|
**Note**: The DM system uses domain-based IndexedDB naming (`nostr-dm-store-${hostname}`) to prevent conflicts between multiple apps on the same domain.
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### 1. Send Messages
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
|
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
||||||
|
|
||||||
|
function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
|
||||||
|
const { sendMessage } = useDMContext();
|
||||||
|
const [content, setContent] = useState('');
|
||||||
|
|
||||||
|
const handleSend = async () => {
|
||||||
|
await sendMessage({
|
||||||
|
recipientPubkey,
|
||||||
|
content,
|
||||||
|
protocol: MESSAGE_PROTOCOL.NIP17, // Uses NIP-44 encryption + gift wrapping
|
||||||
|
});
|
||||||
|
setContent('');
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
|
||||||
|
<textarea
|
||||||
|
value={content}
|
||||||
|
onChange={(e) => setContent(e.target.value)}
|
||||||
|
placeholder="Type a message..."
|
||||||
|
/>
|
||||||
|
<button type="submit">Send</button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Display Conversations
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
|
import { useAuthor } from '@/hooks/useAuthor';
|
||||||
|
import { genUserName } from '@/lib/genUserName';
|
||||||
|
|
||||||
|
function ConversationList({ onSelectConversation }: { onSelectConversation: (pubkey: string) => void }) {
|
||||||
|
const { conversations, isLoading } = useDMContext();
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return <div>Loading conversations...</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{conversations.map((conversation) => (
|
||||||
|
<ConversationItem
|
||||||
|
key={conversation.pubkey}
|
||||||
|
conversation={conversation}
|
||||||
|
onClick={() => onSelectConversation(conversation.pubkey)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ConversationItem({ conversation, onClick }: {
|
||||||
|
conversation: ConversationSummary;
|
||||||
|
onClick: () => void;
|
||||||
|
}) {
|
||||||
|
const author = useAuthor(conversation.pubkey);
|
||||||
|
const displayName = author.data?.metadata?.name || genUserName(conversation.pubkey);
|
||||||
|
const avatarUrl = author.data?.metadata?.picture;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button onClick={onClick} className="w-full p-3 hover:bg-accent rounded-lg">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Avatar>
|
||||||
|
<AvatarImage src={avatarUrl} />
|
||||||
|
<AvatarFallback>{displayName.slice(0, 2).toUpperCase()}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="flex-1 text-left">
|
||||||
|
<div className="font-medium">{displayName}</div>
|
||||||
|
<div className="text-sm text-muted-foreground truncate">
|
||||||
|
{conversation.lastMessage?.decryptedContent || 'No messages yet'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Display Messages in a Conversation
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useConversationMessages } from '@/hooks/useConversationMessages';
|
||||||
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
|
|
||||||
|
function MessageThread({ conversationPubkey }: { conversationPubkey: string }) {
|
||||||
|
const { user } = useCurrentUser();
|
||||||
|
const { messages, hasMoreMessages, loadEarlierMessages } = useConversationMessages(conversationPubkey);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col space-y-2">
|
||||||
|
{hasMoreMessages && (
|
||||||
|
<button onClick={loadEarlierMessages} className="text-sm text-muted-foreground">
|
||||||
|
Load earlier messages
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{messages.map((message) => {
|
||||||
|
const isFromMe = message.pubkey === user?.pubkey;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={message.id}
|
||||||
|
className={cn(
|
||||||
|
"flex",
|
||||||
|
isFromMe ? "justify-end" : "justify-start"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className={cn(
|
||||||
|
"max-w-[70%] rounded-lg px-4 py-2",
|
||||||
|
isFromMe ? "bg-primary text-primary-foreground" : "bg-muted"
|
||||||
|
)}>
|
||||||
|
{message.error ? (
|
||||||
|
<span className="text-red-500">🔒 {message.error}</span>
|
||||||
|
) : (
|
||||||
|
<p className="whitespace-pre-wrap break-words">
|
||||||
|
{message.decryptedContent}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{message.isSending && (
|
||||||
|
<span className="text-xs opacity-50">Sending...</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Using the Complete Messaging Interface
|
||||||
|
|
||||||
|
For a fully-featured messaging UI out of the box, use the `DMMessagingInterface` component:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { DMMessagingInterface } from "@/components/dm/DMMessagingInterface";
|
||||||
|
|
||||||
|
function MessagesPage() {
|
||||||
|
return (
|
||||||
|
<div className="container mx-auto p-4 h-screen">
|
||||||
|
<DMMessagingInterface />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `DMMessagingInterface` component provides a complete messaging UI with:
|
||||||
|
- Conversation list with Active/Requests tabs
|
||||||
|
- Message thread view with pagination
|
||||||
|
- Compose area with file upload support
|
||||||
|
- Real-time message updates
|
||||||
|
- Mobile-responsive layout (shows one panel at a time on mobile)
|
||||||
|
|
||||||
|
It requires no props and works automatically when wrapped in `DMProvider`.
|
||||||
|
|
||||||
|
**For custom layouts**, see the "Building Custom Messaging UIs" section below for individual components (`DMConversationList`, `DMChatArea`, `DMStatusInfo`).
|
||||||
|
|
||||||
|
## Sending Files with Messages
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
|
import { useUploadFile } from '@/hooks/useUploadFile';
|
||||||
|
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
||||||
|
import type { FileAttachment } from '@/contexts/DMContext';
|
||||||
|
|
||||||
|
function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
|
||||||
|
const { sendMessage } = useDMContext();
|
||||||
|
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
|
||||||
|
const [content, setContent] = useState('');
|
||||||
|
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||||
|
|
||||||
|
const handleSend = async () => {
|
||||||
|
let attachments: FileAttachment[] | undefined;
|
||||||
|
|
||||||
|
// Upload file if one is selected
|
||||||
|
if (selectedFile) {
|
||||||
|
const tags = await uploadFile(selectedFile);
|
||||||
|
|
||||||
|
attachments = [{
|
||||||
|
url: tags[0][1], // URL from first tag
|
||||||
|
mimeType: selectedFile.type,
|
||||||
|
size: selectedFile.size,
|
||||||
|
name: selectedFile.name,
|
||||||
|
tags: tags
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
|
||||||
|
await sendMessage({
|
||||||
|
recipientPubkey,
|
||||||
|
content,
|
||||||
|
protocol: MESSAGE_PROTOCOL.NIP17,
|
||||||
|
attachments,
|
||||||
|
});
|
||||||
|
|
||||||
|
setContent('');
|
||||||
|
setSelectedFile(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={(e) => { e.preventDefault(); handleSend(); }}>
|
||||||
|
<textarea
|
||||||
|
value={content}
|
||||||
|
onChange={(e) => setContent(e.target.value)}
|
||||||
|
placeholder="Type a message..."
|
||||||
|
/>
|
||||||
|
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
onChange={(e) => setSelectedFile(e.target.files?.[0] || null)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{selectedFile && <div>Selected: {selectedFile.name}</div>}
|
||||||
|
|
||||||
|
<button type="submit" disabled={isUploading}>
|
||||||
|
{isUploading ? 'Uploading...' : 'Send'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Protocol Comparison
|
||||||
|
|
||||||
|
### NIP-04 (Legacy)
|
||||||
|
- **Encryption**: NIP-04 (simpler, older)
|
||||||
|
- **Metadata**: Sender and recipient visible to relays
|
||||||
|
- **Event Kind**: Kind 4
|
||||||
|
- **Use When**: Compatibility with older clients
|
||||||
|
|
||||||
|
### NIP-17 (Modern & Private)
|
||||||
|
- **Encryption**: NIP-44 (stronger)
|
||||||
|
- **Metadata**: Hidden via gift wrapping (NIP-59)
|
||||||
|
- **Event Kinds**: Kind 14 (text), Kind 15 (files)
|
||||||
|
- **Wrapped In**: Kind 1059 (Gift Wrap) with ephemeral keys
|
||||||
|
- **Use When**: Maximum privacy (recommended)
|
||||||
|
|
||||||
|
**Key Privacy Features of NIP-17:**
|
||||||
|
- Sender identity hidden (uses random ephemeral keys)
|
||||||
|
- Timestamps randomized (±2 days) to hide send time
|
||||||
|
- Dual gift wraps (recipient + sender) for message history
|
||||||
|
|
||||||
|
## Advanced Features
|
||||||
|
|
||||||
|
### Conversation Categorization
|
||||||
|
|
||||||
|
The system automatically categorizes conversations:
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const { conversations } = useDMContext();
|
||||||
|
|
||||||
|
// Filter by category
|
||||||
|
const knownConversations = conversations.filter(c => c.isKnown);
|
||||||
|
const requestConversations = conversations.filter(c => c.isRequest);
|
||||||
|
|
||||||
|
// isKnown = true if user has sent at least one message
|
||||||
|
// isRequest = true if only received messages, never replied
|
||||||
|
```
|
||||||
|
|
||||||
|
### Loading States
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const { isLoading, loadingPhase, scanProgress } = useDMContext();
|
||||||
|
|
||||||
|
// Check overall loading state
|
||||||
|
if (isLoading) {
|
||||||
|
console.log('Current phase:', loadingPhase);
|
||||||
|
// LOADING_PHASES.CACHE - Loading from local cache
|
||||||
|
// LOADING_PHASES.RELAYS - Querying relays
|
||||||
|
// LOADING_PHASES.SUBSCRIPTIONS - Setting up real-time updates
|
||||||
|
// LOADING_PHASES.READY - Fully loaded
|
||||||
|
}
|
||||||
|
|
||||||
|
// Display scan progress for large message histories
|
||||||
|
if (scanProgress.nip17) {
|
||||||
|
console.log(`NIP-17: ${scanProgress.nip17.current} messages - ${scanProgress.nip17.status}`);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Clear Cache and Refresh
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
|
|
||||||
|
function SettingsButton() {
|
||||||
|
const { clearCacheAndRefetch } = useDMContext();
|
||||||
|
|
||||||
|
const handleClearCache = async () => {
|
||||||
|
await clearCacheAndRefetch();
|
||||||
|
// Clears IndexedDB cache and reloads all messages from relays
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button onClick={handleClearCache}>
|
||||||
|
Clear Message Cache
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Architecture Notes
|
||||||
|
|
||||||
|
### Data Flow
|
||||||
|
1. **Cache First**: Messages load instantly from encrypted IndexedDB cache
|
||||||
|
2. **Background Sync**: New messages fetched from relays in parallel
|
||||||
|
3. **Real-time Updates**: WebSocket subscriptions for live messages
|
||||||
|
4. **Optimistic UI**: Sent messages appear immediately, confirmed on relay response
|
||||||
|
|
||||||
|
### Storage
|
||||||
|
- **IndexedDB**: All messages stored locally with NIP-44 encryption
|
||||||
|
- **Per-User Storage**: Separate encrypted store for each logged-in user
|
||||||
|
- **Automatic Sync**: Debounced writes (15s) + immediate on new messages
|
||||||
|
|
||||||
|
### Performance
|
||||||
|
- **Parallel Queries**: NIP-04 and NIP-17 messages fetched simultaneously
|
||||||
|
- **Batched Loading**: Messages loaded in batches (1000/batch, 20k limit)
|
||||||
|
- **Pagination**: Conversation messages paginated (25/page)
|
||||||
|
- **Deduplication**: Automatic filtering of duplicate messages by ID
|
||||||
|
|
||||||
|
### Security
|
||||||
|
- **NIP-44 Encryption**: Modern authenticated encryption for all NIP-17 messages
|
||||||
|
- **Local Encryption**: IndexedDB storage encrypted with user's NIP-44 key
|
||||||
|
- **Ephemeral Keys**: Random keys for NIP-17 gift wraps (sender anonymity)
|
||||||
|
- **No Plaintext**: Decrypted content never persisted unencrypted
|
||||||
|
- **Domain Isolation**: IndexedDB databases are namespaced by hostname to prevent data conflicts
|
||||||
|
|
||||||
|
## Building Custom Messaging UIs
|
||||||
|
|
||||||
|
For advanced use cases, you can use the individual DM components to build custom layouts:
|
||||||
|
|
||||||
|
### Available Components
|
||||||
|
|
||||||
|
**`DMConversationList`** - Conversation sidebar with tabs
|
||||||
|
```tsx
|
||||||
|
import { DMConversationList } from '@/components/dm/DMConversationList';
|
||||||
|
|
||||||
|
<DMConversationList
|
||||||
|
selectedPubkey={selectedPubkey}
|
||||||
|
onSelectConversation={(pubkey) => setSelectedPubkey(pubkey)}
|
||||||
|
onStatusClick={() => setShowStatus(true)} // optional
|
||||||
|
className="h-full"
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
**`DMChatArea`** - Message thread and compose area
|
||||||
|
```tsx
|
||||||
|
import { DMChatArea } from '@/components/dm/DMChatArea';
|
||||||
|
|
||||||
|
<DMChatArea
|
||||||
|
pubkey={selectedPubkey}
|
||||||
|
onBack={() => setSelectedPubkey(null)} // optional, for mobile back button
|
||||||
|
className="h-full"
|
||||||
|
/>
|
||||||
|
```
|
||||||
|
|
||||||
|
**`DMStatusInfo`** - Debug/status panel
|
||||||
|
```tsx
|
||||||
|
import { DMStatusInfo } from '@/components/dm/DMStatusInfo';
|
||||||
|
|
||||||
|
<DMStatusInfo clearCacheAndRefetch={clearCacheAndRefetch} />
|
||||||
|
```
|
||||||
|
|
||||||
|
### Custom Layout Example
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { DMConversationList } from '@/components/dm/DMConversationList';
|
||||||
|
import { DMChatArea } from '@/components/dm/DMChatArea';
|
||||||
|
|
||||||
|
function CustomMessagingLayout() {
|
||||||
|
const [selectedPubkey, setSelectedPubkey] = useState<string | null>(null);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex h-screen">
|
||||||
|
{/* Custom sidebar */}
|
||||||
|
<aside className="w-64 border-r">
|
||||||
|
<DMConversationList
|
||||||
|
selectedPubkey={selectedPubkey}
|
||||||
|
onSelectConversation={setSelectedPubkey}
|
||||||
|
/>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
{/* Custom main area */}
|
||||||
|
<main className="flex-1">
|
||||||
|
{selectedPubkey ? (
|
||||||
|
<DMChatArea pubkey={selectedPubkey} />
|
||||||
|
) : (
|
||||||
|
<div className="flex items-center justify-center h-full">
|
||||||
|
<p>Select a conversation to start messaging</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
@@ -17,7 +17,6 @@ export default tseslint.config(
|
|||||||
globals: globals.browser,
|
globals: globals.browser,
|
||||||
},
|
},
|
||||||
linterOptions: {
|
linterOptions: {
|
||||||
noInlineConfig: true, // Prevents all eslint-disable comments
|
|
||||||
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
|
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
|
||||||
},
|
},
|
||||||
plugins: {
|
plugins: {
|
||||||
|
|||||||
Generated
+209
-60
@@ -11,8 +11,8 @@
|
|||||||
"@fontsource-variable/inter": "^5.2.6",
|
"@fontsource-variable/inter": "^5.2.6",
|
||||||
"@getalby/sdk": "^5.1.1",
|
"@getalby/sdk": "^5.1.1",
|
||||||
"@hookform/resolvers": "^3.9.0",
|
"@hookform/resolvers": "^3.9.0",
|
||||||
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
|
"@nostrify/nostrify": "^0.48.2",
|
||||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
|
"@nostrify/react": "^0.2.20",
|
||||||
"@radix-ui/react-accordion": "^1.2.0",
|
"@radix-ui/react-accordion": "^1.2.0",
|
||||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||||
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
||||||
@@ -43,15 +43,18 @@
|
|||||||
"@tanstack/react-query": "^5.56.2",
|
"@tanstack/react-query": "^5.56.2",
|
||||||
"@unhead/addons": "^2.0.10",
|
"@unhead/addons": "^2.0.10",
|
||||||
"@unhead/react": "^2.0.10",
|
"@unhead/react": "^2.0.10",
|
||||||
|
"buffer": "^6.0.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"cmdk": "^1.0.0",
|
"cmdk": "^1.0.0",
|
||||||
"date-fns": "^3.6.0",
|
"date-fns": "^3.6.0",
|
||||||
"embla-carousel-react": "^8.3.0",
|
"embla-carousel-react": "^8.3.0",
|
||||||
|
"idb": "^8.0.3",
|
||||||
"input-otp": "^1.2.4",
|
"input-otp": "^1.2.4",
|
||||||
"lucide-react": "^0.462.0",
|
"lucide-react": "^0.462.0",
|
||||||
"nostr-tools": "^2.13.0",
|
"nostr-tools": "^2.13.0",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
|
"qrcode.react": "^4.2.0",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-day-picker": "^8.10.1",
|
"react-day-picker": "^8.10.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
@@ -1170,35 +1173,6 @@
|
|||||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@jsr/nostrify__nostrify": {
|
|
||||||
"version": "0.46.4",
|
|
||||||
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__nostrify/0.46.4.tgz",
|
|
||||||
"integrity": "sha512-bYuYkw9+jnHIDEJD6i+w0p8xV1oBLr1RF5rS3qF2yTz1b8i50dXKMO2cLObjalAAO3RYbnib3l85t1ZgWLCzAA==",
|
|
||||||
"dependencies": {
|
|
||||||
"@jsr/nostrify__types": "^0.36.0",
|
|
||||||
"@jsr/scure__base": "^1.2.4",
|
|
||||||
"@jsr/std__encoding": "^0.224.1",
|
|
||||||
"lru-cache": "^10.2.0",
|
|
||||||
"nostr-tools": "^2.13.0",
|
|
||||||
"websocket-ts": "^2.2.1",
|
|
||||||
"zod": "^3.23.8"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@jsr/nostrify__types": {
|
|
||||||
"version": "0.36.0",
|
|
||||||
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__types/0.36.0.tgz",
|
|
||||||
"integrity": "sha512-kDjFf1nJMhZafULtH2GW+TWjs85J0aDxYYLpwBDQugDVsFqG2kLbxnoE2NtMJCIMNk1vUaipUHeil//4fY/d2w=="
|
|
||||||
},
|
|
||||||
"node_modules/@jsr/scure__base": {
|
|
||||||
"version": "1.2.5",
|
|
||||||
"resolved": "https://npm.jsr.io/~/11/@jsr/scure__base/1.2.5.tgz",
|
|
||||||
"integrity": "sha512-ino21k5s2kamz+uhAL/N3iI5vJ7x3zTtrzhM52iXBth41KxkFSIDiOlQNbMj4/jTih27jmS6Mi4Xke5vKTdNIA=="
|
|
||||||
},
|
|
||||||
"node_modules/@jsr/std__encoding": {
|
|
||||||
"version": "0.224.3",
|
|
||||||
"resolved": "https://npm.jsr.io/~/11/@jsr/std__encoding/0.224.3.tgz",
|
|
||||||
"integrity": "sha512-zAuX2QV1zwJ5RSmrnDGVerAtN3pBXpYYNlGzhERW9AiQ1UJd2/xruyB3i5NdTWy2OK2pjETswOj+0+prYTPlxQ=="
|
|
||||||
},
|
|
||||||
"node_modules/@noble/ciphers": {
|
"node_modules/@noble/ciphers": {
|
||||||
"version": "0.5.3",
|
"version": "0.5.3",
|
||||||
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-0.5.3.tgz",
|
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-0.5.3.tgz",
|
||||||
@@ -1280,31 +1254,64 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@nostrify/nostrify": {
|
"node_modules/@nostrify/nostrify": {
|
||||||
"name": "@jsr/nostrify__nostrify",
|
"version": "0.48.2",
|
||||||
"version": "0.46.4",
|
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.48.2.tgz",
|
||||||
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__nostrify/0.46.4.tgz",
|
"integrity": "sha512-Zze3RASsgn4MLQCuC5I4XR0WJi9G3J8qZpVjVIPvkw6vbZRct++JgavcZSxwKjJH1hHq+8d90IrHMOrskNQ8NQ==",
|
||||||
"integrity": "sha512-bYuYkw9+jnHIDEJD6i+w0p8xV1oBLr1RF5rS3qF2yTz1b8i50dXKMO2cLObjalAAO3RYbnib3l85t1ZgWLCzAA==",
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@jsr/nostrify__types": "^0.36.0",
|
"@nostrify/types": "0.36.8",
|
||||||
"@jsr/scure__base": "^1.2.4",
|
"@scure/base": "^2.0.0",
|
||||||
"@jsr/std__encoding": "^0.224.1",
|
"@smithy/util-base64": "^4.3.0",
|
||||||
|
"@smithy/util-hex-encoding": "^4.2.0",
|
||||||
|
"@types/node": "^24.1.0",
|
||||||
"lru-cache": "^10.2.0",
|
"lru-cache": "^10.2.0",
|
||||||
"nostr-tools": "^2.13.0",
|
"nostr-tools": "^2.13.0",
|
||||||
"websocket-ts": "^2.2.1",
|
"websocket-ts": "^2.2.1",
|
||||||
|
"ws": "^8.18.3",
|
||||||
"zod": "^3.23.8"
|
"zod": "^3.23.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@nostrify/react": {
|
"node_modules/@nostrify/nostrify/node_modules/@scure/base": {
|
||||||
"name": "@jsr/nostrify__react",
|
"version": "2.0.0",
|
||||||
"version": "0.2.8",
|
"resolved": "https://registry.npmjs.org/@scure/base/-/base-2.0.0.tgz",
|
||||||
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__react/0.2.8.tgz",
|
"integrity": "sha512-3E1kpuZginKkek01ovG8krQ0Z44E3DHPjc5S2rjJw9lZn3KSQOs8S7wqikF/AH7iRanHypj85uGyxk0XAyC37w==",
|
||||||
"integrity": "sha512-9sCsMm1uwuGWU+NhgFf6LS/4JzeRXnGOz+ocA5X3/ncvxZhidPOEAU39QyygRLFo/JYG8OC5wlyH8w0Uejq+VQ==",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"funding": {
|
||||||
"@jsr/nostrify__nostrify": "^0.46.4",
|
"url": "https://paulmillr.com/funding/"
|
||||||
"nostr-tools": "^2.13.0",
|
|
||||||
"react": "^18.0.0"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@nostrify/nostrify/node_modules/@types/node": {
|
||||||
|
"version": "24.10.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.4.tgz",
|
||||||
|
"integrity": "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"undici-types": "~7.16.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@nostrify/nostrify/node_modules/undici-types": {
|
||||||
|
"version": "7.16.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",
|
||||||
|
"integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@nostrify/react": {
|
||||||
|
"version": "0.2.20",
|
||||||
|
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.20.tgz",
|
||||||
|
"integrity": "sha512-Tvkdr5X+MQxh6CKKthk9Idch3vFp5nPcm57uJZJWrIqBtuj9jxMamM6uEo2lQAr0ugK52xDlyD50lRDRe0RMbQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"@nostrify/nostrify": "0.48.2",
|
||||||
|
"@nostrify/types": "0.36.8",
|
||||||
|
"@tanstack/react-query": "^5.69.0",
|
||||||
|
"nostr-tools": "^2.13.0",
|
||||||
|
"react": "^18.0.0",
|
||||||
|
"react-dom": "^18.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@nostrify/types": {
|
||||||
|
"version": "0.36.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.8.tgz",
|
||||||
|
"integrity": "sha512-tmpz5pkU8oXu7+V1qxvAzuoo8s5x4Gvo7h+JRm+JAW6x/2VZ8aQoA54yhn89qZ9agciMJhVdhqCm1PlK55w17A=="
|
||||||
|
},
|
||||||
"node_modules/@pkgjs/parseargs": {
|
"node_modules/@pkgjs/parseargs": {
|
||||||
"version": "0.11.0",
|
"version": "0.11.0",
|
||||||
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
|
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
|
||||||
@@ -3049,6 +3056,70 @@
|
|||||||
"url": "https://paulmillr.com/funding/"
|
"url": "https://paulmillr.com/funding/"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@smithy/is-array-buffer": {
|
||||||
|
"version": "4.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-4.2.0.tgz",
|
||||||
|
"integrity": "sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.6.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@smithy/util-base64": {
|
||||||
|
"version": "4.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.3.0.tgz",
|
||||||
|
"integrity": "sha512-GkXZ59JfyxsIwNTWFnjmFEI8kZpRNIBfxKjv09+nkAWPt/4aGaEWMM04m4sxgNVWkbt2MdSvE3KF/PfX4nFedQ==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@smithy/util-buffer-from": "^4.2.0",
|
||||||
|
"@smithy/util-utf8": "^4.2.0",
|
||||||
|
"tslib": "^2.6.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@smithy/util-buffer-from": {
|
||||||
|
"version": "4.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-4.2.0.tgz",
|
||||||
|
"integrity": "sha512-kAY9hTKulTNevM2nlRtxAG2FQ3B2OR6QIrPY3zE5LqJy1oxzmgBGsHLWTcNhWXKchgA0WHW+mZkQrng/pgcCew==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@smithy/is-array-buffer": "^4.2.0",
|
||||||
|
"tslib": "^2.6.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@smithy/util-hex-encoding": {
|
||||||
|
"version": "4.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@smithy/util-hex-encoding/-/util-hex-encoding-4.2.0.tgz",
|
||||||
|
"integrity": "sha512-CCQBwJIvXMLKxVbO88IukazJD9a4kQ9ZN7/UMGBjBcJYvatpWk+9g870El4cB8/EJxfe+k+y0GmR9CAzkF+Nbw==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.6.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@smithy/util-utf8": {
|
||||||
|
"version": "4.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.2.0.tgz",
|
||||||
|
"integrity": "sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw==",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@smithy/util-buffer-from": "^4.2.0",
|
||||||
|
"tslib": "^2.6.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@swc/core": {
|
"node_modules/@swc/core": {
|
||||||
"version": "1.11.24",
|
"version": "1.11.24",
|
||||||
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz",
|
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz",
|
||||||
@@ -4116,6 +4187,26 @@
|
|||||||
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/base64-js": {
|
||||||
|
"version": "1.5.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
||||||
|
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "patreon",
|
||||||
|
"url": "https://www.patreon.com/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "consulting",
|
||||||
|
"url": "https://feross.org/support"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/binary-extensions": {
|
"node_modules/binary-extensions": {
|
||||||
"version": "2.3.0",
|
"version": "2.3.0",
|
||||||
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
|
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
|
||||||
@@ -4184,6 +4275,30 @@
|
|||||||
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
|
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/buffer": {
|
||||||
|
"version": "6.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz",
|
||||||
|
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "patreon",
|
||||||
|
"url": "https://www.patreon.com/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "consulting",
|
||||||
|
"url": "https://feross.org/support"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"base64-js": "^1.3.1",
|
||||||
|
"ieee754": "^1.2.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/cac": {
|
"node_modules/cac": {
|
||||||
"version": "6.7.14",
|
"version": "6.7.14",
|
||||||
"resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
|
"resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
|
||||||
@@ -5316,9 +5431,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/glob": {
|
"node_modules/glob": {
|
||||||
"version": "10.4.5",
|
"version": "10.5.0",
|
||||||
"resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz",
|
"resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
|
||||||
"integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==",
|
"integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"foreground-child": "^3.1.0",
|
"foreground-child": "^3.1.0",
|
||||||
@@ -5473,6 +5588,32 @@
|
|||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/idb": {
|
||||||
|
"version": "8.0.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/idb/-/idb-8.0.3.tgz",
|
||||||
|
"integrity": "sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg==",
|
||||||
|
"license": "ISC"
|
||||||
|
},
|
||||||
|
"node_modules/ieee754": {
|
||||||
|
"version": "1.2.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
||||||
|
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "patreon",
|
||||||
|
"url": "https://www.patreon.com/feross"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "consulting",
|
||||||
|
"url": "https://feross.org/support"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"license": "BSD-3-Clause"
|
||||||
|
},
|
||||||
"node_modules/ignore": {
|
"node_modules/ignore": {
|
||||||
"version": "5.3.2",
|
"version": "5.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||||
@@ -5649,9 +5790,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/js-yaml": {
|
"node_modules/js-yaml": {
|
||||||
"version": "4.1.0",
|
"version": "4.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
|
||||||
"integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==",
|
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -6540,6 +6681,15 @@
|
|||||||
"node": ">=10.13.0"
|
"node": ">=10.13.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/qrcode.react": {
|
||||||
|
"version": "4.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz",
|
||||||
|
"integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==",
|
||||||
|
"license": "ISC",
|
||||||
|
"peerDependencies": {
|
||||||
|
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/queue-microtask": {
|
"node_modules/queue-microtask": {
|
||||||
"version": "1.2.3",
|
"version": "1.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
|
||||||
@@ -7779,9 +7929,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/vite": {
|
"node_modules/vite": {
|
||||||
"version": "6.3.5",
|
"version": "6.4.1",
|
||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.1.tgz",
|
||||||
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
|
"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -8184,10 +8334,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/ws": {
|
"node_modules/ws": {
|
||||||
"version": "8.18.2",
|
"version": "8.18.3",
|
||||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.2.tgz",
|
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
|
||||||
"integrity": "sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ==",
|
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=10.0.0"
|
"node": ">=10.0.0"
|
||||||
|
|||||||
+5
-2
@@ -13,8 +13,8 @@
|
|||||||
"@fontsource-variable/inter": "^5.2.6",
|
"@fontsource-variable/inter": "^5.2.6",
|
||||||
"@getalby/sdk": "^5.1.1",
|
"@getalby/sdk": "^5.1.1",
|
||||||
"@hookform/resolvers": "^3.9.0",
|
"@hookform/resolvers": "^3.9.0",
|
||||||
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
|
"@nostrify/nostrify": "^0.48.2",
|
||||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
|
"@nostrify/react": "^0.2.20",
|
||||||
"@radix-ui/react-accordion": "^1.2.0",
|
"@radix-ui/react-accordion": "^1.2.0",
|
||||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||||
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
||||||
@@ -45,15 +45,18 @@
|
|||||||
"@tanstack/react-query": "^5.56.2",
|
"@tanstack/react-query": "^5.56.2",
|
||||||
"@unhead/addons": "^2.0.10",
|
"@unhead/addons": "^2.0.10",
|
||||||
"@unhead/react": "^2.0.10",
|
"@unhead/react": "^2.0.10",
|
||||||
|
"buffer": "^6.0.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
"cmdk": "^1.0.0",
|
"cmdk": "^1.0.0",
|
||||||
"date-fns": "^3.6.0",
|
"date-fns": "^3.6.0",
|
||||||
"embla-carousel-react": "^8.3.0",
|
"embla-carousel-react": "^8.3.0",
|
||||||
|
"idb": "^8.0.3",
|
||||||
"input-otp": "^1.2.4",
|
"input-otp": "^1.2.4",
|
||||||
"lucide-react": "^0.462.0",
|
"lucide-react": "^0.462.0",
|
||||||
"nostr-tools": "^2.13.0",
|
"nostr-tools": "^2.13.0",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
|
"qrcode.react": "^4.2.0",
|
||||||
"react": "^18.3.1",
|
"react": "^18.3.1",
|
||||||
"react-day-picker": "^8.10.1",
|
"react-day-picker": "^8.10.1",
|
||||||
"react-dom": "^18.3.1",
|
"react-dom": "^18.3.1",
|
||||||
|
|||||||
+2
-1
@@ -1 +1,2 @@
|
|||||||
/* /index.html 200
|
/assets/* /assets/:splat 200
|
||||||
|
/* /index.html 200
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
User-agent: *
|
||||||
|
Allow: /
|
||||||
+11
-9
@@ -6,6 +6,7 @@ import { createHead, UnheadProvider } from '@unhead/react/client';
|
|||||||
import { InferSeoMetaPlugin } from '@unhead/addons';
|
import { InferSeoMetaPlugin } from '@unhead/addons';
|
||||||
import { Suspense } from 'react';
|
import { Suspense } from 'react';
|
||||||
import NostrProvider from '@/components/NostrProvider';
|
import NostrProvider from '@/components/NostrProvider';
|
||||||
|
import { NostrSync } from '@/components/NostrSync';
|
||||||
import { Toaster } from "@/components/ui/toaster";
|
import { Toaster } from "@/components/ui/toaster";
|
||||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||||
import { NostrLoginProvider } from '@nostrify/react/login';
|
import { NostrLoginProvider } from '@nostrify/react/login';
|
||||||
@@ -32,23 +33,24 @@ const queryClient = new QueryClient({
|
|||||||
|
|
||||||
const defaultConfig: AppConfig = {
|
const defaultConfig: AppConfig = {
|
||||||
theme: "light",
|
theme: "light",
|
||||||
relayUrl: "wss://relay.primal.net",
|
relayMetadata: {
|
||||||
|
relays: [
|
||||||
|
{ url: 'wss://relay.ditto.pub', read: true, write: true },
|
||||||
|
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
||||||
|
{ url: 'wss://relay.damus.io', read: true, write: true },
|
||||||
|
],
|
||||||
|
updatedAt: 0,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const presetRelays = [
|
|
||||||
{ url: 'wss://ditto.pub/relay', name: 'Ditto' },
|
|
||||||
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
|
|
||||||
{ url: 'wss://relay.damus.io', name: 'Damus' },
|
|
||||||
{ url: 'wss://relay.primal.net', name: 'Primal' },
|
|
||||||
];
|
|
||||||
|
|
||||||
export function App() {
|
export function App() {
|
||||||
return (
|
return (
|
||||||
<UnheadProvider head={head}>
|
<UnheadProvider head={head}>
|
||||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<NostrLoginProvider storageKey='nostr:login'>
|
<NostrLoginProvider storageKey='nostr:login'>
|
||||||
<NostrProvider>
|
<NostrProvider>
|
||||||
|
<NostrSync />
|
||||||
<NWCProvider>
|
<NWCProvider>
|
||||||
<TooltipProvider>
|
<TooltipProvider>
|
||||||
<Toaster />
|
<Toaster />
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { ScrollToTop } from "./components/ScrollToTop";
|
|||||||
|
|
||||||
import Index from "./pages/Index";
|
import Index from "./pages/Index";
|
||||||
import { NIP19Page } from "./pages/NIP19Page";
|
import { NIP19Page } from "./pages/NIP19Page";
|
||||||
|
import { RemoteLoginSuccess } from "./pages/RemoteLoginSuccess";
|
||||||
import NotFound from "./pages/NotFound";
|
import NotFound from "./pages/NotFound";
|
||||||
|
|
||||||
export function AppRouter() {
|
export function AppRouter() {
|
||||||
@@ -11,6 +12,7 @@ export function AppRouter() {
|
|||||||
<ScrollToTop />
|
<ScrollToTop />
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/" element={<Index />} />
|
<Route path="/" element={<Index />} />
|
||||||
|
<Route path="/remoteloginsuccess" element={<RemoteLoginSuccess />} />
|
||||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
||||||
<Route path="/:nip19" element={<NIP19Page />} />
|
<Route path="/:nip19" element={<NIP19Page />} />
|
||||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { ReactNode, useEffect } from 'react';
|
import { ReactNode, useEffect } from 'react';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||||
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
|
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
|
||||||
|
|
||||||
interface AppProviderProps {
|
interface AppProviderProps {
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
@@ -9,46 +9,54 @@ interface AppProviderProps {
|
|||||||
storageKey: string;
|
storageKey: string;
|
||||||
/** Default app configuration */
|
/** Default app configuration */
|
||||||
defaultConfig: AppConfig;
|
defaultConfig: AppConfig;
|
||||||
/** Optional list of preset relays to display in the RelaySelector */
|
|
||||||
presetRelays?: { name: string; url: string }[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Zod schema for RelayMetadata validation
|
||||||
|
const RelayMetadataSchema = z.object({
|
||||||
|
relays: z.array(z.object({
|
||||||
|
url: z.string().url(),
|
||||||
|
read: z.boolean(),
|
||||||
|
write: z.boolean(),
|
||||||
|
})),
|
||||||
|
updatedAt: z.number(),
|
||||||
|
}) satisfies z.ZodType<RelayMetadata>;
|
||||||
|
|
||||||
// Zod schema for AppConfig validation
|
// Zod schema for AppConfig validation
|
||||||
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
|
const AppConfigSchema = z.object({
|
||||||
theme: z.enum(['dark', 'light', 'system']),
|
theme: z.enum(['dark', 'light', 'system']),
|
||||||
relayUrl: z.string().url(),
|
relayMetadata: RelayMetadataSchema,
|
||||||
});
|
}) satisfies z.ZodType<AppConfig>;
|
||||||
|
|
||||||
export function AppProvider(props: AppProviderProps) {
|
export function AppProvider(props: AppProviderProps) {
|
||||||
const {
|
const {
|
||||||
children,
|
children,
|
||||||
storageKey,
|
storageKey,
|
||||||
defaultConfig,
|
defaultConfig,
|
||||||
presetRelays,
|
|
||||||
} = props;
|
} = props;
|
||||||
|
|
||||||
// App configuration state with localStorage persistence
|
// App configuration state with localStorage persistence
|
||||||
const [config, setConfig] = useLocalStorage<AppConfig>(
|
const [rawConfig, setConfig] = useLocalStorage<Partial<AppConfig>>(
|
||||||
storageKey,
|
storageKey,
|
||||||
defaultConfig,
|
{},
|
||||||
{
|
{
|
||||||
serialize: JSON.stringify,
|
serialize: JSON.stringify,
|
||||||
deserialize: (value: string) => {
|
deserialize: (value: string) => {
|
||||||
const parsed = JSON.parse(value);
|
const parsed = JSON.parse(value);
|
||||||
return AppConfigSchema.parse(parsed);
|
return AppConfigSchema.partial().parse(parsed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
// Generic config updater with callback pattern
|
// Generic config updater with callback pattern
|
||||||
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
|
const updateConfig = (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => {
|
||||||
setConfig(updater);
|
setConfig(updater);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const config = { ...defaultConfig, ...rawConfig };
|
||||||
|
|
||||||
const appContextValue: AppContextType = {
|
const appContextValue: AppContextType = {
|
||||||
config,
|
config,
|
||||||
updateConfig,
|
updateConfig,
|
||||||
presetRelays,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Apply theme effects to document
|
// Apply theme effects to document
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,5 @@
|
|||||||
import React, { useEffect, useRef } from 'react';
|
import React, { useEffect, useRef } from 'react';
|
||||||
import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify';
|
import { NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify';
|
||||||
import { NostrContext } from '@nostrify/react';
|
import { NostrContext } from '@nostrify/react';
|
||||||
import { useQueryClient } from '@tanstack/react-query';
|
import { useQueryClient } from '@tanstack/react-query';
|
||||||
import { useAppContext } from '@/hooks/useAppContext';
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
@@ -10,7 +10,7 @@ interface NostrProviderProps {
|
|||||||
|
|
||||||
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||||
const { children } = props;
|
const { children } = props;
|
||||||
const { config, presetRelays } = useAppContext();
|
const { config } = useAppContext();
|
||||||
|
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
|
||||||
@@ -18,13 +18,13 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
|||||||
const pool = useRef<NPool | undefined>(undefined);
|
const pool = useRef<NPool | undefined>(undefined);
|
||||||
|
|
||||||
// Use refs so the pool always has the latest data
|
// Use refs so the pool always has the latest data
|
||||||
const relayUrl = useRef<string>(config.relayUrl);
|
const relayMetadata = useRef(config.relayMetadata);
|
||||||
|
|
||||||
// Update refs when config changes
|
// Invalidate Nostr queries when relay metadata changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
relayUrl.current = config.relayUrl;
|
relayMetadata.current = config.relayMetadata;
|
||||||
queryClient.resetQueries();
|
queryClient.invalidateQueries({ queryKey: ['nostr'] });
|
||||||
}, [config.relayUrl, queryClient]);
|
}, [config.relayMetadata, queryClient]);
|
||||||
|
|
||||||
// Initialize NPool only once
|
// Initialize NPool only once
|
||||||
if (!pool.current) {
|
if (!pool.current) {
|
||||||
@@ -32,21 +32,27 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
|||||||
open(url: string) {
|
open(url: string) {
|
||||||
return new NRelay1(url);
|
return new NRelay1(url);
|
||||||
},
|
},
|
||||||
reqRouter(filters) {
|
reqRouter(filters: NostrFilter[]) {
|
||||||
return new Map([[relayUrl.current, filters]]);
|
const routes = new Map<string, NostrFilter[]>();
|
||||||
|
|
||||||
|
// Route to all read relays
|
||||||
|
const readRelays = relayMetadata.current.relays
|
||||||
|
.filter(r => r.read)
|
||||||
|
.map(r => r.url);
|
||||||
|
|
||||||
|
for (const url of readRelays) {
|
||||||
|
routes.set(url, filters);
|
||||||
|
}
|
||||||
|
|
||||||
|
return routes;
|
||||||
},
|
},
|
||||||
eventRouter(_event: NostrEvent) {
|
eventRouter(_event: NostrEvent) {
|
||||||
// Publish to the selected relay
|
// Get write relays from metadata
|
||||||
const allRelays = new Set<string>([relayUrl.current]);
|
const writeRelays = relayMetadata.current.relays
|
||||||
|
.filter(r => r.write)
|
||||||
|
.map(r => r.url);
|
||||||
|
|
||||||
// Also publish to the preset relays, capped to 5
|
const allRelays = new Set<string>(writeRelays);
|
||||||
for (const { url } of (presetRelays ?? [])) {
|
|
||||||
allRelays.add(url);
|
|
||||||
|
|
||||||
if (allRelays.size >= 5) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return [...allRelays];
|
return [...allRelays];
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { useEffect } from 'react';
|
||||||
|
import { useNostr } from '@nostrify/react';
|
||||||
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* NostrSync - Syncs user's Nostr data
|
||||||
|
*
|
||||||
|
* This component runs globally to sync various Nostr data when the user logs in.
|
||||||
|
* Currently syncs:
|
||||||
|
* - NIP-65 relay list (kind 10002)
|
||||||
|
*/
|
||||||
|
export function NostrSync() {
|
||||||
|
const { nostr } = useNostr();
|
||||||
|
const { user } = useCurrentUser();
|
||||||
|
const { config, updateConfig } = useAppContext();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!user) return;
|
||||||
|
|
||||||
|
const syncRelaysFromNostr = async () => {
|
||||||
|
try {
|
||||||
|
const events = await nostr.query(
|
||||||
|
[{ kinds: [10002], authors: [user.pubkey], limit: 1 }],
|
||||||
|
{ signal: AbortSignal.timeout(5000) }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (events.length > 0) {
|
||||||
|
const event = events[0];
|
||||||
|
|
||||||
|
// Only update if the event is newer than our stored data
|
||||||
|
if (event.created_at > config.relayMetadata.updatedAt) {
|
||||||
|
const fetchedRelays = event.tags
|
||||||
|
.filter(([name]) => name === 'r')
|
||||||
|
.map(([_, url, marker]) => ({
|
||||||
|
url,
|
||||||
|
read: !marker || marker === 'read',
|
||||||
|
write: !marker || marker === 'write',
|
||||||
|
}));
|
||||||
|
|
||||||
|
if (fetchedRelays.length > 0) {
|
||||||
|
console.log('Syncing relay list from Nostr:', fetchedRelays);
|
||||||
|
updateConfig((current) => ({
|
||||||
|
...current,
|
||||||
|
relayMetadata: {
|
||||||
|
relays: fetchedRelays,
|
||||||
|
updatedAt: event.created_at,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to sync relays from Nostr:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
syncRelaysFromNostr();
|
||||||
|
}, [user, config.relayMetadata.updatedAt, nostr, updateConfig]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { Plus, X, Wifi, Settings } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Switch } from '@/components/ui/switch';
|
||||||
|
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||||
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
|
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||||
|
import { useToast } from '@/hooks/useToast';
|
||||||
|
|
||||||
|
interface Relay {
|
||||||
|
url: string;
|
||||||
|
read: boolean;
|
||||||
|
write: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function RelayListManager() {
|
||||||
|
const { config, updateConfig } = useAppContext();
|
||||||
|
const { user } = useCurrentUser();
|
||||||
|
const { mutate: publishEvent } = useNostrPublish();
|
||||||
|
const { toast } = useToast();
|
||||||
|
|
||||||
|
const [relays, setRelays] = useState<Relay[]>(config.relayMetadata.relays);
|
||||||
|
const [newRelayUrl, setNewRelayUrl] = useState('');
|
||||||
|
|
||||||
|
// Sync local state with config when it changes (e.g., from NostrProvider sync)
|
||||||
|
useEffect(() => {
|
||||||
|
setRelays(config.relayMetadata.relays);
|
||||||
|
}, [config.relayMetadata.relays]);
|
||||||
|
|
||||||
|
const normalizeRelayUrl = (url: string): string => {
|
||||||
|
url = url.trim();
|
||||||
|
try {
|
||||||
|
return new URL(url).toString();
|
||||||
|
} catch {
|
||||||
|
try {
|
||||||
|
return new URL(`wss://${url}`).toString();
|
||||||
|
} catch {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const isValidRelayUrl = (url: string): boolean => {
|
||||||
|
const trimmed = url.trim();
|
||||||
|
if (!trimmed) return false;
|
||||||
|
|
||||||
|
const normalized = normalizeRelayUrl(trimmed);
|
||||||
|
try {
|
||||||
|
new URL(normalized);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddRelay = () => {
|
||||||
|
if (!isValidRelayUrl(newRelayUrl)) {
|
||||||
|
toast({
|
||||||
|
title: 'Invalid relay URL',
|
||||||
|
description: 'Please enter a valid relay URL (e.g., wss://relay.example.com)',
|
||||||
|
variant: 'destructive',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalized = normalizeRelayUrl(newRelayUrl);
|
||||||
|
|
||||||
|
if (relays.some(r => r.url === normalized)) {
|
||||||
|
toast({
|
||||||
|
title: 'Relay already exists',
|
||||||
|
description: 'This relay is already in your list.',
|
||||||
|
variant: 'destructive',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const newRelays = [...relays, { url: normalized, read: true, write: true }];
|
||||||
|
setRelays(newRelays);
|
||||||
|
setNewRelayUrl('');
|
||||||
|
|
||||||
|
saveRelays(newRelays);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoveRelay = (url: string) => {
|
||||||
|
const newRelays = relays.filter(r => r.url !== url);
|
||||||
|
setRelays(newRelays);
|
||||||
|
saveRelays(newRelays);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleToggleRead = (url: string) => {
|
||||||
|
const newRelays = relays.map(r =>
|
||||||
|
r.url === url ? { ...r, read: !r.read } : r
|
||||||
|
);
|
||||||
|
setRelays(newRelays);
|
||||||
|
saveRelays(newRelays);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleToggleWrite = (url: string) => {
|
||||||
|
const newRelays = relays.map(r =>
|
||||||
|
r.url === url ? { ...r, write: !r.write } : r
|
||||||
|
);
|
||||||
|
setRelays(newRelays);
|
||||||
|
saveRelays(newRelays);
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveRelays = (newRelays: Relay[]) => {
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
|
// Update local config
|
||||||
|
updateConfig((current) => ({
|
||||||
|
...current,
|
||||||
|
relayMetadata: {
|
||||||
|
relays: newRelays,
|
||||||
|
updatedAt: now,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Publish to Nostr if user is logged in
|
||||||
|
if (user) {
|
||||||
|
publishNIP65RelayList(newRelays);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const publishNIP65RelayList = (relayList: Relay[]) => {
|
||||||
|
const tags = relayList.map(relay => {
|
||||||
|
if (relay.read && relay.write) {
|
||||||
|
return ['r', relay.url];
|
||||||
|
} else if (relay.read) {
|
||||||
|
return ['r', relay.url, 'read'];
|
||||||
|
} else if (relay.write) {
|
||||||
|
return ['r', relay.url, 'write'];
|
||||||
|
}
|
||||||
|
// If neither read nor write, don't include (shouldn't happen)
|
||||||
|
return null;
|
||||||
|
}).filter((tag): tag is string[] => tag !== null);
|
||||||
|
|
||||||
|
publishEvent(
|
||||||
|
{
|
||||||
|
kind: 10002,
|
||||||
|
content: '',
|
||||||
|
tags,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
onSuccess: () => {
|
||||||
|
toast({
|
||||||
|
title: 'Relay list published',
|
||||||
|
description: 'Your relay list has been published to Nostr.',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error('Failed to publish relay list:', error);
|
||||||
|
toast({
|
||||||
|
title: 'Failed to publish relay list',
|
||||||
|
description: 'There was an error publishing your relay list to Nostr.',
|
||||||
|
variant: 'destructive',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderRelayUrl = (url: string): string => {
|
||||||
|
try {
|
||||||
|
const parsed = new URL(url);
|
||||||
|
if (parsed.protocol === 'wss:') {
|
||||||
|
if (parsed.pathname === '/') {
|
||||||
|
return parsed.host;
|
||||||
|
} else {
|
||||||
|
return parsed.host + parsed.pathname;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return parsed.href;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Relay List */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
{relays.map((relay) => (
|
||||||
|
<div
|
||||||
|
key={relay.url}
|
||||||
|
className="flex items-center gap-3 p-3 rounded-md border bg-muted/20"
|
||||||
|
>
|
||||||
|
<Wifi className="h-4 w-4 text-muted-foreground shrink-0" />
|
||||||
|
<span className="font-mono text-sm flex-1 truncate" title={relay.url}>
|
||||||
|
{renderRelayUrl(relay.url)}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
{/* Settings Popover */}
|
||||||
|
<Popover>
|
||||||
|
<PopoverTrigger asChild>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="size-5 text-muted-foreground hover:text-foreground shrink-0"
|
||||||
|
>
|
||||||
|
<Settings className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</PopoverTrigger>
|
||||||
|
<PopoverContent className="w-48" align="end">
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label htmlFor={`read-${relay.url}`} className="text-sm cursor-pointer">
|
||||||
|
Read
|
||||||
|
</Label>
|
||||||
|
<Switch
|
||||||
|
id={`read-${relay.url}`}
|
||||||
|
checked={relay.read}
|
||||||
|
onCheckedChange={() => handleToggleRead(relay.url)}
|
||||||
|
className="data-[state=checked]:bg-green-500 scale-75"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<Label htmlFor={`write-${relay.url}`} className="text-sm cursor-pointer">
|
||||||
|
Write
|
||||||
|
</Label>
|
||||||
|
<Switch
|
||||||
|
id={`write-${relay.url}`}
|
||||||
|
checked={relay.write}
|
||||||
|
onCheckedChange={() => handleToggleWrite(relay.url)}
|
||||||
|
className="data-[state=checked]:bg-blue-500 scale-75"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</PopoverContent>
|
||||||
|
</Popover>
|
||||||
|
|
||||||
|
{/* Remove Button */}
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => handleRemoveRelay(relay.url)}
|
||||||
|
className="size-5 text-muted-foreground hover:text-destructive hover:bg-transparent shrink-0"
|
||||||
|
disabled={relays.length <= 1}
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Add Relay Form */}
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<div className="flex-1">
|
||||||
|
<Label htmlFor="new-relay-url" className="sr-only">
|
||||||
|
Relay URL
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
id="new-relay-url"
|
||||||
|
placeholder="Enter relay URL (e.g., wss://relay.example.com)"
|
||||||
|
value={newRelayUrl}
|
||||||
|
onChange={(e) => setNewRelayUrl(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
handleAddRelay();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
onClick={handleAddRelay}
|
||||||
|
disabled={!newRelayUrl.trim()}
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="h-10 shrink-0"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4 mr-2" />
|
||||||
|
Add Relay
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!user && (
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Log in to sync your relay list with Nostr
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,174 +0,0 @@
|
|||||||
import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react";
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import {
|
|
||||||
Command,
|
|
||||||
CommandEmpty,
|
|
||||||
CommandGroup,
|
|
||||||
CommandInput,
|
|
||||||
CommandItem,
|
|
||||||
CommandList,
|
|
||||||
} from "@/components/ui/command";
|
|
||||||
import {
|
|
||||||
Popover,
|
|
||||||
PopoverContent,
|
|
||||||
PopoverTrigger,
|
|
||||||
} from "@/components/ui/popover";
|
|
||||||
import { useState } from "react";
|
|
||||||
import { useAppContext } from "@/hooks/useAppContext";
|
|
||||||
|
|
||||||
interface RelaySelectorProps {
|
|
||||||
className?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function RelaySelector(props: RelaySelectorProps) {
|
|
||||||
const { className } = props;
|
|
||||||
const { config, updateConfig, presetRelays = [] } = useAppContext();
|
|
||||||
|
|
||||||
const selectedRelay = config.relayUrl;
|
|
||||||
const setSelectedRelay = (relay: string) => {
|
|
||||||
updateConfig((current) => ({ ...current, relayUrl: relay }));
|
|
||||||
};
|
|
||||||
|
|
||||||
const [open, setOpen] = useState(false);
|
|
||||||
const [inputValue, setInputValue] = useState("");
|
|
||||||
|
|
||||||
const selectedOption = presetRelays.find((option) => option.url === selectedRelay);
|
|
||||||
|
|
||||||
// Function to normalize relay URL by adding wss:// if no protocol is present
|
|
||||||
const normalizeRelayUrl = (url: string): string => {
|
|
||||||
const trimmed = url.trim();
|
|
||||||
if (!trimmed) return trimmed;
|
|
||||||
|
|
||||||
// Check if it already has a protocol
|
|
||||||
if (trimmed.includes('://')) {
|
|
||||||
return trimmed;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add wss:// prefix
|
|
||||||
return `wss://${trimmed}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Handle adding a custom relay
|
|
||||||
const handleAddCustomRelay = (url: string) => {
|
|
||||||
setSelectedRelay?.(normalizeRelayUrl(url));
|
|
||||||
setOpen(false);
|
|
||||||
setInputValue("");
|
|
||||||
};
|
|
||||||
|
|
||||||
// Check if input value looks like a valid relay URL
|
|
||||||
const isValidRelayInput = (value: string): boolean => {
|
|
||||||
const trimmed = value.trim();
|
|
||||||
if (!trimmed) return false;
|
|
||||||
|
|
||||||
// Basic validation - should contain at least a domain-like structure
|
|
||||||
const normalized = normalizeRelayUrl(trimmed);
|
|
||||||
try {
|
|
||||||
new URL(normalized);
|
|
||||||
return true;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Popover open={open} onOpenChange={setOpen}>
|
|
||||||
<PopoverTrigger asChild>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
role="combobox"
|
|
||||||
aria-expanded={open}
|
|
||||||
className={cn("justify-between", className)}
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Wifi className="h-4 w-4" />
|
|
||||||
<span className="truncate">
|
|
||||||
{selectedOption
|
|
||||||
? selectedOption.name
|
|
||||||
: selectedRelay
|
|
||||||
? selectedRelay.replace(/^wss?:\/\//, '')
|
|
||||||
: "Select relay..."
|
|
||||||
}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
|
||||||
</Button>
|
|
||||||
</PopoverTrigger>
|
|
||||||
<PopoverContent className="w-[300px] p-0">
|
|
||||||
<Command>
|
|
||||||
<CommandInput
|
|
||||||
placeholder="Search relays or type URL..."
|
|
||||||
value={inputValue}
|
|
||||||
onValueChange={setInputValue}
|
|
||||||
/>
|
|
||||||
<CommandList>
|
|
||||||
<CommandEmpty>
|
|
||||||
{inputValue && isValidRelayInput(inputValue) ? (
|
|
||||||
<CommandItem
|
|
||||||
onSelect={() => handleAddCustomRelay(inputValue)}
|
|
||||||
className="cursor-pointer"
|
|
||||||
>
|
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
|
||||||
<div className="flex flex-col">
|
|
||||||
<span className="font-medium">Add custom relay</span>
|
|
||||||
<span className="text-xs text-muted-foreground">
|
|
||||||
{normalizeRelayUrl(inputValue)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</CommandItem>
|
|
||||||
) : (
|
|
||||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
|
||||||
{inputValue ? "Invalid relay URL" : "No relay found."}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CommandEmpty>
|
|
||||||
<CommandGroup>
|
|
||||||
{presetRelays
|
|
||||||
.filter((option) =>
|
|
||||||
!inputValue ||
|
|
||||||
option.name.toLowerCase().includes(inputValue.toLowerCase()) ||
|
|
||||||
option.url.toLowerCase().includes(inputValue.toLowerCase())
|
|
||||||
)
|
|
||||||
.map((option) => (
|
|
||||||
<CommandItem
|
|
||||||
key={option.url}
|
|
||||||
value={option.url}
|
|
||||||
onSelect={(currentValue) => {
|
|
||||||
setSelectedRelay(normalizeRelayUrl(currentValue));
|
|
||||||
setOpen(false);
|
|
||||||
setInputValue("");
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Check
|
|
||||||
className={cn(
|
|
||||||
"mr-2 h-4 w-4",
|
|
||||||
selectedRelay === option.url ? "opacity-100" : "opacity-0"
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<div className="flex flex-col">
|
|
||||||
<span className="font-medium">{option.name}</span>
|
|
||||||
<span className="text-xs text-muted-foreground">{option.url}</span>
|
|
||||||
</div>
|
|
||||||
</CommandItem>
|
|
||||||
))}
|
|
||||||
{inputValue && isValidRelayInput(inputValue) && (
|
|
||||||
<CommandItem
|
|
||||||
onSelect={() => handleAddCustomRelay(inputValue)}
|
|
||||||
className="cursor-pointer border-t"
|
|
||||||
>
|
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
|
||||||
<div className="flex flex-col">
|
|
||||||
<span className="font-medium">Add custom relay</span>
|
|
||||||
<span className="text-xs text-muted-foreground">
|
|
||||||
{normalizeRelayUrl(inputValue)}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</CommandItem>
|
|
||||||
)}
|
|
||||||
</CommandGroup>
|
|
||||||
</CommandList>
|
|
||||||
</Command>
|
|
||||||
</PopoverContent>
|
|
||||||
</Popover>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -10,7 +10,6 @@ import {
|
|||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu.tsx';
|
} from '@/components/ui/dropdown-menu.tsx';
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
|
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar.tsx';
|
||||||
import { RelaySelector } from '@/components/RelaySelector';
|
|
||||||
import { WalletModal } from '@/components/WalletModal';
|
import { WalletModal } from '@/components/WalletModal';
|
||||||
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
|
import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts';
|
||||||
import { genUserName } from '@/lib/genUserName';
|
import { genUserName } from '@/lib/genUserName';
|
||||||
@@ -43,9 +42,6 @@ export function AccountSwitcher({ onAddAccountClick }: AccountSwitcherProps) {
|
|||||||
</button>
|
</button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
|
<DropdownMenuContent className='w-56 p-2 animate-scale-in'>
|
||||||
<div className='font-medium text-sm px-2 py-1.5'>Switch Relay</div>
|
|
||||||
<RelaySelector className="w-full" />
|
|
||||||
<DropdownMenuSeparator />
|
|
||||||
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
|
<div className='font-medium text-sm px-2 py-1.5'>Switch Account</div>
|
||||||
{otherUsers.map((user) => (
|
{otherUsers.map((user) => (
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
|
|||||||
@@ -1,14 +1,21 @@
|
|||||||
// NOTE: This file is stable and usually should not be modified.
|
// NOTE: This file is stable and usually should not be modified.
|
||||||
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
||||||
|
|
||||||
import React, { useRef, useState, useEffect } from 'react';
|
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
|
import { QRCodeSVG } from 'qrcode.react';
|
||||||
|
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Loader2, Copy, Check, ChevronDown, ChevronUp, Link, ExternalLink } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
|
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
import {
|
||||||
|
useLoginActions,
|
||||||
|
generateNostrConnectParams,
|
||||||
|
generateNostrConnectURI,
|
||||||
|
type NostrConnectParams,
|
||||||
|
} from '@/hooks/useLoginActions';
|
||||||
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
interface LoginDialogProps {
|
interface LoginDialogProps {
|
||||||
@@ -23,7 +30,7 @@ const validateNsec = (nsec: string) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const validateBunkerUri = (uri: string) => {
|
const validateBunkerUri = (uri: string) => {
|
||||||
return uri.startsWith('bunker://');
|
return uri.startsWith('bunker://') || uri.startsWith('nostrconnect://');
|
||||||
};
|
};
|
||||||
|
|
||||||
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
|
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
|
||||||
@@ -31,6 +38,12 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
|||||||
const [isFileLoading, setIsFileLoading] = useState(false);
|
const [isFileLoading, setIsFileLoading] = useState(false);
|
||||||
const [nsec, setNsec] = useState('');
|
const [nsec, setNsec] = useState('');
|
||||||
const [bunkerUri, setBunkerUri] = useState('');
|
const [bunkerUri, setBunkerUri] = useState('');
|
||||||
|
const [nostrConnectParams, setNostrConnectParams] = useState<NostrConnectParams | null>(null);
|
||||||
|
const [nostrConnectUri, setNostrConnectUri] = useState<string>('');
|
||||||
|
const [isWaitingForConnect, setIsWaitingForConnect] = useState(false);
|
||||||
|
const [connectError, setConnectError] = useState<string | null>(null);
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
const [showBunkerInput, setShowBunkerInput] = useState(false);
|
||||||
const [errors, setErrors] = useState<{
|
const [errors, setErrors] = useState<{
|
||||||
nsec?: string;
|
nsec?: string;
|
||||||
bunker?: string;
|
bunker?: string;
|
||||||
@@ -38,17 +51,63 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
|||||||
extension?: string;
|
extension?: string;
|
||||||
}>({});
|
}>({});
|
||||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const abortControllerRef = useRef<AbortController | null>(null);
|
||||||
const login = useLoginActions();
|
const login = useLoginActions();
|
||||||
|
|
||||||
|
// Check if on mobile device
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
// Check if extension is available
|
||||||
|
const hasExtension = 'nostr' in window;
|
||||||
|
|
||||||
|
// Generate nostrconnect params (sync) - just creates the QR code data
|
||||||
|
const generateConnectSession = useCallback(() => {
|
||||||
|
const relayUrl = login.getRelayUrl();
|
||||||
|
const params = generateNostrConnectParams([relayUrl]);
|
||||||
|
const uri = generateNostrConnectURI(params, 'MKStack');
|
||||||
|
setNostrConnectParams(params);
|
||||||
|
setNostrConnectUri(uri);
|
||||||
|
setConnectError(null);
|
||||||
|
}, [login]);
|
||||||
|
|
||||||
|
// Start listening for connection (async) - runs after params are set
|
||||||
|
useEffect(() => {
|
||||||
|
if (!nostrConnectParams || isWaitingForConnect) return;
|
||||||
|
|
||||||
|
const startListening = async () => {
|
||||||
|
setIsWaitingForConnect(true);
|
||||||
|
abortControllerRef.current = new AbortController();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await login.nostrconnect(nostrConnectParams);
|
||||||
|
onLogin();
|
||||||
|
onClose();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Nostrconnect failed:', error);
|
||||||
|
setConnectError(error instanceof Error ? error.message : 'Connection failed');
|
||||||
|
setIsWaitingForConnect(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
startListening();
|
||||||
|
}, [nostrConnectParams, login, onLogin, onClose, isWaitingForConnect]);
|
||||||
|
|
||||||
// Reset all state when dialog opens/closes
|
// Reset all state when dialog opens/closes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isOpen) {
|
if (!isOpen) {
|
||||||
// Reset state when dialog opens
|
// Reset state when dialog closes
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
setIsFileLoading(false);
|
setIsFileLoading(false);
|
||||||
setNsec('');
|
setNsec('');
|
||||||
setBunkerUri('');
|
setBunkerUri('');
|
||||||
|
setNostrConnectParams(null);
|
||||||
|
setNostrConnectUri('');
|
||||||
|
setIsWaitingForConnect(false);
|
||||||
|
setConnectError(null);
|
||||||
|
setShowBunkerInput(false);
|
||||||
setErrors({});
|
setErrors({});
|
||||||
|
if (abortControllerRef.current) {
|
||||||
|
abortControllerRef.current.abort();
|
||||||
|
}
|
||||||
// Reset file input
|
// Reset file input
|
||||||
if (fileInputRef.current) {
|
if (fileInputRef.current) {
|
||||||
fileInputRef.current.value = '';
|
fileInputRef.current.value = '';
|
||||||
@@ -56,6 +115,29 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
|||||||
}
|
}
|
||||||
}, [isOpen]);
|
}, [isOpen]);
|
||||||
|
|
||||||
|
// Retry connection with new params
|
||||||
|
const handleRetry = useCallback(() => {
|
||||||
|
setNostrConnectParams(null);
|
||||||
|
setNostrConnectUri('');
|
||||||
|
setIsWaitingForConnect(false);
|
||||||
|
setConnectError(null);
|
||||||
|
// Generate new session after state clears
|
||||||
|
setTimeout(() => generateConnectSession(), 0);
|
||||||
|
}, [generateConnectSession]);
|
||||||
|
|
||||||
|
const handleCopyUri = async () => {
|
||||||
|
await navigator.clipboard.writeText(nostrConnectUri);
|
||||||
|
setCopied(true);
|
||||||
|
setTimeout(() => setCopied(false), 2000);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Open the nostrconnect URI in the system - this will launch a signer app like Amber if installed
|
||||||
|
const handleOpenSignerApp = () => {
|
||||||
|
if (!nostrConnectUri) return;
|
||||||
|
// On mobile, this will trigger the system to find an app that handles nostrconnect:// URIs
|
||||||
|
window.location.href = nostrConnectUri;
|
||||||
|
};
|
||||||
|
|
||||||
const handleExtensionLogin = async () => {
|
const handleExtensionLogin = async () => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setErrors(prev => ({ ...prev, extension: undefined }));
|
setErrors(prev => ({ ...prev, extension: undefined }));
|
||||||
@@ -69,8 +151,6 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
|||||||
onClose();
|
onClose();
|
||||||
} catch (e: unknown) {
|
} catch (e: unknown) {
|
||||||
const error = e as Error;
|
const error = e as Error;
|
||||||
console.error('Bunker login failed:', error);
|
|
||||||
console.error('Nsec login failed:', error);
|
|
||||||
console.error('Extension login failed:', error);
|
console.error('Extension login failed:', error);
|
||||||
setErrors(prev => ({
|
setErrors(prev => ({
|
||||||
...prev,
|
...prev,
|
||||||
@@ -118,7 +198,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!validateBunkerUri(bunkerUri)) {
|
if (!validateBunkerUri(bunkerUri)) {
|
||||||
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
|
setErrors(prev => ({ ...prev, bunker: 'Invalid URI format. Must start with bunker:// or nostrconnect://' }));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,7 +257,7 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const defaultTab = 'nostr' in window ? 'extension' : 'key';
|
const defaultTab = hasExtension ? 'extension' : 'connect';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||||
@@ -226,21 +306,30 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Login Methods */}
|
{/* Login Methods */}
|
||||||
<Tabs defaultValue={defaultTab} className="w-full">
|
<Tabs
|
||||||
|
defaultValue={defaultTab}
|
||||||
|
className="w-full"
|
||||||
|
onValueChange={(value) => {
|
||||||
|
if (value === 'connect' && !nostrConnectParams && !connectError) {
|
||||||
|
generateConnectSession();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
<TabsList className="grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4">
|
<TabsList className="grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4">
|
||||||
<TabsTrigger value="extension" className="flex items-center gap-2">
|
<TabsTrigger value="extension" className="flex items-center gap-2">
|
||||||
<Shield className="w-4 h-4" />
|
<Shield className="w-4 h-4" />
|
||||||
<span>Extension</span>
|
<span>Extension</span>
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
|
<TabsTrigger value="connect" className="flex items-center gap-2">
|
||||||
|
<Link className="w-4 h-4" />
|
||||||
|
<span>Connect</span>
|
||||||
|
</TabsTrigger>
|
||||||
<TabsTrigger value="key" className="flex items-center gap-2">
|
<TabsTrigger value="key" className="flex items-center gap-2">
|
||||||
<KeyRound className="w-4 h-4" />
|
<KeyRound className="w-4 h-4" />
|
||||||
<span>Key</span>
|
<span>Key</span>
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
<TabsTrigger value="bunker" className="flex items-center gap-2">
|
|
||||||
<Cloud className="w-4 h-4" />
|
|
||||||
<span>Bunker</span>
|
|
||||||
</TabsTrigger>
|
|
||||||
</TabsList>
|
</TabsList>
|
||||||
|
|
||||||
<TabsContent value='extension' className='space-y-3 bg-muted'>
|
<TabsContent value='extension' className='space-y-3 bg-muted'>
|
||||||
{errors.extension && (
|
{errors.extension && (
|
||||||
<Alert variant="destructive">
|
<Alert variant="destructive">
|
||||||
@@ -265,6 +354,123 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
|||||||
</div>
|
</div>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
|
<TabsContent value='connect' className='space-y-4'>
|
||||||
|
{/* Nostrconnect Section */}
|
||||||
|
<div className='flex flex-col items-center space-y-4'>
|
||||||
|
{connectError ? (
|
||||||
|
<div className='flex flex-col items-center space-y-4 py-4'>
|
||||||
|
<p className='text-sm text-red-500 text-center'>{connectError}</p>
|
||||||
|
<Button variant='outline' onClick={handleRetry}>
|
||||||
|
Try Again
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : nostrConnectUri ? (
|
||||||
|
<>
|
||||||
|
{/* QR Code - only show on desktop */}
|
||||||
|
{!isMobile && (
|
||||||
|
<div className='p-4 bg-white rounded-xl'>
|
||||||
|
<QRCodeSVG
|
||||||
|
value={nostrConnectUri}
|
||||||
|
size={180}
|
||||||
|
level='M'
|
||||||
|
includeMargin={false}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Status message */}
|
||||||
|
<div className='flex items-center gap-2 text-sm text-muted-foreground'>
|
||||||
|
{isWaitingForConnect ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className='w-4 h-4 animate-spin' />
|
||||||
|
<span>Waiting for connection...</span>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<span>{isMobile ? 'Open your signer app to connect' : 'Scan with your signer app'}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Open Signer App button - primary action on mobile */}
|
||||||
|
{isMobile && (
|
||||||
|
<Button
|
||||||
|
className='w-full gap-2 py-6 rounded-full'
|
||||||
|
onClick={handleOpenSignerApp}
|
||||||
|
>
|
||||||
|
<ExternalLink className='w-5 h-5' />
|
||||||
|
Open Signer App
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Copy button */}
|
||||||
|
<Button
|
||||||
|
variant='outline'
|
||||||
|
size={isMobile ? 'default' : 'sm'}
|
||||||
|
className={isMobile ? 'w-full gap-2 rounded-full' : 'gap-2'}
|
||||||
|
onClick={handleCopyUri}
|
||||||
|
>
|
||||||
|
{copied ? (
|
||||||
|
<>
|
||||||
|
<Check className='w-4 h-4' />
|
||||||
|
Copied!
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Copy className='w-4 h-4' />
|
||||||
|
Copy Connection String
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className='flex items-center justify-center h-[100px]'>
|
||||||
|
<Loader2 className='w-8 h-8 animate-spin text-muted-foreground' />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Manual URI input section - collapsible */}
|
||||||
|
<div className='pt-4 border-t border-gray-200 dark:border-gray-700'>
|
||||||
|
<button
|
||||||
|
type='button'
|
||||||
|
onClick={() => setShowBunkerInput(!showBunkerInput)}
|
||||||
|
className='flex items-center justify-center gap-2 w-full text-sm text-muted-foreground hover:text-foreground transition-colors py-2'
|
||||||
|
>
|
||||||
|
<span>Manual bunker connection</span>
|
||||||
|
{showBunkerInput ? (
|
||||||
|
<ChevronUp className='w-4 h-4' />
|
||||||
|
) : (
|
||||||
|
<ChevronDown className='w-4 h-4' />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{showBunkerInput && (
|
||||||
|
<div className='space-y-3 mt-3'>
|
||||||
|
<div className='space-y-2'>
|
||||||
|
<Input
|
||||||
|
id='connectBunkerUri'
|
||||||
|
value={bunkerUri}
|
||||||
|
onChange={(e) => setBunkerUri(e.target.value)}
|
||||||
|
className='rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary text-sm'
|
||||||
|
placeholder='bunker://'
|
||||||
|
/>
|
||||||
|
{bunkerUri && !validateBunkerUri(bunkerUri) && (
|
||||||
|
<p className='text-red-500 text-xs'>URI must start with bunker:// or nostrconnect://</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
className='w-full rounded-full py-4'
|
||||||
|
variant='outline'
|
||||||
|
onClick={handleBunkerLogin}
|
||||||
|
disabled={isLoading || !bunkerUri.trim() || !validateBunkerUri(bunkerUri)}
|
||||||
|
>
|
||||||
|
{isLoading ? 'Connecting...' : 'Connect with Bunker'}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
<TabsContent value='key' className='space-y-4'>
|
<TabsContent value='key' className='space-y-4'>
|
||||||
<div className='space-y-4'>
|
<div className='space-y-4'>
|
||||||
<div className='space-y-2'>
|
<div className='space-y-2'>
|
||||||
@@ -333,39 +539,6 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
|||||||
</div>
|
</div>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
<TabsContent value='bunker' className='space-y-3 bg-muted'>
|
|
||||||
<div className='space-y-2'>
|
|
||||||
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
|
|
||||||
Bunker URI
|
|
||||||
</label>
|
|
||||||
<Input
|
|
||||||
id='bunkerUri'
|
|
||||||
value={bunkerUri}
|
|
||||||
onChange={(e) => {
|
|
||||||
setBunkerUri(e.target.value);
|
|
||||||
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
|
|
||||||
}}
|
|
||||||
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
|
|
||||||
errors.bunker ? 'border-red-500' : ''
|
|
||||||
}`}
|
|
||||||
placeholder='bunker://'
|
|
||||||
autoComplete="off"
|
|
||||||
/>
|
|
||||||
{errors.bunker && (
|
|
||||||
<p className="text-sm text-red-500">{errors.bunker}</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex justify-center">
|
|
||||||
<Button
|
|
||||||
className='w-full rounded-full py-4'
|
|
||||||
onClick={handleBunkerLogin}
|
|
||||||
disabled={isLoading || !bunkerUri.trim()}
|
|
||||||
>
|
|
||||||
{isLoading ? 'Connecting...' : 'Login with Bunker'}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</TabsContent>
|
|
||||||
</Tabs>
|
</Tabs>
|
||||||
</div>
|
</div>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
|
|||||||
@@ -0,0 +1,409 @@
|
|||||||
|
import { useState, useRef, useEffect, useCallback, memo } from 'react';
|
||||||
|
import { useConversationMessages } from '@/hooks/useConversationMessages';
|
||||||
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
|
import { useAuthor } from '@/hooks/useAuthor';
|
||||||
|
import { genUserName } from '@/lib/genUserName';
|
||||||
|
import { MESSAGE_PROTOCOL, PROTOCOL_MODE, type MessageProtocol } from '@/lib/dmConstants';
|
||||||
|
import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils';
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Card } from '@/components/ui/card';
|
||||||
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
|
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||||
|
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||||
|
import { ArrowLeft, Send, Loader2, AlertTriangle, Key, ShieldCheck } from 'lucide-react';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { NoteContent } from '@/components/NoteContent';
|
||||||
|
import type { NostrEvent } from '@nostrify/nostrify';
|
||||||
|
|
||||||
|
interface DMChatAreaProps {
|
||||||
|
pubkey: string | null;
|
||||||
|
onBack?: () => void;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MessageBubble = memo(({
|
||||||
|
message,
|
||||||
|
isFromCurrentUser
|
||||||
|
}: {
|
||||||
|
message: {
|
||||||
|
id: string;
|
||||||
|
pubkey: string;
|
||||||
|
kind: number;
|
||||||
|
tags: string[][];
|
||||||
|
decryptedContent?: string;
|
||||||
|
decryptedEvent?: NostrEvent;
|
||||||
|
error?: string;
|
||||||
|
created_at: number;
|
||||||
|
isSending?: boolean;
|
||||||
|
};
|
||||||
|
isFromCurrentUser: boolean;
|
||||||
|
}) => {
|
||||||
|
// For NIP-17, use inner message kind (14/15); for NIP-04, use message kind (4)
|
||||||
|
const actualKind = message.decryptedEvent?.kind || message.kind;
|
||||||
|
const isNIP4Message = message.kind === 4;
|
||||||
|
const isFileAttachment = actualKind === 15; // Kind 15 = files/attachments
|
||||||
|
|
||||||
|
// Create a NostrEvent object for NoteContent (only used for kind 15)
|
||||||
|
// For NIP-17 file attachments, use the decryptedEvent which has the actual tags
|
||||||
|
const messageEvent: NostrEvent = message.decryptedEvent || {
|
||||||
|
id: message.id,
|
||||||
|
pubkey: message.pubkey,
|
||||||
|
created_at: message.created_at,
|
||||||
|
kind: message.kind,
|
||||||
|
tags: message.tags,
|
||||||
|
content: message.decryptedContent || '',
|
||||||
|
sig: '', // Not needed for display
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn("flex mb-4", isFromCurrentUser ? "justify-end" : "justify-start")}>
|
||||||
|
<div className={cn(
|
||||||
|
"max-w-[70%] rounded-lg px-4 py-2",
|
||||||
|
isFromCurrentUser
|
||||||
|
? "bg-primary text-primary-foreground"
|
||||||
|
: "bg-muted"
|
||||||
|
)}>
|
||||||
|
{message.error ? (
|
||||||
|
<Tooltip delayDuration={200}>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<p className="text-sm italic opacity-70 cursor-help">🔒 Failed to decrypt</p>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>
|
||||||
|
<p className="text-xs">{message.error}</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
) : isFileAttachment ? (
|
||||||
|
// Kind 15: Use NoteContent to render files/media with imeta tags
|
||||||
|
<div className="text-sm">
|
||||||
|
<NoteContent event={messageEvent} className="whitespace-pre-wrap break-words" />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
// Kind 4 (NIP-04) and Kind 14 (NIP-17 text): Display plain text
|
||||||
|
<p className="text-sm whitespace-pre-wrap break-words">
|
||||||
|
{message.decryptedContent}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center gap-2 mt-1">
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip delayDuration={200}>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<span className={cn(
|
||||||
|
"text-xs opacity-70 cursor-default",
|
||||||
|
isFromCurrentUser ? "text-primary-foreground" : "text-muted-foreground"
|
||||||
|
)}>
|
||||||
|
{formatConversationTime(message.created_at)}
|
||||||
|
</span>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>
|
||||||
|
<p className="text-xs">{formatFullDateTime(message.created_at)}</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip delayDuration={200}>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<span className={cn(
|
||||||
|
"flex-shrink-0 opacity-50",
|
||||||
|
isFromCurrentUser ? "text-primary-foreground" : "text-muted-foreground"
|
||||||
|
)}>
|
||||||
|
{message.kind === 4 ? (
|
||||||
|
<Key className="h-3 w-3" />
|
||||||
|
) : (
|
||||||
|
<ShieldCheck className="h-3 w-3" />
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>
|
||||||
|
<p className="text-xs">
|
||||||
|
{message.kind === 4 && "NIP-04 Kind 4 (Legacy DM)"}
|
||||||
|
{message.kind === 14 && "NIP-17 Kind 14 (Private Message)"}
|
||||||
|
{message.kind === 15 && "NIP-17 Kind 15 (Media)"}
|
||||||
|
{message.kind !== 4 && message.kind !== 14 && message.kind !== 15 && `Kind ${message.kind}`}
|
||||||
|
</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
{isNIP4Message && (
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<div className="flex-shrink-0">
|
||||||
|
<AlertTriangle className="h-3 w-3 text-yellow-600 dark:text-yellow-500" />
|
||||||
|
</div>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>
|
||||||
|
<p className="text-xs">Uses outdated NIP-04 encryption</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
)}
|
||||||
|
{message.isSending && (
|
||||||
|
<Loader2 className="h-3 w-3 animate-spin opacity-70" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
MessageBubble.displayName = 'MessageBubble';
|
||||||
|
|
||||||
|
const ChatHeader = ({ pubkey, onBack }: { pubkey: string; onBack?: () => void }) => {
|
||||||
|
const author = useAuthor(pubkey);
|
||||||
|
const metadata = author.data?.metadata;
|
||||||
|
|
||||||
|
const displayName = metadata?.name || genUserName(pubkey);
|
||||||
|
const avatarUrl = metadata?.picture;
|
||||||
|
const initials = displayName.slice(0, 2).toUpperCase();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="p-4 border-b flex items-center gap-3">
|
||||||
|
{onBack && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
onClick={onBack}
|
||||||
|
className="md:hidden"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-5 w-5" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Avatar className="h-10 w-10">
|
||||||
|
<AvatarImage src={avatarUrl} alt={displayName} />
|
||||||
|
<AvatarFallback>{initials}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<h2 className="font-semibold truncate">{displayName}</h2>
|
||||||
|
{metadata?.nip05 && (
|
||||||
|
<p className="text-xs text-muted-foreground truncate">{metadata.nip05}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const EmptyState = ({ isLoading }: { isLoading: boolean }) => {
|
||||||
|
return (
|
||||||
|
<div className="h-full flex items-center justify-center p-8">
|
||||||
|
<div className="text-center text-muted-foreground max-w-sm">
|
||||||
|
{isLoading ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
|
||||||
|
<p className="text-sm">Loading conversations...</p>
|
||||||
|
<p className="text-xs mt-2">
|
||||||
|
Fetching encrypted messages from relays
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<p className="text-sm">Select a conversation to start messaging</p>
|
||||||
|
<p className="text-xs mt-2">
|
||||||
|
Your messages are encrypted and stored locally
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const DMChatArea = ({ pubkey, onBack, className }: DMChatAreaProps) => {
|
||||||
|
const { user } = useCurrentUser();
|
||||||
|
const { sendMessage, protocolMode, isLoading } = useDMContext();
|
||||||
|
const { messages, hasMoreMessages, loadEarlierMessages } = useConversationMessages(pubkey || '');
|
||||||
|
|
||||||
|
const [messageText, setMessageText] = useState('');
|
||||||
|
const [isSending, setIsSending] = useState(false);
|
||||||
|
const [isLoadingMore, setIsLoadingMore] = useState(false);
|
||||||
|
|
||||||
|
// Determine default protocol based on mode
|
||||||
|
const getDefaultProtocol = () => {
|
||||||
|
if (protocolMode === PROTOCOL_MODE.NIP04_ONLY) return MESSAGE_PROTOCOL.NIP04;
|
||||||
|
if (protocolMode === PROTOCOL_MODE.NIP17_ONLY) return MESSAGE_PROTOCOL.NIP17;
|
||||||
|
if (protocolMode === PROTOCOL_MODE.NIP04_OR_NIP17) return MESSAGE_PROTOCOL.NIP17;
|
||||||
|
// Fallback to NIP-17 for any unexpected mode
|
||||||
|
return MESSAGE_PROTOCOL.NIP17;
|
||||||
|
};
|
||||||
|
|
||||||
|
const [selectedProtocol, setSelectedProtocol] = useState<MessageProtocol>(getDefaultProtocol());
|
||||||
|
const scrollAreaRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// Determine if selection is allowed
|
||||||
|
const allowSelection = protocolMode === PROTOCOL_MODE.NIP04_OR_NIP17;
|
||||||
|
|
||||||
|
// Auto-scroll to bottom when new messages arrive
|
||||||
|
useEffect(() => {
|
||||||
|
if (scrollAreaRef.current) {
|
||||||
|
const scrollContainer = scrollAreaRef.current.querySelector('[data-radix-scroll-area-viewport]');
|
||||||
|
if (scrollContainer) {
|
||||||
|
scrollContainer.scrollTop = scrollContainer.scrollHeight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [messages.length]);
|
||||||
|
|
||||||
|
const handleSend = useCallback(async () => {
|
||||||
|
if (!messageText.trim() || !pubkey || !user) return;
|
||||||
|
|
||||||
|
setIsSending(true);
|
||||||
|
try {
|
||||||
|
await sendMessage({
|
||||||
|
recipientPubkey: pubkey,
|
||||||
|
content: messageText.trim(),
|
||||||
|
protocol: selectedProtocol,
|
||||||
|
});
|
||||||
|
setMessageText('');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to send message:', error);
|
||||||
|
} finally {
|
||||||
|
setIsSending(false);
|
||||||
|
}
|
||||||
|
}, [messageText, pubkey, user, sendMessage, selectedProtocol]);
|
||||||
|
|
||||||
|
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||||
|
if (e.key === 'Enter' && !e.shiftKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
handleSend();
|
||||||
|
}
|
||||||
|
}, [handleSend]);
|
||||||
|
|
||||||
|
const handleLoadMore = useCallback(async () => {
|
||||||
|
if (!scrollAreaRef.current || isLoadingMore) return;
|
||||||
|
|
||||||
|
const scrollContainer = scrollAreaRef.current.querySelector('[data-radix-scroll-area-viewport]');
|
||||||
|
if (!scrollContainer) return;
|
||||||
|
|
||||||
|
// Store current scroll position and height
|
||||||
|
const previousScrollHeight = scrollContainer.scrollHeight;
|
||||||
|
const previousScrollTop = scrollContainer.scrollTop;
|
||||||
|
|
||||||
|
setIsLoadingMore(true);
|
||||||
|
|
||||||
|
// Load more messages
|
||||||
|
loadEarlierMessages();
|
||||||
|
|
||||||
|
// Wait for DOM to update, then restore relative scroll position
|
||||||
|
setTimeout(() => {
|
||||||
|
if (scrollContainer) {
|
||||||
|
const newScrollHeight = scrollContainer.scrollHeight;
|
||||||
|
const heightDifference = newScrollHeight - previousScrollHeight;
|
||||||
|
scrollContainer.scrollTop = previousScrollTop + heightDifference;
|
||||||
|
}
|
||||||
|
setIsLoadingMore(false);
|
||||||
|
}, 0);
|
||||||
|
}, [loadEarlierMessages, isLoadingMore]);
|
||||||
|
|
||||||
|
if (!pubkey) {
|
||||||
|
return (
|
||||||
|
<Card className={cn("h-full", className)}>
|
||||||
|
<EmptyState isLoading={isLoading} />
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return (
|
||||||
|
<Card className={cn("h-full flex items-center justify-center", className)}>
|
||||||
|
<div className="text-center text-muted-foreground">
|
||||||
|
<p className="text-sm">Please log in to view messages</p>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className={cn("h-full flex flex-col", className)}>
|
||||||
|
<ChatHeader pubkey={pubkey} onBack={onBack} />
|
||||||
|
|
||||||
|
<ScrollArea ref={scrollAreaRef} className="flex-1 p-4">
|
||||||
|
{messages.length === 0 ? (
|
||||||
|
<div className="h-full flex items-center justify-center">
|
||||||
|
<div className="text-center text-muted-foreground">
|
||||||
|
<p className="text-sm">No messages yet</p>
|
||||||
|
<p className="text-xs mt-1">Send a message to start the conversation</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div>
|
||||||
|
{hasMoreMessages && (
|
||||||
|
<div className="flex justify-center mb-4">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={handleLoadMore}
|
||||||
|
disabled={isLoadingMore}
|
||||||
|
className="text-xs"
|
||||||
|
>
|
||||||
|
{isLoadingMore ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="h-3 w-3 animate-spin mr-2" />
|
||||||
|
Loading...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
'Load Earlier Messages'
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{messages.map((message) => (
|
||||||
|
<MessageBubble
|
||||||
|
key={message.id}
|
||||||
|
message={message}
|
||||||
|
isFromCurrentUser={message.pubkey === user.pubkey}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</ScrollArea>
|
||||||
|
|
||||||
|
<div className="p-4 border-t">
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Textarea
|
||||||
|
value={messageText}
|
||||||
|
onChange={(e) => setMessageText(e.target.value)}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
placeholder="Type a message... (Enter to send, Shift+Enter for new line)"
|
||||||
|
className="min-h-[80px] resize-none"
|
||||||
|
disabled={isSending}
|
||||||
|
/>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Button
|
||||||
|
onClick={handleSend}
|
||||||
|
disabled={!messageText.trim() || isSending}
|
||||||
|
size="icon"
|
||||||
|
className="h-[44px] w-[90px]"
|
||||||
|
>
|
||||||
|
{isSending ? (
|
||||||
|
<Loader2 className="h-5 w-5 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Send className="h-5 w-5" />
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
<Select
|
||||||
|
value={selectedProtocol}
|
||||||
|
onValueChange={(value) => setSelectedProtocol(value as MessageProtocol)}
|
||||||
|
disabled={!allowSelection}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="h-[32px] w-[90px] text-xs px-2">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value={MESSAGE_PROTOCOL.NIP17} className="text-xs">
|
||||||
|
NIP-17
|
||||||
|
</SelectItem>
|
||||||
|
<SelectItem value={MESSAGE_PROTOCOL.NIP04} className="text-xs">
|
||||||
|
NIP-04
|
||||||
|
</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
import { useMemo, useState, memo } from 'react';
|
||||||
|
import { AlertTriangle, Info, Loader2 } from 'lucide-react';
|
||||||
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
|
import { useAuthor } from '@/hooks/useAuthor';
|
||||||
|
import { genUserName } from '@/lib/genUserName';
|
||||||
|
import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils';
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Card } from '@/components/ui/card';
|
||||||
|
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
|
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { LOADING_PHASES } from '@/lib/dmConstants';
|
||||||
|
|
||||||
|
interface DMConversationListProps {
|
||||||
|
selectedPubkey: string | null;
|
||||||
|
onSelectConversation: (pubkey: string) => void;
|
||||||
|
className?: string;
|
||||||
|
onStatusClick?: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ConversationItemProps {
|
||||||
|
pubkey: string;
|
||||||
|
isSelected: boolean;
|
||||||
|
onClick: () => void;
|
||||||
|
lastMessage: { decryptedContent?: string; error?: string } | null;
|
||||||
|
lastActivity: number;
|
||||||
|
hasNIP4Messages: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ConversationItemComponent = ({
|
||||||
|
pubkey,
|
||||||
|
isSelected,
|
||||||
|
onClick,
|
||||||
|
lastMessage,
|
||||||
|
lastActivity,
|
||||||
|
hasNIP4Messages
|
||||||
|
}: ConversationItemProps) => {
|
||||||
|
const author = useAuthor(pubkey);
|
||||||
|
const metadata = author.data?.metadata;
|
||||||
|
|
||||||
|
const displayName = metadata?.name || genUserName(pubkey);
|
||||||
|
const avatarUrl = metadata?.picture;
|
||||||
|
const initials = displayName.slice(0, 2).toUpperCase();
|
||||||
|
|
||||||
|
const lastMessagePreview = lastMessage?.error
|
||||||
|
? '🔒 Encrypted message'
|
||||||
|
: lastMessage?.decryptedContent || 'No messages yet';
|
||||||
|
|
||||||
|
// Show skeleton only for name/avatar while loading (we already have message data)
|
||||||
|
const isLoadingProfile = author.isLoading && !metadata;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
onClick={onClick}
|
||||||
|
className={cn(
|
||||||
|
"w-full text-left p-3 rounded-lg transition-colors hover:bg-accent block overflow-hidden",
|
||||||
|
isSelected && "bg-accent"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="flex items-start gap-3 max-w-full">
|
||||||
|
{isLoadingProfile ? (
|
||||||
|
<Skeleton className="h-10 w-10 rounded-full flex-shrink-0" />
|
||||||
|
) : (
|
||||||
|
<Avatar className="h-10 w-10 flex-shrink-0">
|
||||||
|
<AvatarImage src={avatarUrl} alt={displayName} />
|
||||||
|
<AvatarFallback>{initials}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<div className="flex items-center justify-between gap-2 mb-1">
|
||||||
|
<div className="flex items-center gap-1.5 min-w-0 flex-1">
|
||||||
|
{isLoadingProfile ? (
|
||||||
|
<Skeleton className="h-[1.25rem] w-24" />
|
||||||
|
) : (
|
||||||
|
<span className="font-medium text-sm truncate">{displayName}</span>
|
||||||
|
)}
|
||||||
|
{hasNIP4Messages && (
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<div className="flex-shrink-0">
|
||||||
|
<AlertTriangle className="h-3.5 w-3.5 text-yellow-600 dark:text-yellow-500" />
|
||||||
|
</div>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="left">
|
||||||
|
<p className="text-xs max-w-[200px]">Some messages use outdated NIP-04 encryption</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<span className="text-xs text-muted-foreground whitespace-nowrap flex-shrink-0 cursor-default">
|
||||||
|
{formatConversationTime(lastActivity)}
|
||||||
|
</span>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent side="left">
|
||||||
|
<p className="text-xs">{formatFullDateTime(lastActivity)}</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="text-sm text-muted-foreground truncate">
|
||||||
|
{lastMessagePreview}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const ConversationItem = memo(ConversationItemComponent);
|
||||||
|
ConversationItem.displayName = 'ConversationItem';
|
||||||
|
|
||||||
|
const ConversationListSkeleton = () => {
|
||||||
|
return (
|
||||||
|
<div className="space-y-2 p-4">
|
||||||
|
{[1, 2, 3, 4, 5].map((i) => (
|
||||||
|
<div key={i} className="flex items-start gap-3 p-3">
|
||||||
|
<Skeleton className="h-10 w-10 rounded-full flex-shrink-0" />
|
||||||
|
<div className="flex-1 space-y-2">
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<Skeleton className="h-4 w-24" />
|
||||||
|
<Skeleton className="h-3 w-12" />
|
||||||
|
</div>
|
||||||
|
<Skeleton className="h-3 w-full" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const DMConversationList = ({
|
||||||
|
selectedPubkey,
|
||||||
|
onSelectConversation,
|
||||||
|
className,
|
||||||
|
onStatusClick
|
||||||
|
}: DMConversationListProps) => {
|
||||||
|
const { conversations, isLoading, loadingPhase } = useDMContext();
|
||||||
|
const [activeTab, setActiveTab] = useState<'known' | 'requests'>('known');
|
||||||
|
|
||||||
|
// Filter conversations by type
|
||||||
|
const { knownConversations, requestConversations } = useMemo(() => {
|
||||||
|
return {
|
||||||
|
knownConversations: conversations.filter(c => c.isKnown),
|
||||||
|
requestConversations: conversations.filter(c => c.isRequest),
|
||||||
|
};
|
||||||
|
}, [conversations]);
|
||||||
|
|
||||||
|
// Get the current list based on active tab
|
||||||
|
const currentConversations = activeTab === 'known' ? knownConversations : requestConversations;
|
||||||
|
|
||||||
|
// Show skeleton during initial load (cache + relays) if we have no conversations yet
|
||||||
|
const isInitialLoad = (loadingPhase === LOADING_PHASES.CACHE || loadingPhase === LOADING_PHASES.RELAYS) && conversations.length === 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className={cn("h-full flex flex-col overflow-hidden", className)}>
|
||||||
|
{/* Header - always visible */}
|
||||||
|
<div className="p-4 border-b flex-shrink-0 flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<h2 className="font-semibold text-lg">Messages</h2>
|
||||||
|
{(loadingPhase === LOADING_PHASES.CACHE ||
|
||||||
|
loadingPhase === LOADING_PHASES.RELAYS ||
|
||||||
|
loadingPhase === LOADING_PHASES.SUBSCRIPTIONS) && (
|
||||||
|
<TooltipProvider>
|
||||||
|
<Tooltip>
|
||||||
|
<TooltipTrigger asChild>
|
||||||
|
<div className="flex items-center">
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>
|
||||||
|
<p className="text-xs">
|
||||||
|
{loadingPhase === LOADING_PHASES.CACHE && 'Loading from cache...'}
|
||||||
|
{loadingPhase === LOADING_PHASES.RELAYS && 'Querying relays for new messages...'}
|
||||||
|
{loadingPhase === LOADING_PHASES.SUBSCRIPTIONS && 'Setting up subscriptions...'}
|
||||||
|
</p>
|
||||||
|
</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
|
</TooltipProvider>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{onStatusClick && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-8 w-8"
|
||||||
|
onClick={onStatusClick}
|
||||||
|
aria-label="View messaging status"
|
||||||
|
>
|
||||||
|
<Info className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tab buttons - always visible */}
|
||||||
|
<div className="px-2 pt-2 flex-shrink-0">
|
||||||
|
<div className="grid grid-cols-2 gap-1 bg-muted p-1 rounded-lg">
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('known')}
|
||||||
|
className={cn(
|
||||||
|
"text-xs py-2 px-3 rounded-md transition-colors",
|
||||||
|
activeTab === 'known'
|
||||||
|
? "bg-background shadow-sm font-medium"
|
||||||
|
: "text-muted-foreground hover:text-foreground"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
Active {knownConversations.length > 0 && `(${knownConversations.length})`}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setActiveTab('requests')}
|
||||||
|
className={cn(
|
||||||
|
"text-xs py-2 px-3 rounded-md transition-colors",
|
||||||
|
activeTab === 'requests'
|
||||||
|
? "bg-background shadow-sm font-medium"
|
||||||
|
: "text-muted-foreground hover:text-foreground"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
Requests {requestConversations.length > 0 && `(${requestConversations.length})`}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Content area - show skeleton during initial load, otherwise show conversations */}
|
||||||
|
<div className="flex-1 min-h-0 mt-2 overflow-hidden">
|
||||||
|
{(isLoading || isInitialLoad) ? (
|
||||||
|
<ConversationListSkeleton />
|
||||||
|
) : conversations.length === 0 ? (
|
||||||
|
<div className="flex items-center justify-center h-full text-center text-muted-foreground px-4">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm">No conversations yet</p>
|
||||||
|
<p className="text-xs mt-1">Start a new conversation to get started</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : currentConversations.length === 0 ? (
|
||||||
|
<div className="flex items-center justify-center h-32 text-center text-muted-foreground px-4">
|
||||||
|
<p className="text-sm">No {activeTab} conversations</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ScrollArea className="h-full block">
|
||||||
|
<div className="block w-full px-2 py-2 space-y-1">
|
||||||
|
{currentConversations.map((conversation) => (
|
||||||
|
<ConversationItem
|
||||||
|
key={conversation.pubkey}
|
||||||
|
pubkey={conversation.pubkey}
|
||||||
|
isSelected={selectedPubkey === conversation.pubkey}
|
||||||
|
onClick={() => onSelectConversation(conversation.pubkey)}
|
||||||
|
lastMessage={conversation.lastMessage}
|
||||||
|
lastActivity={conversation.lastActivity}
|
||||||
|
hasNIP4Messages={conversation.hasNIP4Messages}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { useState, useCallback } from 'react';
|
||||||
|
import { DMConversationList } from '@/components/dm/DMConversationList';
|
||||||
|
import { DMChatArea } from '@/components/dm/DMChatArea';
|
||||||
|
import { DMStatusInfo } from '@/components/dm/DMStatusInfo';
|
||||||
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from '@/components/ui/dialog';
|
||||||
|
|
||||||
|
interface DMMessagingInterfaceProps {
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DMMessagingInterface = ({ className }: DMMessagingInterfaceProps) => {
|
||||||
|
const [selectedPubkey, setSelectedPubkey] = useState<string | null>(null);
|
||||||
|
const [statusModalOpen, setStatusModalOpen] = useState(false);
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
const { clearCacheAndRefetch } = useDMContext();
|
||||||
|
|
||||||
|
// On mobile, show only one panel at a time
|
||||||
|
const showConversationList = !isMobile || !selectedPubkey;
|
||||||
|
const showChatArea = !isMobile || selectedPubkey;
|
||||||
|
|
||||||
|
const handleSelectConversation = useCallback((pubkey: string) => {
|
||||||
|
setSelectedPubkey(pubkey);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleBack = useCallback(() => {
|
||||||
|
setSelectedPubkey(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Status Modal */}
|
||||||
|
<Dialog open={statusModalOpen} onOpenChange={setStatusModalOpen}>
|
||||||
|
<DialogContent className="max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Messaging Status</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
View loading status, cache info, and connection details
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DMStatusInfo clearCacheAndRefetch={clearCacheAndRefetch} />
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
|
<div className={cn("flex gap-4 overflow-hidden", className)}>
|
||||||
|
{/* Conversation List - Left Sidebar */}
|
||||||
|
<div className={cn(
|
||||||
|
"md:w-80 md:flex-shrink-0",
|
||||||
|
isMobile && !showConversationList && "hidden",
|
||||||
|
isMobile && showConversationList && "w-full"
|
||||||
|
)}>
|
||||||
|
<DMConversationList
|
||||||
|
selectedPubkey={selectedPubkey}
|
||||||
|
onSelectConversation={handleSelectConversation}
|
||||||
|
className="h-full"
|
||||||
|
onStatusClick={() => setStatusModalOpen(true)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Chat Area - Right Panel */}
|
||||||
|
<div className={cn(
|
||||||
|
"flex-1 md:min-w-0",
|
||||||
|
isMobile && !showChatArea && "hidden",
|
||||||
|
isMobile && showChatArea && "w-full"
|
||||||
|
)}>
|
||||||
|
<DMChatArea
|
||||||
|
pubkey={selectedPubkey}
|
||||||
|
onBack={isMobile ? handleBack : undefined}
|
||||||
|
className="h-full"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { RefreshCw, Database, Wifi, CheckCircle2, Loader2 } from 'lucide-react';
|
||||||
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
|
import { LOADING_PHASES } from '@/lib/dmConstants';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { Separator } from '@/components/ui/separator';
|
||||||
|
import { useToast } from '@/hooks/useToast';
|
||||||
|
|
||||||
|
interface DMStatusInfoProps {
|
||||||
|
clearCacheAndRefetch?: () => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DMStatusInfo = ({ clearCacheAndRefetch }: DMStatusInfoProps) => {
|
||||||
|
const [isClearing, setIsClearing] = useState(false);
|
||||||
|
const { toast } = useToast();
|
||||||
|
const {
|
||||||
|
loadingPhase,
|
||||||
|
subscriptions,
|
||||||
|
scanProgress,
|
||||||
|
isDoingInitialLoad,
|
||||||
|
lastSync,
|
||||||
|
conversations,
|
||||||
|
} = useDMContext();
|
||||||
|
|
||||||
|
const handleClearCache = async () => {
|
||||||
|
if (!clearCacheAndRefetch) return;
|
||||||
|
|
||||||
|
setIsClearing(true);
|
||||||
|
try {
|
||||||
|
await clearCacheAndRefetch();
|
||||||
|
toast({
|
||||||
|
title: 'Cache cleared',
|
||||||
|
description: 'Refetching messages from relays...',
|
||||||
|
});
|
||||||
|
setIsClearing(false);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error clearing cache:', error);
|
||||||
|
toast({
|
||||||
|
title: 'Error',
|
||||||
|
description: 'Failed to clear cache. Please try again.',
|
||||||
|
variant: 'destructive',
|
||||||
|
});
|
||||||
|
setIsClearing(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getLoadingPhaseInfo = () => {
|
||||||
|
switch (loadingPhase) {
|
||||||
|
case LOADING_PHASES.IDLE:
|
||||||
|
return { label: 'Idle', description: 'Not yet initialized', icon: Loader2, color: 'text-muted-foreground' };
|
||||||
|
case LOADING_PHASES.CACHE:
|
||||||
|
return { label: 'Loading from cache', description: 'Reading cached messages...', icon: Database, color: 'text-blue-500' };
|
||||||
|
case LOADING_PHASES.RELAYS:
|
||||||
|
return { label: 'Loading from relays', description: 'Fetching messages from Nostr relays...', icon: Wifi, color: 'text-yellow-500' };
|
||||||
|
case LOADING_PHASES.SUBSCRIPTIONS:
|
||||||
|
return { label: 'Connecting subscriptions', description: 'Setting up real-time message sync...', icon: RefreshCw, color: 'text-orange-500' };
|
||||||
|
case LOADING_PHASES.READY:
|
||||||
|
return { label: 'Ready', description: 'All systems operational', icon: CheckCircle2, color: 'text-green-500' };
|
||||||
|
default:
|
||||||
|
return { label: 'Unknown', description: 'Status unknown', icon: Loader2, color: 'text-muted-foreground' };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const phaseInfo = getLoadingPhaseInfo();
|
||||||
|
const PhaseIcon = phaseInfo.icon;
|
||||||
|
|
||||||
|
const formatTimestamp = (timestamp: number | null) => {
|
||||||
|
if (!timestamp) return 'Never';
|
||||||
|
const date = new Date(timestamp * 1000);
|
||||||
|
const now = new Date();
|
||||||
|
const diffMs = now.getTime() - date.getTime();
|
||||||
|
const diffMins = Math.floor(diffMs / 60000);
|
||||||
|
|
||||||
|
if (diffMins < 1) return 'Just now';
|
||||||
|
if (diffMins < 60) return `${diffMins}m ago`;
|
||||||
|
if (diffMins < 1440) return `${Math.floor(diffMins / 60)}h ago`;
|
||||||
|
return date.toLocaleDateString();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Loading Phase */}
|
||||||
|
<Card>
|
||||||
|
<CardContent className="pt-6">
|
||||||
|
<div className="flex items-start gap-3">
|
||||||
|
<PhaseIcon className={`h-5 w-5 ${phaseInfo.color} ${loadingPhase !== LOADING_PHASES.READY ? 'animate-pulse' : ''}`} />
|
||||||
|
<div className="flex-1 space-y-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<p className="font-medium">{phaseInfo.label}</p>
|
||||||
|
{isDoingInitialLoad && (
|
||||||
|
<Badge variant="secondary" className="text-xs">
|
||||||
|
Initial Load
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-muted-foreground">{phaseInfo.description}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Scan Progress */}
|
||||||
|
{(scanProgress.nip4 !== null || scanProgress.nip17 !== null) && (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="pt-6">
|
||||||
|
<div className="space-y-3">
|
||||||
|
<p className="text-sm font-medium">Scanning Messages</p>
|
||||||
|
{scanProgress.nip4 !== null && (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<div className="flex items-center justify-between text-xs">
|
||||||
|
<span className="text-muted-foreground">NIP-4 (Legacy)</span>
|
||||||
|
<span className="text-muted-foreground">{scanProgress.nip4.current} events</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">{scanProgress.nip4.status}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{scanProgress.nip17 !== null && (
|
||||||
|
<div className="space-y-1">
|
||||||
|
<div className="flex items-center justify-between text-xs">
|
||||||
|
<span className="text-muted-foreground">NIP-17 (Private)</span>
|
||||||
|
<span className="text-muted-foreground">{scanProgress.nip17.current} events</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">{scanProgress.nip17.status}</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Subscriptions */}
|
||||||
|
<Card>
|
||||||
|
<CardContent className="pt-6">
|
||||||
|
<div className="space-y-3">
|
||||||
|
<p className="text-sm font-medium">Real-time Subscriptions</p>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-sm text-muted-foreground">NIP-4 (Legacy DMs)</span>
|
||||||
|
<Badge variant={subscriptions.isNIP4Connected ? 'default' : 'secondary'}>
|
||||||
|
{subscriptions.isNIP4Connected ? 'Connected' : 'Disconnected'}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-sm text-muted-foreground">NIP-17 (Private DMs)</span>
|
||||||
|
<Badge variant={subscriptions.isNIP17Connected ? 'default' : 'secondary'}>
|
||||||
|
{subscriptions.isNIP17Connected ? 'Connected' : 'Disconnected'}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Cache Info */}
|
||||||
|
<Card>
|
||||||
|
<CardContent className="pt-6">
|
||||||
|
<div className="space-y-3">
|
||||||
|
<p className="text-sm font-medium">Cache Information</p>
|
||||||
|
<div className="space-y-2 text-sm">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Conversations</span>
|
||||||
|
<span className="font-medium">{conversations.length}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Last NIP-4 sync</span>
|
||||||
|
<span className="font-medium">{formatTimestamp(lastSync.nip4)}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-muted-foreground">Last NIP-17 sync</span>
|
||||||
|
<span className="font-medium">{formatTimestamp(lastSync.nip17)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{/* Actions */}
|
||||||
|
{clearCacheAndRefetch && (
|
||||||
|
<>
|
||||||
|
<Separator />
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="text-sm font-medium">Cache Management</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Clear all cached messages and refetch from relays. This will force a fresh sync.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
onClick={handleClearCache}
|
||||||
|
disabled={isClearing}
|
||||||
|
variant="outline"
|
||||||
|
className="w-full"
|
||||||
|
>
|
||||||
|
{isClearing ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||||
|
Clearing...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<RefreshCw className="mr-2 h-4 w-4" />
|
||||||
|
Clear Cache & Refetch
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
@@ -12,7 +12,7 @@ const ScrollArea = React.forwardRef<
|
|||||||
className={cn("relative overflow-hidden", className)}
|
className={cn("relative overflow-hidden", className)}
|
||||||
{...props}
|
{...props}
|
||||||
>
|
>
|
||||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
|
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit] [&>div]:!block [&>div]:!w-full">
|
||||||
{children}
|
{children}
|
||||||
</ScrollAreaPrimitive.Viewport>
|
</ScrollAreaPrimitive.Viewport>
|
||||||
<ScrollBar />
|
<ScrollBar />
|
||||||
|
|||||||
@@ -2,20 +2,25 @@ import { createContext } from "react";
|
|||||||
|
|
||||||
export type Theme = "dark" | "light" | "system";
|
export type Theme = "dark" | "light" | "system";
|
||||||
|
|
||||||
|
export interface RelayMetadata {
|
||||||
|
/** List of relays with read/write permissions */
|
||||||
|
relays: { url: string; read: boolean; write: boolean }[];
|
||||||
|
/** Unix timestamp of when the relay list was last updated */
|
||||||
|
updatedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AppConfig {
|
export interface AppConfig {
|
||||||
/** Current theme */
|
/** Current theme */
|
||||||
theme: Theme;
|
theme: Theme;
|
||||||
/** Selected relay URL */
|
/** NIP-65 relay list metadata */
|
||||||
relayUrl: string;
|
relayMetadata: RelayMetadata;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AppContextType {
|
export interface AppContextType {
|
||||||
/** Current application configuration */
|
/** Current application configuration */
|
||||||
config: AppConfig;
|
config: AppConfig;
|
||||||
/** Update configuration using a callback that receives current config and returns new config */
|
/** Update configuration using a callback that receives current config and returns new config */
|
||||||
updateConfig: (updater: (currentConfig: AppConfig) => AppConfig) => void;
|
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
|
||||||
/** Optional list of preset relays to display in the RelaySelector */
|
|
||||||
presetRelays?: { name: string; url: string }[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const AppContext = createContext<AppContextType | undefined>(undefined);
|
export const AppContext = createContext<AppContextType | undefined>(undefined);
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import { createContext } from 'react';
|
||||||
|
import { type LoadingPhase, type ProtocolMode } from '@/lib/dmConstants';
|
||||||
|
import { type NostrEvent } from '@nostrify/nostrify';
|
||||||
|
import type { MessageProtocol } from '@/lib/dmConstants';
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// DM Types and Constants
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
interface ParticipantData {
|
||||||
|
messages: DecryptedMessage[];
|
||||||
|
lastActivity: number;
|
||||||
|
lastMessage: DecryptedMessage | null;
|
||||||
|
hasNIP4: boolean;
|
||||||
|
hasNIP17: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
type MessagesState = Map<string, ParticipantData>;
|
||||||
|
|
||||||
|
interface LastSyncData {
|
||||||
|
nip4: number | null;
|
||||||
|
nip17: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SubscriptionStatus {
|
||||||
|
isNIP4Connected: boolean;
|
||||||
|
isNIP17Connected: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ScanProgress {
|
||||||
|
current: number;
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ScanProgressState {
|
||||||
|
nip4: ScanProgress | null;
|
||||||
|
nip17: ScanProgress | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ConversationSummary {
|
||||||
|
id: string;
|
||||||
|
pubkey: string;
|
||||||
|
lastMessage: DecryptedMessage | null;
|
||||||
|
lastActivity: number;
|
||||||
|
hasNIP4Messages: boolean;
|
||||||
|
hasNIP17Messages: boolean;
|
||||||
|
isKnown: boolean;
|
||||||
|
isRequest: boolean;
|
||||||
|
lastMessageFromUser: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DecryptedMessage extends NostrEvent {
|
||||||
|
decryptedContent?: string;
|
||||||
|
error?: string;
|
||||||
|
isSending?: boolean;
|
||||||
|
clientFirstSeen?: number;
|
||||||
|
decryptedEvent?: NostrEvent; // For NIP-17: the inner kind 14/15 event
|
||||||
|
originalGiftWrapId?: string; // Store gift wrap ID for NIP-17 deduplication
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* File attachment for direct messages (NIP-92 compatible).
|
||||||
|
*
|
||||||
|
* All fields are required. Use with `useUploadFile` hook to upload files
|
||||||
|
* and generate the proper tags format.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* import { useUploadFile } from '@/hooks/useUploadFile';
|
||||||
|
* import type { FileAttachment } from '@/contexts/DMContext';
|
||||||
|
*
|
||||||
|
* const { mutateAsync: uploadFile } = useUploadFile();
|
||||||
|
*
|
||||||
|
* const tags = await uploadFile(file);
|
||||||
|
* const attachment: FileAttachment = {
|
||||||
|
* url: tags[0][1],
|
||||||
|
* mimeType: file.type,
|
||||||
|
* size: file.size,
|
||||||
|
* name: file.name,
|
||||||
|
* tags: tags
|
||||||
|
* };
|
||||||
|
*
|
||||||
|
* await sendMessage({
|
||||||
|
* recipientPubkey: 'hex-pubkey',
|
||||||
|
* content: 'Check out this file!',
|
||||||
|
* attachments: [attachment]
|
||||||
|
* });
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @property url - Blossom server URL where file is hosted
|
||||||
|
* @property mimeType - MIME type of the file (e.g., 'image/png')
|
||||||
|
* @property size - File size in bytes
|
||||||
|
* @property name - Original filename
|
||||||
|
* @property tags - NIP-94 file metadata tags (includes hashes)
|
||||||
|
*/
|
||||||
|
export interface FileAttachment {
|
||||||
|
url: string;
|
||||||
|
mimeType: string;
|
||||||
|
size: number;
|
||||||
|
name: string;
|
||||||
|
tags: string[][];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Direct Messaging context interface providing access to all DM functionality.
|
||||||
|
*
|
||||||
|
* @property messages - Raw message state (Map of pubkey -> participant data)
|
||||||
|
* @property isLoading - True during initial load phases
|
||||||
|
* @property loadingPhase - Current loading phase (CACHE, RELAYS, SUBSCRIPTIONS, READY, IDLE)
|
||||||
|
* @property isDoingInitialLoad - True only during cache/relay loading (not subscriptions)
|
||||||
|
* @property lastSync - Unix timestamps of last successful sync for each protocol
|
||||||
|
* @property subscriptions - Connection status for real-time message subscriptions
|
||||||
|
* @property conversations - Array of conversation summaries sorted by last activity
|
||||||
|
* @property sendMessage - Send an encrypted direct message (NIP-04 or NIP-17)
|
||||||
|
* @property protocolMode - Current protocol mode (NIP04_ONLY, NIP17_ONLY, or BOTH)
|
||||||
|
* @property scanProgress - Progress info for large message history scans
|
||||||
|
* @property clearCacheAndRefetch - Clear IndexedDB cache and reload all messages from relays
|
||||||
|
*/
|
||||||
|
export interface DMContextType {
|
||||||
|
messages: MessagesState;
|
||||||
|
isLoading: boolean;
|
||||||
|
loadingPhase: LoadingPhase;
|
||||||
|
isDoingInitialLoad: boolean;
|
||||||
|
lastSync: LastSyncData;
|
||||||
|
subscriptions: SubscriptionStatus;
|
||||||
|
conversations: ConversationSummary[];
|
||||||
|
sendMessage: (params: {
|
||||||
|
recipientPubkey: string;
|
||||||
|
content: string;
|
||||||
|
protocol?: MessageProtocol;
|
||||||
|
attachments?: FileAttachment[];
|
||||||
|
}) => Promise<void>;
|
||||||
|
protocolMode: ProtocolMode;
|
||||||
|
scanProgress: ScanProgressState;
|
||||||
|
clearCacheAndRefetch: () => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DMContext = createContext<DMContextType | null>(null);
|
||||||
@@ -28,6 +28,7 @@ export function useAuthor(pubkey: string | undefined) {
|
|||||||
return { event };
|
return { event };
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
staleTime: 5 * 60 * 1000, // Keep cached data fresh for 5 minutes
|
||||||
retry: 3,
|
retry: 3,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -6,7 +6,7 @@ export function useComments(root: NostrEvent | URL, limit?: number) {
|
|||||||
const { nostr } = useNostr();
|
const { nostr } = useNostr();
|
||||||
|
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ['comments', root instanceof URL ? root.toString() : root.id, limit],
|
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id, limit],
|
||||||
queryFn: async (c) => {
|
queryFn: async (c) => {
|
||||||
const filter: NostrFilter = { kinds: [1111] };
|
const filter: NostrFilter = { kinds: [1111] };
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
|
import { useDMContext } from "@/hooks/useDMContext";
|
||||||
|
|
||||||
|
const MESSAGES_PER_PAGE = 25;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hook to access paginated messages for a specific conversation.
|
||||||
|
*
|
||||||
|
* Returns the most recent messages (default 25) with the ability to load earlier messages.
|
||||||
|
* Automatically resets to default page size when switching conversations.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* import { useConversationMessages } from '@/contexts/DMContext';
|
||||||
|
*
|
||||||
|
* function MessageThread({ recipientPubkey }: { recipientPubkey: string }) {
|
||||||
|
* const {
|
||||||
|
* messages,
|
||||||
|
* hasMoreMessages,
|
||||||
|
* loadEarlierMessages,
|
||||||
|
* totalCount
|
||||||
|
* } = useConversationMessages(recipientPubkey);
|
||||||
|
*
|
||||||
|
* return (
|
||||||
|
* <div>
|
||||||
|
* {hasMoreMessages && (
|
||||||
|
* <button onClick={loadEarlierMessages}>
|
||||||
|
* Load Earlier ({totalCount - messages.length} more)
|
||||||
|
* </button>
|
||||||
|
* )}
|
||||||
|
* {messages.map(msg => (
|
||||||
|
* <div key={msg.id}>{msg.decryptedContent}</div>
|
||||||
|
* ))}
|
||||||
|
* </div>
|
||||||
|
* );
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @param conversationId - The pubkey of the conversation participant
|
||||||
|
* @returns Paginated message data with loading function
|
||||||
|
*/
|
||||||
|
export function useConversationMessages(conversationId: string) {
|
||||||
|
const { messages: allMessages } = useDMContext();
|
||||||
|
const [visibleCount, setVisibleCount] = useState(MESSAGES_PER_PAGE);
|
||||||
|
|
||||||
|
const result = useMemo(() => {
|
||||||
|
const conversationData = allMessages.get(conversationId);
|
||||||
|
|
||||||
|
if (!conversationData) {
|
||||||
|
return {
|
||||||
|
messages: [],
|
||||||
|
hasMoreMessages: false,
|
||||||
|
totalCount: 0,
|
||||||
|
lastMessage: null,
|
||||||
|
lastActivity: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalMessages = conversationData.messages.length;
|
||||||
|
const hasMore = totalMessages > visibleCount;
|
||||||
|
|
||||||
|
// Return the most recent N messages (slice from the end)
|
||||||
|
const visibleMessages = conversationData.messages.slice(-visibleCount);
|
||||||
|
|
||||||
|
return {
|
||||||
|
messages: visibleMessages,
|
||||||
|
hasMoreMessages: hasMore,
|
||||||
|
totalCount: totalMessages,
|
||||||
|
lastMessage: conversationData.lastMessage,
|
||||||
|
lastActivity: conversationData.lastActivity,
|
||||||
|
};
|
||||||
|
}, [allMessages, conversationId, visibleCount]);
|
||||||
|
|
||||||
|
const loadEarlierMessages = useCallback(() => {
|
||||||
|
setVisibleCount(prev => prev + MESSAGES_PER_PAGE);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Reset visible count when conversation changes
|
||||||
|
useEffect(() => {
|
||||||
|
setVisibleCount(MESSAGES_PER_PAGE);
|
||||||
|
}, [conversationId]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...result,
|
||||||
|
loadEarlierMessages,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { useContext } from "react";
|
||||||
|
import { DMContext, DMContextType } from "@/contexts/DMContext";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hook to access the direct messaging system.
|
||||||
|
*
|
||||||
|
* Provides access to conversations, message sending, loading states, and cache management.
|
||||||
|
* Must be used within a DMProvider.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* import { useDMContext } from '@/hooks/useDMContext';
|
||||||
|
* import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
||||||
|
*
|
||||||
|
* function MyComponent() {
|
||||||
|
* const { conversations, sendMessage, isLoading } = useDMContext();
|
||||||
|
*
|
||||||
|
* // Send a message
|
||||||
|
* await sendMessage({
|
||||||
|
* recipientPubkey: 'hex-pubkey',
|
||||||
|
* content: 'Hello!',
|
||||||
|
* protocol: MESSAGE_PROTOCOL.NIP17
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* // Display conversations
|
||||||
|
* return (
|
||||||
|
* <div>
|
||||||
|
* {isLoading ? 'Loading...' : conversations.map(c => (
|
||||||
|
* <div key={c.pubkey}>{c.lastMessage?.decryptedContent}</div>
|
||||||
|
* ))}
|
||||||
|
* </div>
|
||||||
|
* );
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @returns DMContextType - The direct messaging context
|
||||||
|
* @throws Error if used outside DMProvider
|
||||||
|
*/
|
||||||
|
export function useDMContext(): DMContextType {
|
||||||
|
const context = useContext(DMContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useDMContext must be used within DMProvider');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
||||||
@@ -15,7 +15,7 @@ export function useLoggedInAccounts() {
|
|||||||
const { logins, setLogin, removeLogin } = useNostrLogin();
|
const { logins, setLogin, removeLogin } = useNostrLogin();
|
||||||
|
|
||||||
const { data: authors = [] } = useQuery({
|
const { data: authors = [] } = useQuery({
|
||||||
queryKey: ['logins', logins.map((l) => l.id).join(';')],
|
queryKey: ['nostr', 'logins', logins.map((l) => l.id).join(';')],
|
||||||
queryFn: async ({ signal }) => {
|
queryFn: async ({ signal }) => {
|
||||||
const events = await nostr.query(
|
const events = await nostr.query(
|
||||||
[{ kinds: [0], authors: logins.map((l) => l.pubkey) }],
|
[{ kinds: [0], authors: logins.map((l) => l.pubkey) }],
|
||||||
|
|||||||
@@ -1,11 +1,67 @@
|
|||||||
|
import { NConnectSigner, NSecSigner } from '@nostrify/nostrify';
|
||||||
import { useNostr } from '@nostrify/react';
|
import { useNostr } from '@nostrify/react';
|
||||||
import { NLogin, useNostrLogin } from '@nostrify/react/login';
|
import { NLogin, useNostrLogin } from '@nostrify/react/login';
|
||||||
|
import { generateSecretKey, getPublicKey } from 'nostr-tools';
|
||||||
|
import { nip19 } from 'nostr-tools';
|
||||||
|
|
||||||
|
import { useAppContext } from '@/hooks/useAppContext';
|
||||||
|
|
||||||
// NOTE: This file should not be edited except for adding new login methods.
|
// NOTE: This file should not be edited except for adding new login methods.
|
||||||
|
|
||||||
|
/** Check if running on actual mobile device (not just small screen) */
|
||||||
|
function isMobileDevice(): boolean {
|
||||||
|
if (typeof navigator === 'undefined') return false;
|
||||||
|
return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parameters for initiating a nostrconnect:// session */
|
||||||
|
export interface NostrConnectParams {
|
||||||
|
clientSecretKey: Uint8Array;
|
||||||
|
clientPubkey: string;
|
||||||
|
secret: string;
|
||||||
|
relays: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Generates a nostrconnect:// URI for QR code display */
|
||||||
|
export function generateNostrConnectURI(params: NostrConnectParams, appName?: string): string {
|
||||||
|
const searchParams = new URLSearchParams();
|
||||||
|
|
||||||
|
for (const relay of params.relays) {
|
||||||
|
searchParams.append('relay', relay);
|
||||||
|
}
|
||||||
|
searchParams.set('secret', params.secret);
|
||||||
|
|
||||||
|
if (appName) {
|
||||||
|
searchParams.set('name', appName);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add callback URL only on mobile devices (not desktop QR code scanning)
|
||||||
|
// When scanning QR from desktop, the signer app is on the phone but the session is on desktop
|
||||||
|
if (typeof window !== 'undefined' && isMobileDevice()) {
|
||||||
|
searchParams.set('callback', `${window.location.origin}/remoteloginsuccess`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return `nostrconnect://${params.clientPubkey}?${searchParams.toString()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Generates random parameters for a nostrconnect session */
|
||||||
|
export function generateNostrConnectParams(relays: string[]): NostrConnectParams {
|
||||||
|
const clientSecretKey = generateSecretKey();
|
||||||
|
const clientPubkey = getPublicKey(clientSecretKey);
|
||||||
|
const secret = crypto.randomUUID().slice(0, 8);
|
||||||
|
|
||||||
|
return {
|
||||||
|
clientSecretKey,
|
||||||
|
clientPubkey,
|
||||||
|
secret,
|
||||||
|
relays,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function useLoginActions() {
|
export function useLoginActions() {
|
||||||
const { nostr } = useNostr();
|
const { nostr } = useNostr();
|
||||||
const { logins, addLogin, removeLogin } = useNostrLogin();
|
const { logins, addLogin, removeLogin } = useNostrLogin();
|
||||||
|
const { config } = useAppContext();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
// Login with a Nostr secret key
|
// Login with a Nostr secret key
|
||||||
@@ -23,6 +79,74 @@ export function useLoginActions() {
|
|||||||
const login = await NLogin.fromExtension();
|
const login = await NLogin.fromExtension();
|
||||||
addLogin(login);
|
addLogin(login);
|
||||||
},
|
},
|
||||||
|
// Login via nostrconnect:// (client-initiated NIP-46)
|
||||||
|
// The client displays a QR code and waits for the remote signer to connect
|
||||||
|
async nostrconnect(params: NostrConnectParams): Promise<void> {
|
||||||
|
const clientSigner = new NSecSigner(params.clientSecretKey);
|
||||||
|
const clientPubkey = getPublicKey(params.clientSecretKey);
|
||||||
|
|
||||||
|
// Create a relay group for the connection
|
||||||
|
const relayGroup = nostr.group(params.relays);
|
||||||
|
|
||||||
|
// Wait for the connect response from the remote signer
|
||||||
|
// We subscribe to kind 24133 events p-tagged to our client pubkey
|
||||||
|
const signal = AbortSignal.timeout(120_000); // 2 minute timeout
|
||||||
|
|
||||||
|
const sub = relayGroup.req(
|
||||||
|
[{ kinds: [24133], '#p': [clientPubkey], limit: 1 }],
|
||||||
|
{ signal }
|
||||||
|
);
|
||||||
|
|
||||||
|
for await (const msg of sub) {
|
||||||
|
if (msg[0] === 'CLOSED') {
|
||||||
|
throw new Error('Connection closed before remote signer responded');
|
||||||
|
}
|
||||||
|
if (msg[0] === 'EVENT') {
|
||||||
|
const event = msg[2];
|
||||||
|
|
||||||
|
// Decrypt the response
|
||||||
|
const decrypted = await clientSigner.nip44!.decrypt(event.pubkey, event.content);
|
||||||
|
const response = JSON.parse(decrypted);
|
||||||
|
|
||||||
|
// Validate the secret matches
|
||||||
|
if (response.result !== params.secret && response.result !== 'ack') {
|
||||||
|
continue; // Not our response, keep waiting
|
||||||
|
}
|
||||||
|
|
||||||
|
// Success! The remote signer has connected
|
||||||
|
// Now create the NConnectSigner for ongoing use
|
||||||
|
const bunkerPubkey = event.pubkey;
|
||||||
|
|
||||||
|
const signer = new NConnectSigner({
|
||||||
|
relay: relayGroup,
|
||||||
|
pubkey: bunkerPubkey,
|
||||||
|
signer: clientSigner,
|
||||||
|
timeout: 60_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Get the actual user pubkey
|
||||||
|
const userPubkey = await signer.getPublicKey();
|
||||||
|
|
||||||
|
// Create and add the login
|
||||||
|
const login = new NLogin('bunker', userPubkey, {
|
||||||
|
bunkerPubkey,
|
||||||
|
clientNsec: nip19.nsecEncode(params.clientSecretKey),
|
||||||
|
relays: params.relays,
|
||||||
|
});
|
||||||
|
|
||||||
|
addLogin(login);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('Timeout waiting for remote signer');
|
||||||
|
},
|
||||||
|
// Get the current relay URL for nostrconnect
|
||||||
|
getRelayUrl(): string {
|
||||||
|
// Get the first write-enabled relay, or fallback to a default
|
||||||
|
const writeRelay = config.relayMetadata?.relays?.find(r => r.write);
|
||||||
|
return writeRelay?.url ?? 'wss://relay.nostr.band';
|
||||||
|
},
|
||||||
// Log out the current user
|
// Log out the current user
|
||||||
async logout(): Promise<void> {
|
async logout(): Promise<void> {
|
||||||
const login = logins[0];
|
const login = logins[0];
|
||||||
|
|||||||
@@ -85,7 +85,7 @@ export function usePostComment() {
|
|||||||
onSuccess: (_, { root }) => {
|
onSuccess: (_, { root }) => {
|
||||||
// Invalidate and refetch comments
|
// Invalidate and refetch comments
|
||||||
queryClient.invalidateQueries({
|
queryClient.invalidateQueries({
|
||||||
queryKey: ['comments', root instanceof URL ? root.toString() : root.id]
|
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id]
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -122,7 +122,7 @@ async function handleAPIError(response: Response) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw new Error(`Invalid request: ${error.error?.message || error.details || error.error || 'Please check your request parameters.'}`);
|
throw new Error(`Invalid request: ${error.error?.message || error.details || error.error || 'Please check your request parameters.'}`);
|
||||||
} catch (parseError) {
|
} catch {
|
||||||
throw new Error('Invalid request. Please check your parameters and try again.');
|
throw new Error('Invalid request. Please check your parameters and try again.');
|
||||||
}
|
}
|
||||||
} else if (response.status === 404) {
|
} else if (response.status === 404) {
|
||||||
@@ -133,7 +133,7 @@ async function handleAPIError(response: Response) {
|
|||||||
try {
|
try {
|
||||||
const errorData = await response.json();
|
const errorData = await response.json();
|
||||||
throw new Error(`API error: ${errorData.error?.message || errorData.details || errorData.error || response.statusText}`);
|
throw new Error(`API error: ${errorData.error?.message || errorData.details || errorData.error || response.statusText}`);
|
||||||
} catch (parseError) {
|
} catch {
|
||||||
throw new Error(`Network error: ${response.statusText}. Please check your connection and try again.`);
|
throw new Error(`Network error: ${response.statusText}. Please check your connection and try again.`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -205,7 +205,7 @@ export function useZaps(
|
|||||||
profile: actualTarget.pubkey,
|
profile: actualTarget.pubkey,
|
||||||
event: event,
|
event: event,
|
||||||
amount: zapAmount,
|
amount: zapAmount,
|
||||||
relays: [config.relayUrl],
|
relays: config.relayMetadata.relays.map(r => r.url),
|
||||||
comment
|
comment
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import type { NostrEvent } from '@nostrify/nostrify';
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Message Protocol Types
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
export const MESSAGE_PROTOCOL = {
|
||||||
|
NIP04: 'nip04',
|
||||||
|
NIP17: 'nip17',
|
||||||
|
UNKNOWN: 'unknown',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type MessageProtocol = typeof MESSAGE_PROTOCOL[keyof typeof MESSAGE_PROTOCOL];
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Protocol Mode (for user selection)
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
export const PROTOCOL_MODE = {
|
||||||
|
NIP04_ONLY: 'nip04_only',
|
||||||
|
NIP17_ONLY: 'nip17_only',
|
||||||
|
NIP04_OR_NIP17: 'nip04_or_nip17',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type ProtocolMode = typeof PROTOCOL_MODE[keyof typeof PROTOCOL_MODE];
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Loading Phases
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
export const LOADING_PHASES = {
|
||||||
|
IDLE: 'idle',
|
||||||
|
CACHE: 'cache',
|
||||||
|
RELAYS: 'relays',
|
||||||
|
SUBSCRIPTIONS: 'subscriptions',
|
||||||
|
READY: 'ready',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type LoadingPhase = typeof LOADING_PHASES[keyof typeof LOADING_PHASES];
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Protocol Configuration
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
export const PROTOCOL_CONFIG = {
|
||||||
|
[MESSAGE_PROTOCOL.NIP04]: {
|
||||||
|
label: 'NIP-04',
|
||||||
|
description: 'Legacy DMs',
|
||||||
|
kind: 4,
|
||||||
|
},
|
||||||
|
[MESSAGE_PROTOCOL.NIP17]: {
|
||||||
|
label: 'NIP-17',
|
||||||
|
description: 'Private DMs',
|
||||||
|
kind: 1059,
|
||||||
|
},
|
||||||
|
[MESSAGE_PROTOCOL.UNKNOWN]: {
|
||||||
|
label: 'Unknown',
|
||||||
|
description: 'Unknown protocol',
|
||||||
|
kind: 0,
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Helper Functions
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the message protocol from an event kind
|
||||||
|
*/
|
||||||
|
export function getMessageProtocol(event: NostrEvent): MessageProtocol {
|
||||||
|
switch (event.kind) {
|
||||||
|
case 4:
|
||||||
|
return MESSAGE_PROTOCOL.NIP04;
|
||||||
|
case 1059:
|
||||||
|
return MESSAGE_PROTOCOL.NIP17;
|
||||||
|
default:
|
||||||
|
return MESSAGE_PROTOCOL.UNKNOWN;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a protocol is valid for sending messages
|
||||||
|
*/
|
||||||
|
export function isValidSendProtocol(protocol: MessageProtocol): boolean {
|
||||||
|
return protocol === MESSAGE_PROTOCOL.NIP04 || protocol === MESSAGE_PROTOCOL.NIP17;
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import { openDB, type IDBPDatabase } from 'idb';
|
||||||
|
import type { NostrEvent } from '@nostrify/nostrify';
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// IndexedDB Schema
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
// Use domain-based naming to avoid conflicts between apps on same domain
|
||||||
|
const getDBName = () => {
|
||||||
|
// Use hostname for unique DB per app (e.g., 'nostr-dm-store-localhost', 'nostr-dm-store-myapp.com')
|
||||||
|
const hostname = typeof window !== 'undefined' ? window.location.hostname : 'default';
|
||||||
|
return `nostr-dm-store-${hostname}`;
|
||||||
|
};
|
||||||
|
const DB_NAME = getDBName();
|
||||||
|
const DB_VERSION = 1;
|
||||||
|
const STORE_NAME = 'messages';
|
||||||
|
|
||||||
|
interface StoredParticipant {
|
||||||
|
messages: NostrEvent[];
|
||||||
|
lastActivity: number;
|
||||||
|
hasNIP4: boolean;
|
||||||
|
hasNIP17: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MessageStore {
|
||||||
|
participants: Record<string, StoredParticipant>;
|
||||||
|
lastSync: {
|
||||||
|
nip4: number | null;
|
||||||
|
nip17: number | null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Database Operations
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open the IndexedDB database
|
||||||
|
*/
|
||||||
|
async function openDatabase(): Promise<IDBPDatabase> {
|
||||||
|
return openDB(DB_NAME, DB_VERSION, {
|
||||||
|
upgrade(db) {
|
||||||
|
// Create the messages store if it doesn't exist
|
||||||
|
if (!db.objectStoreNames.contains(STORE_NAME)) {
|
||||||
|
db.createObjectStore(STORE_NAME);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write messages to IndexedDB for a specific user
|
||||||
|
* Messages are stored in their original encrypted form (kind 4 or kind 13)
|
||||||
|
*/
|
||||||
|
export async function writeMessagesToDB(
|
||||||
|
userPubkey: string,
|
||||||
|
messageStore: MessageStore
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
const db = await openDatabase();
|
||||||
|
|
||||||
|
// Store messages in their original encrypted form (no NIP-44 wrapper needed)
|
||||||
|
// Each message content is already encrypted by the sender
|
||||||
|
await db.put(STORE_NAME, messageStore, userPubkey);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[MessageStore] ❌ Error writing to IndexedDB:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read messages from IndexedDB for a specific user
|
||||||
|
* Messages are stored in their original encrypted form (kind 4 or kind 13)
|
||||||
|
*/
|
||||||
|
export async function readMessagesFromDB(
|
||||||
|
userPubkey: string
|
||||||
|
): Promise<MessageStore | undefined> {
|
||||||
|
try {
|
||||||
|
const db = await openDatabase();
|
||||||
|
const data = await db.get(STORE_NAME, userPubkey);
|
||||||
|
|
||||||
|
if (!data) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return data as MessageStore;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[MessageStore] Error reading from IndexedDB:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete messages from IndexedDB for a specific user
|
||||||
|
*/
|
||||||
|
export async function deleteMessagesFromDB(userPubkey: string): Promise<void> {
|
||||||
|
try {
|
||||||
|
const db = await openDatabase();
|
||||||
|
await db.delete(STORE_NAME, userPubkey);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[MessageStore] Error deleting from IndexedDB:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear all messages from IndexedDB
|
||||||
|
*/
|
||||||
|
export async function clearAllMessages(): Promise<void> {
|
||||||
|
try {
|
||||||
|
const db = await openDatabase();
|
||||||
|
await db.clear(STORE_NAME);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[MessageStore] Error clearing IndexedDB:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import type { NostrEvent } from '@nostrify/nostrify';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate that an event is a proper DM event
|
||||||
|
*/
|
||||||
|
export function validateDMEvent(event: NostrEvent): boolean {
|
||||||
|
// Must be kind 4 (NIP-04 DM)
|
||||||
|
if (event.kind !== 4) return false;
|
||||||
|
|
||||||
|
// Must have a 'p' tag
|
||||||
|
const hasRecipient = event.tags?.some(([name]) => name === 'p');
|
||||||
|
if (!hasRecipient) return false;
|
||||||
|
|
||||||
|
// Must have content (even if encrypted)
|
||||||
|
if (!event.content) return false;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the recipient pubkey from a DM event
|
||||||
|
*/
|
||||||
|
export function getRecipientPubkey(event: NostrEvent): string | undefined {
|
||||||
|
return event.tags?.find(([name]) => name === 'p')?.[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the conversation partner pubkey from a DM event
|
||||||
|
* (the other person in the conversation, not the current user)
|
||||||
|
*/
|
||||||
|
export function getConversationPartner(event: NostrEvent, userPubkey: string): string | undefined {
|
||||||
|
const isFromUser = event.pubkey === userPubkey;
|
||||||
|
|
||||||
|
if (isFromUser) {
|
||||||
|
// If we sent it, the partner is the recipient
|
||||||
|
return getRecipientPubkey(event);
|
||||||
|
} else {
|
||||||
|
// If they sent it, the partner is the author
|
||||||
|
return event.pubkey;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format timestamp for display (matches Signal/WhatsApp/Telegram pattern)
|
||||||
|
* Today: Show time (e.g., "2:45 PM")
|
||||||
|
* Yesterday: "Yesterday"
|
||||||
|
* This week: Day name (e.g., "Mon")
|
||||||
|
* This year: Month and day (e.g., "Jan 15")
|
||||||
|
* Older: Full date (e.g., "Jan 15, 2024")
|
||||||
|
*/
|
||||||
|
export function formatConversationTime(timestamp: number): string {
|
||||||
|
const date = new Date(timestamp * 1000);
|
||||||
|
const now = new Date();
|
||||||
|
|
||||||
|
// Start of today (midnight)
|
||||||
|
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||||
|
|
||||||
|
// Start of yesterday
|
||||||
|
const yesterdayStart = new Date(todayStart);
|
||||||
|
yesterdayStart.setDate(yesterdayStart.getDate() - 1);
|
||||||
|
|
||||||
|
// Start of this week (assuming week starts on Sunday, adjust if needed)
|
||||||
|
const weekStart = new Date(todayStart);
|
||||||
|
weekStart.setDate(weekStart.getDate() - weekStart.getDay());
|
||||||
|
|
||||||
|
if (date >= todayStart) {
|
||||||
|
// Today: Show time (e.g., "2:45 PM")
|
||||||
|
return date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
|
||||||
|
} else if (date >= yesterdayStart) {
|
||||||
|
// Yesterday
|
||||||
|
return 'Yesterday';
|
||||||
|
} else if (date >= weekStart) {
|
||||||
|
// This week: Show day name (e.g., "Monday")
|
||||||
|
return date.toLocaleDateString(undefined, { weekday: 'short' });
|
||||||
|
} else if (date.getFullYear() === now.getFullYear()) {
|
||||||
|
// This year: Show month and day (e.g., "Jan 15")
|
||||||
|
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
|
||||||
|
} else {
|
||||||
|
// Older: Show full date (e.g., "Jan 15, 2024")
|
||||||
|
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format timestamp as full date and time for tooltips
|
||||||
|
* e.g., "Mon, Jan 15, 2024, 2:45 PM"
|
||||||
|
*/
|
||||||
|
export function formatFullDateTime(timestamp: number): string {
|
||||||
|
const date = new Date(timestamp * 1000);
|
||||||
|
return date.toLocaleString(undefined, {
|
||||||
|
weekday: 'short',
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
hour: 'numeric',
|
||||||
|
minute: '2-digit'
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,3 +1,15 @@
|
|||||||
|
import Buffer from 'buffer';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Polyfill for Buffer in browser environment
|
||||||
|
*
|
||||||
|
* Many Node.js libraries like isomorphic-git and bitcoinjs-lib expect Buffer to be globally available.
|
||||||
|
* This polyfill makes the buffer package's Buffer available globally.
|
||||||
|
*/
|
||||||
|
if (!globalThis.Buffer) {
|
||||||
|
globalThis.Buffer = Buffer.Buffer;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Polyfill for AbortSignal.any()
|
* Polyfill for AbortSignal.any()
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { useSeoMeta } from '@unhead/react';
|
||||||
|
import { DMMessagingInterface } from '@/components/dm/DMMessagingInterface';
|
||||||
|
|
||||||
|
const Messages = () => {
|
||||||
|
useSeoMeta({
|
||||||
|
title: 'Messages',
|
||||||
|
description: 'Private encrypted messaging on Nostr',
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-background">
|
||||||
|
<div className="container mx-auto p-4 h-screen flex flex-col">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<h1 className="text-2xl font-semibold">Messages</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DMMessagingInterface className="flex-1" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Messages;
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import { useEffect, useState, useCallback } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { useNostrLogin } from '@nostrify/react/login';
|
||||||
|
import { Loader2, CheckCircle, XCircle } from 'lucide-react';
|
||||||
|
|
||||||
|
// Storage key must match the one in App.tsx NostrLoginProvider
|
||||||
|
const LOGINS_STORAGE_KEY = 'nostr:login';
|
||||||
|
|
||||||
|
export function RemoteLoginSuccess() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { logins } = useNostrLogin();
|
||||||
|
const [checkCount, setCheckCount] = useState(0);
|
||||||
|
const [status, setStatus] = useState<'checking' | 'success' | 'timeout'>('checking');
|
||||||
|
|
||||||
|
// Check localStorage directly as a fallback
|
||||||
|
const checkLocalStorage = useCallback(() => {
|
||||||
|
try {
|
||||||
|
const stored = localStorage.getItem(LOGINS_STORAGE_KEY);
|
||||||
|
if (stored) {
|
||||||
|
const parsed = JSON.parse(stored);
|
||||||
|
return Array.isArray(parsed) && parsed.length > 0;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore parse errors
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Check if logged in via React state or localStorage
|
||||||
|
const isLoggedIn = logins.length > 0 || checkLocalStorage();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isLoggedIn) {
|
||||||
|
setStatus('success');
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
// Try to close this tab (works if opened by signer app)
|
||||||
|
// This leaves the user on the original tab which should detect the login
|
||||||
|
window.close();
|
||||||
|
// If we're still here (close didn't work), do a full page redirect
|
||||||
|
window.location.href = '/';
|
||||||
|
}, 1500);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check up to 20 times (10 seconds total) for the session to become active
|
||||||
|
if (checkCount < 20) {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
setCheckCount(prev => prev + 1);
|
||||||
|
}, 500);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
} else {
|
||||||
|
setStatus('timeout');
|
||||||
|
}
|
||||||
|
}, [isLoggedIn, checkCount, navigate, checkLocalStorage]);
|
||||||
|
|
||||||
|
// Listen for storage events (in case login is added from another context)
|
||||||
|
useEffect(() => {
|
||||||
|
const handleStorage = (e: StorageEvent) => {
|
||||||
|
if (e.key === LOGINS_STORAGE_KEY && e.newValue) {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(e.newValue);
|
||||||
|
if (Array.isArray(parsed) && parsed.length > 0) {
|
||||||
|
setStatus('success');
|
||||||
|
setTimeout(() => {
|
||||||
|
window.close();
|
||||||
|
window.location.href = '/';
|
||||||
|
}, 1500);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Ignore parse errors
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('storage', handleStorage);
|
||||||
|
return () => window.removeEventListener('storage', handleStorage);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-background">
|
||||||
|
<div className="text-center p-8">
|
||||||
|
{status === 'checking' && (
|
||||||
|
<>
|
||||||
|
<Loader2 className="h-16 w-16 animate-spin text-primary mx-auto mb-4" />
|
||||||
|
<h1 className="text-2xl font-bold mb-2">Completing Login...</h1>
|
||||||
|
<p className="text-muted-foreground">Please wait while we verify your session.</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{status === 'success' && (
|
||||||
|
<>
|
||||||
|
<CheckCircle className="h-16 w-16 text-green-500 mx-auto mb-4" />
|
||||||
|
<h1 className="text-2xl font-bold mb-2">Login Successful!</h1>
|
||||||
|
<p className="text-muted-foreground">Redirecting you now...</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{status === 'timeout' && (
|
||||||
|
<>
|
||||||
|
<XCircle className="h-16 w-16 text-destructive mx-auto mb-4" />
|
||||||
|
<h1 className="text-2xl font-bold mb-2">Session Not Found</h1>
|
||||||
|
<p className="text-muted-foreground mb-4">
|
||||||
|
We couldn't detect an active login session.
|
||||||
|
</p>
|
||||||
|
<a
|
||||||
|
href="/"
|
||||||
|
className="text-primary hover:underline"
|
||||||
|
>
|
||||||
|
Return to home page
|
||||||
|
</a>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -23,7 +23,12 @@ export function TestApp({ children }: TestAppProps) {
|
|||||||
|
|
||||||
const defaultConfig: AppConfig = {
|
const defaultConfig: AppConfig = {
|
||||||
theme: 'light',
|
theme: 'light',
|
||||||
relayUrl: 'wss://relay.nostr.band',
|
relayMetadata: {
|
||||||
|
relays: [
|
||||||
|
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
||||||
|
],
|
||||||
|
updatedAt: 0,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"target": "ES2020",
|
"target": "ES2020",
|
||||||
"useDefineForClassFields": true,
|
"useDefineForClassFields": true,
|
||||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
"lib": ["ESNext", "DOM", "DOM.Iterable"],
|
||||||
"module": "ESNext",
|
"module": "ESNext",
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user