mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 08:07:21 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c21a4147c |
No files matched your search
Symlink
+1
@@ -0,0 +1 @@
|
||||
../.mcp.json
|
||||
@@ -7,13 +7,11 @@ yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
.ai/
|
||||
yarn.lock
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
|
||||
@@ -15,11 +15,9 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `/docs/`: Specialized documentation for implementation patterns and features
|
||||
- `/src/components/`: UI components including NostrProvider for Nostr integration
|
||||
- `/src/components/ui/`: shadcn/ui components (48+ components available)
|
||||
- `/src/components/auth/`: Authentication-related components (LoginArea, LoginDialog, etc.)
|
||||
- `/src/components/dm/`: Direct messaging UI components (DMMessagingInterface, DMConversationList, DMChatArea)
|
||||
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
|
||||
- `/src/hooks/`: Custom hooks including:
|
||||
- `useNostr`: Core Nostr protocol integration
|
||||
@@ -38,12 +36,10 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `useWallet`: Unified wallet detection (WebLN + NWC)
|
||||
- `useNWC`: Nostr Wallet Connect connection management
|
||||
- `useNWCContext`: Access NWC context provider
|
||||
- `useShakespeare`: AI chat completions with Shakespeare AI API
|
||||
- `usePush`: Push notifications via Nostr RPC
|
||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||
- `/src/lib/`: Utility functions and shared logic
|
||||
- `/src/contexts/`: React context providers (AppContext, NWCContext, DMContext)
|
||||
- `useDMContext`: Hook exported from DMContext for direct messaging (NIP-04 & NIP-17)
|
||||
- `useConversationMessages`: Hook exported from DMContext for paginated messages
|
||||
- `/src/contexts/`: React context providers (AppContext, NWCContext)
|
||||
- `/src/test/`: Testing utilities including TestApp component
|
||||
- `/public/`: Static assets
|
||||
- `App.tsx`: Main app component with provider setup
|
||||
@@ -102,18 +98,6 @@ The project uses shadcn/ui components located in `@/components/ui`. These are un
|
||||
|
||||
These components follow a consistent pattern using React's `forwardRef` and use the `cn()` utility for class name merging. Many are built on Radix UI primitives for accessibility and customized with Tailwind CSS.
|
||||
|
||||
## Documentation
|
||||
|
||||
The project includes a **`docs/`** directory containing specialized documentation for specific implementation tasks. You are encouraged to add new documentation files to help future development.
|
||||
|
||||
- **`docs/AI_CHAT.md`**: Read when building any AI-powered chat interfaces, implementing streaming responses, or integrating with the Shakespeare API.
|
||||
|
||||
- **`docs/NOSTR_COMMENTS.md`**: Read when implementing comment systems, adding discussion features to posts/articles, or building community interaction features.
|
||||
|
||||
- **`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
|
||||
|
||||
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:
|
||||
@@ -399,7 +383,71 @@ function usePosts() {
|
||||
}
|
||||
```
|
||||
|
||||
### Efficient Query Design
|
||||
### Infinite Scroll for Feeds
|
||||
|
||||
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
|
||||
export function useGlobalFeed() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: ['global-feed'],
|
||||
queryFn: async ({ pageParam, signal }) => {
|
||||
const filter = { kinds: [1], limit: 20 };
|
||||
if (pageParam) filter.until = pageParam;
|
||||
|
||||
const events = await nostr.query([filter], {
|
||||
signal: AbortSignal.any([signal, AbortSignal.timeout(1500)])
|
||||
});
|
||||
|
||||
return events;
|
||||
},
|
||||
getNextPageParam: (lastPage) => {
|
||||
if (lastPage.length === 0) return undefined;
|
||||
return lastPage[lastPage.length - 1].created_at - 1; // Subtract 1 since 'until' is inclusive
|
||||
},
|
||||
initialPageParam: undefined,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Example usage with intersection observer for automatic loading:
|
||||
|
||||
```tsx
|
||||
import { useInView } from 'react-intersection-observer';
|
||||
|
||||
function GlobalFeed() {
|
||||
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
|
||||
const { ref, inView } = useInView();
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage) {
|
||||
fetchNextPage();
|
||||
}
|
||||
}, [inView, hasNextPage, fetchNextPage]);
|
||||
|
||||
const posts = data?.pages.flat() || [];
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{posts.map((post) => (
|
||||
<PostCard key={post.id} post={post} />
|
||||
))}
|
||||
{hasNextPage && (
|
||||
<div ref={ref} className="py-4">
|
||||
{isFetchingNextPage && <Skeleton className="h-20 w-full" />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Efficient Query Design
|
||||
|
||||
**Critical**: Always minimize the number of separate queries to avoid rate limiting and improve performance. Combine related queries whenever possible.
|
||||
|
||||
@@ -439,7 +487,7 @@ const [notes, reposts, genericReposts] = await Promise.all([
|
||||
|
||||
The data may be transformed into a more appropriate format if needed, and multiple calls to `nostr.query()` may be made in a single queryFn.
|
||||
|
||||
### Event Validation
|
||||
#### Event Validation
|
||||
|
||||
When querying events, if the event kind being returned has required tags or required JSON fields in the content, the events should be filtered through a validator function. This is not generally needed for kinds such as 1, where all tags are optional and the content is freeform text, but is especially useful for custom kinds as well as kinds with strict requirements.
|
||||
|
||||
@@ -510,7 +558,7 @@ function Post({ event }: { event: NostrEvent }) {
|
||||
}
|
||||
```
|
||||
|
||||
### `NostrMetadata` type
|
||||
#### `NostrMetadata` type
|
||||
|
||||
```ts
|
||||
/** Kind 0 metadata. */
|
||||
@@ -749,20 +797,6 @@ function EditProfilePage() {
|
||||
|
||||
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
|
||||
|
||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||
@@ -809,6 +843,48 @@ const encrypted = await user.signer.nip44.encrypt(user.pubkey, "hello world");
|
||||
const decrypted = await user.signer.nip44.decrypt(user.pubkey, encrypted) // "hello world"
|
||||
```
|
||||
|
||||
### Push Notifications
|
||||
|
||||
The project includes `usePush` hook for managing push notifications via Nostr RPC. This enables users to receive browser notifications for Nostr events.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { usePush } from '@/hooks/usePush';
|
||||
|
||||
function NotificationButton({ authorPubkey }: { authorPubkey: string }) {
|
||||
const { subscribeToAuthor, isLoading, error } = usePush();
|
||||
|
||||
const handleEnableNotifications = async () => {
|
||||
try {
|
||||
await subscribeToAuthor(authorPubkey);
|
||||
} catch (error) {
|
||||
console.error('Failed to enable notifications:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Button onClick={handleEnableNotifications} disabled={isLoading}>
|
||||
{isLoading ? 'Enabling...' : 'Enable Notifications'}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Available Methods
|
||||
|
||||
- **`subscribeToAuthor`**: Get notifications for new posts from a specific user
|
||||
- **`subscribeToMentions`**: Get notifications when mentioned in posts
|
||||
- **`subscribeToHashtag`**: Get notifications for posts with specific hashtags
|
||||
- **`registerSubscription`**: Create custom notification subscriptions
|
||||
- **`deleteSubscription`**: Remove notification subscriptions
|
||||
|
||||
#### Requirements
|
||||
|
||||
- User must be logged in with NIP-44 encryption support
|
||||
- Browser must support push notifications
|
||||
- VAPID public key is included by default
|
||||
|
||||
### Rendering Rich Text Content
|
||||
|
||||
Nostr text notes (kind 1, 11, and 1111) have a plaintext `content` field that may contain URLs, hashtags, and Nostr URIs. These events should render their content using the `NoteContent` component:
|
||||
@@ -829,6 +905,61 @@ export function Post(/* ...props */) {
|
||||
}
|
||||
```
|
||||
|
||||
### Adding Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
#### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
#### Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
|
||||
## App Configuration
|
||||
|
||||
The project includes an `AppProvider` that manages global application state including theme and relay configuration. The default configuration includes:
|
||||
@@ -915,53 +1046,15 @@ import { Card, CardContent } from '@/components/ui/card';
|
||||
</div>
|
||||
```
|
||||
|
||||
## CRITICAL Design Standards
|
||||
## Design Customization
|
||||
|
||||
- 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
|
||||
**Tailor the site's look and feel based on the user's specific request.** This includes:
|
||||
|
||||
### Design Principles
|
||||
|
||||
- Achieve Apple-level refinement with meticulous attention to detail, ensuring designs evoke strong emotions (e.g., wonder, inspiration, energy) through color, motion, and composition
|
||||
- Deliver fully functional interactive components with intuitive feedback states, ensuring every element has a clear purpose and enhances user engagement
|
||||
- Use custom illustrations, 3D elements, or symbolic visuals instead of generic stock imagery to create a unique brand narrative; stock imagery, when required, must be sourced exclusively from Pexels (NEVER Unsplash) and align with the design’s emotional tone
|
||||
- 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
|
||||
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
|
||||
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
|
||||
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
|
||||
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
|
||||
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
|
||||
|
||||
### Adding Fonts
|
||||
|
||||
|
||||
-332
@@ -1,332 +0,0 @@
|
||||
### AI Integration with Shakespeare API
|
||||
|
||||
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
|
||||
import { useShakespeare, type ChatMessage, type Model } from '@/hooks/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
|
||||
|
||||
```tsx
|
||||
function AIChat() {
|
||||
const { sendChatMessage, isLoading, error, isAuthenticated } = useShakespeare();
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
const [selectedModel, setSelectedModel] = useState<string>('');
|
||||
|
||||
const handleSend = async () => {
|
||||
if (!input.trim() || !selectedModel) return;
|
||||
|
||||
const newMessages = [...messages, { role: 'user', content: input }];
|
||||
setMessages(newMessages);
|
||||
setInput('');
|
||||
|
||||
try {
|
||||
const response = await sendChatMessage(newMessages, selectedModel);
|
||||
setMessages(prev => [...prev, {
|
||||
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>;
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto p-4">
|
||||
{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">
|
||||
{messages.map((msg, i) => (
|
||||
<div key={i} className={`p-2 rounded ${msg.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'}`}>
|
||||
<strong>{msg.role}:</strong> {msg.content}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
|
||||
className="flex-1 p-2 border rounded"
|
||||
disabled={isLoading || !selectedModel}
|
||||
placeholder={!selectedModel ? "Select a model first..." : "Type your message..."}
|
||||
/>
|
||||
<button
|
||||
onClick={handleSend}
|
||||
disabled={isLoading || !selectedModel}
|
||||
className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
|
||||
>
|
||||
Send
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Streaming Chat Example
|
||||
|
||||
```tsx
|
||||
function StreamingChat() {
|
||||
const { sendStreamingMessage } = useShakespeare();
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [currentResponse, setCurrentResponse] = useState('');
|
||||
const [selectedModel, setSelectedModel] = useState<string>('');
|
||||
|
||||
const handleStreaming = async (content: string) => {
|
||||
if (!selectedModel) return;
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
#### Model Information
|
||||
|
||||
Models are dynamically fetched from the Shakespeare API and include:
|
||||
|
||||
- **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
|
||||
|
||||
- **Dynamic Model Discovery**: Always fetch available models using `getAvailableModels()`
|
||||
- **Authentication Required**: User must be logged in with Nostr account
|
||||
- **Free vs Premium**: Check pricing to determine if model requires credits
|
||||
- **Error Handling**: Handle `isLoading` and `error` states appropriately
|
||||
- **Model Selection**: Provide UI for users to choose between available models
|
||||
|
||||
## Implementation Patterns and Best Practices
|
||||
|
||||
### Dialog Component Patterns
|
||||
|
||||
When using Dialog components, always ensure accessibility compliance by including required elements:
|
||||
|
||||
```tsx
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
|
||||
|
||||
// ✅ Correct - Always include DialogHeader with DialogTitle
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Dialog Title</DialogTitle>
|
||||
<DialogDescription>
|
||||
Optional description for screen readers
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
{/* Dialog content */}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
```
|
||||
|
||||
**Important**: Even if you want to hide the title visually, use the `VisuallyHidden` component to maintain accessibility:
|
||||
|
||||
```tsx
|
||||
import { VisuallyHidden } from "@radix-ui/react-visually-hidden";
|
||||
|
||||
<DialogHeader>
|
||||
<VisuallyHidden>
|
||||
<DialogTitle>Hidden Title for Screen Readers</DialogTitle>
|
||||
</VisuallyHidden>
|
||||
</DialogHeader>
|
||||
```
|
||||
|
||||
### Streaming Response Handling
|
||||
|
||||
When implementing streaming chat interfaces, always accumulate streamed content in a local variable before clearing the streaming state to prevent content loss:
|
||||
|
||||
```tsx
|
||||
const handleStreamingResponse = async () => {
|
||||
let streamedContent = ''; // ✅ Use local variable to accumulate content
|
||||
|
||||
try {
|
||||
await sendStreamingMessage(messages, model, (chunk) => {
|
||||
streamedContent += chunk; // ✅ Accumulate in local variable
|
||||
setCurrentStreamingMessage(streamedContent); // Update UI
|
||||
});
|
||||
|
||||
// ✅ Save accumulated content to persistent state
|
||||
if (streamedContent.trim()) {
|
||||
const assistantMessage: MessageDisplay = {
|
||||
id: Date.now().toString(),
|
||||
role: 'assistant',
|
||||
content: streamedContent, // ✅ Use accumulated content
|
||||
timestamp: new Date()
|
||||
};
|
||||
setMessages(prev => [...prev, assistantMessage]);
|
||||
}
|
||||
} finally {
|
||||
setCurrentStreamingMessage(''); // ✅ Clear streaming state after saving
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Error Boundary Patterns
|
||||
|
||||
Always wrap AI components with error boundaries and provide user-friendly error messages for common failure scenarios:
|
||||
|
||||
```tsx
|
||||
import { ErrorBoundary } from '@/components/ErrorBoundary';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
|
||||
function AIChatWithErrorBoundary() {
|
||||
return (
|
||||
<ErrorBoundary
|
||||
fallback={
|
||||
<div className="p-4">
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
Something went wrong with the AI chat. Please refresh the page and try again.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<AIChat />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
// In your AI component, handle specific error types gracefully:
|
||||
function useAIWithErrorHandling() {
|
||||
const { sendChatMessage, error, clearError } = useShakespeare();
|
||||
|
||||
const sendMessage = async (messages: ChatMessage[], modelId: string) => {
|
||||
try {
|
||||
await sendChatMessage(messages, modelId);
|
||||
} catch (err) {
|
||||
// Handle specific error types with user-friendly messages
|
||||
if (err.message.includes('401')) {
|
||||
throw new Error('Authentication failed. Please log in again.');
|
||||
} else if (err.message.includes('402')) {
|
||||
throw new Error('Insufficient credits. Please add credits to use premium features.');
|
||||
} else if (err.message.includes('network')) {
|
||||
throw new Error('Network error. Please check your internet connection.');
|
||||
}
|
||||
throw err; // Re-throw for error boundary
|
||||
}
|
||||
};
|
||||
|
||||
return { sendMessage, error, clearError };
|
||||
}
|
||||
```
|
||||
@@ -1,54 +0,0 @@
|
||||
# Adding Nostr Comments Sections
|
||||
|
||||
The project includes a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event or URL. The `CommentsSection` component provides a full-featured commenting interface with threaded replies, user authentication, and real-time updates.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
```tsx
|
||||
import { CommentsSection } from "@/components/comments/CommentsSection";
|
||||
|
||||
function ArticlePage({ article }: { article: NostrEvent }) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Your article content */}
|
||||
<div>{/* article content */}</div>
|
||||
|
||||
{/* Comments section */}
|
||||
<CommentsSection root={article} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Props and Customization
|
||||
|
||||
The `CommentsSection` component accepts the following props:
|
||||
|
||||
- **`root`** (required): The root event or URL to comment on. Can be a `NostrEvent` or `URL` object.
|
||||
- **`title`**: Custom title for the comments section (default: "Comments")
|
||||
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
|
||||
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
|
||||
- **`className`**: Additional CSS classes for styling
|
||||
- **`limit`**: Maximum number of comments to load (default: 500)
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={event}
|
||||
title="Discussion"
|
||||
emptyStateMessage="Start the conversation"
|
||||
emptyStateSubtitle="Share your thoughts about this post"
|
||||
className="mt-8"
|
||||
limit={100}
|
||||
/>
|
||||
```
|
||||
|
||||
## Commenting on URLs
|
||||
|
||||
The comments system also supports commenting on external URLs, making it useful for web pages, articles, or any online content:
|
||||
|
||||
```tsx
|
||||
<CommentsSection
|
||||
root={new URL("https://example.com/article")}
|
||||
title="Comments on this article"
|
||||
/>
|
||||
```
|
||||
@@ -1,438 +0,0 @@
|
||||
### 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.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Enable Direct Messaging
|
||||
|
||||
The `DMProvider` is already added to your app, but **disabled by default**. To enable messaging, pass `enabled: true` in the config:
|
||||
|
||||
```tsx
|
||||
import { DMProvider } from '@/contexts/DMContext';
|
||||
import { PROTOCOL_MODE } from '@/lib/dmConstants';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<DMProvider config={{
|
||||
enabled: true, // Enable the DM system
|
||||
protocolMode: PROTOCOL_MODE.NIP17_ONLY
|
||||
}}>
|
||||
{/* Your app components */}
|
||||
</DMProvider>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**Config 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.BOTH` - 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.
|
||||
|
||||
### 2. Send Messages
|
||||
|
||||
```tsx
|
||||
import { useDMContext } from '@/contexts/DMContext';
|
||||
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>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Display Conversations
|
||||
|
||||
```tsx
|
||||
import { useDMContext } from '@/contexts/DMContext';
|
||||
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>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Display Messages in a Conversation
|
||||
|
||||
```tsx
|
||||
import { useConversationMessages } from '@/contexts/DMContext';
|
||||
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, type FileAttachment } from '@/contexts/DMContext';
|
||||
import { useUploadFile } from '@/hooks/useUploadFile';
|
||||
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
||||
|
||||
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 '@/contexts/DMContext';
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
### Infinite Scroll for Nostr Feeds
|
||||
|
||||
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
|
||||
|
||||
```typescript
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
|
||||
export function useGlobalFeed() {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useInfiniteQuery({
|
||||
queryKey: ['global-feed'],
|
||||
queryFn: async ({ pageParam, signal }) => {
|
||||
const filter = { kinds: [1], limit: 20 };
|
||||
if (pageParam) filter.until = pageParam;
|
||||
|
||||
const events = await nostr.query([filter], {
|
||||
signal: AbortSignal.any([signal, AbortSignal.timeout(1500)])
|
||||
});
|
||||
|
||||
return events;
|
||||
},
|
||||
getNextPageParam: (lastPage) => {
|
||||
if (lastPage.length === 0) return undefined;
|
||||
return lastPage[lastPage.length - 1].created_at - 1; // Subtract 1 since 'until' is inclusive
|
||||
},
|
||||
initialPageParam: undefined,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Example usage with intersection observer for automatic loading:
|
||||
|
||||
```tsx
|
||||
import { useInView } from 'react-intersection-observer';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
function GlobalFeed() {
|
||||
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
|
||||
const { ref, inView } = useInView();
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage();
|
||||
}
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]);
|
||||
|
||||
// Remove duplicate events by ID
|
||||
const posts = useMemo(() => {
|
||||
const seen = new Set();
|
||||
return data?.pages.flat().filter(event => {
|
||||
if (!event.id || seen.has(event.id)) return false;
|
||||
seen.add(event.id);
|
||||
return true;
|
||||
}) || [];
|
||||
}, [data?.pages]);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{posts.map((post) => (
|
||||
<PostCard key={post.id} post={post} />
|
||||
))}
|
||||
{hasNextPage && (
|
||||
<div ref={ref} className="py-4">
|
||||
{isFetchingNextPage && <Skeleton className="h-20 w-full" />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
Generated
+83
-163
@@ -11,8 +11,8 @@
|
||||
"@fontsource-variable/inter": "^5.2.6",
|
||||
"@getalby/sdk": "^5.1.1",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
"@nostrify/nostrify": "^0.47.1",
|
||||
"@nostrify/react": "^0.2.17",
|
||||
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
|
||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
||||
@@ -43,13 +43,11 @@
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
"@unhead/react": "^2.0.10",
|
||||
"buffer": "^6.0.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.0.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"idb": "^8.0.3",
|
||||
"input-otp": "^1.2.4",
|
||||
"lucide-react": "^0.462.0",
|
||||
"nostr-tools": "^2.13.0",
|
||||
@@ -65,6 +63,7 @@
|
||||
"tailwind-merge": "^2.5.2",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"vaul": "^0.9.3",
|
||||
"webln": "^0.3.2",
|
||||
"zod": "^3.25.71"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -79,7 +78,6 @@
|
||||
"@types/react": "^18.3.1",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||
"@webbtc/webln-types": "^3.0.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"eslint": "^9.9.0",
|
||||
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
||||
@@ -1172,6 +1170,35 @@
|
||||
"@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": {
|
||||
"version": "0.5.3",
|
||||
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-0.5.3.tgz",
|
||||
@@ -1253,64 +1280,31 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@nostrify/nostrify": {
|
||||
"version": "0.47.1",
|
||||
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.47.1.tgz",
|
||||
"integrity": "sha512-8jdAeKIyyDK/UQN92WgrQn9+B067HYcjfW35TpIjNLAT9qYe+KYFHaC9O6PD+I1DvLHziJMxk4Q18Fu4fqOiAQ==",
|
||||
"name": "@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": {
|
||||
"@nostrify/types": "0.36.7",
|
||||
"@scure/base": "^1.2.6",
|
||||
"@std/encoding": "npm:@jsr/std__encoding@^0.224.1",
|
||||
"@types/node": "^24.1.0",
|
||||
"@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",
|
||||
"ws": "^8.18.3",
|
||||
"zod": "^3.23.8"
|
||||
}
|
||||
},
|
||||
"node_modules/@nostrify/nostrify/node_modules/@scure/base": {
|
||||
"version": "1.2.6",
|
||||
"resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz",
|
||||
"integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@nostrify/nostrify/node_modules/@types/node": {
|
||||
"version": "24.9.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.9.1.tgz",
|
||||
"integrity": "sha512-QoiaXANRkSXK6p0Duvt56W208du4P9Uye9hWLWgGMDTEoKPhuenzNcC4vGUmrNkiOKTlIrBoyNQYNpSwfEZXSg==",
|
||||
"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.17",
|
||||
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.2.17.tgz",
|
||||
"integrity": "sha512-IG6XPiNBe1nDFZ055EnWufxASPjgOZ2cE53Hjanj5xQQURwzA946yMhDDzaHmD9lvoBYjuijopmTiyFk2RObHQ==",
|
||||
"name": "@jsr/nostrify__react",
|
||||
"version": "0.2.8",
|
||||
"resolved": "https://npm.jsr.io/~/11/@jsr/nostrify__react/0.2.8.tgz",
|
||||
"integrity": "sha512-9sCsMm1uwuGWU+NhgFf6LS/4JzeRXnGOz+ocA5X3/ncvxZhidPOEAU39QyygRLFo/JYG8OC5wlyH8w0Uejq+VQ==",
|
||||
"dependencies": {
|
||||
"@nostrify/nostrify": "0.47.1",
|
||||
"@nostrify/types": "0.36.7",
|
||||
"@tanstack/react-query": "^5.69.0",
|
||||
"happy-dom": "^17.4.4",
|
||||
"@jsr/nostrify__nostrify": "^0.46.4",
|
||||
"nostr-tools": "^2.13.0",
|
||||
"react": "^18.0.0",
|
||||
"react-dom": "^18.0.0"
|
||||
"react": "^18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@nostrify/types": {
|
||||
"version": "0.36.7",
|
||||
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.7.tgz",
|
||||
"integrity": "sha512-Jdf2eWdIzonMzic/st4ltre7XIcXVNTjmcbKpw4xGEfNmoq2Y4wj8KcSB6s0TUqxcLEyiXnyGP8EDx/gEVri9A=="
|
||||
},
|
||||
"node_modules/@pkgjs/parseargs": {
|
||||
"version": "0.11.0",
|
||||
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
|
||||
@@ -3055,12 +3049,6 @@
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@std/encoding": {
|
||||
"name": "@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/@swc/core": {
|
||||
"version": "1.11.24",
|
||||
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz",
|
||||
@@ -3428,6 +3416,15 @@
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@types/chrome": {
|
||||
"version": "0.0.74",
|
||||
"resolved": "https://registry.npmjs.org/@types/chrome/-/chrome-0.0.74.tgz",
|
||||
"integrity": "sha512-hzosS5CkQcIKCgxcsV2AzbJ36KNxG/Db2YEN/erEu7Boprg+KpMDLBQqKFmSo+JkQMGqRcicUyqCowJpuT+C6A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/filesystem": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/d3-array": {
|
||||
"version": "3.2.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.1.tgz",
|
||||
@@ -3497,6 +3494,21 @@
|
||||
"integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/filesystem": {
|
||||
"version": "0.0.36",
|
||||
"resolved": "https://registry.npmjs.org/@types/filesystem/-/filesystem-0.0.36.tgz",
|
||||
"integrity": "sha512-vPDXOZuannb9FZdxgHnqSwAG/jvdGM8Wq+6N4D/d80z+D4HWH+bItqsZaVRQykAn6WEVeEkLm2oQigyHtgb0RA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/filewriter": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/filewriter": {
|
||||
"version": "0.0.33",
|
||||
"resolved": "https://registry.npmjs.org/@types/filewriter/-/filewriter-0.0.33.tgz",
|
||||
"integrity": "sha512-xFU8ZXTw4gd358lb2jw25nxY9QAgqn2+bKKjKOYfNCzN4DKCFetK7sPtrlpg66Ywe3vWY9FNxprZawAh9wfJ3g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/json-schema": {
|
||||
"version": "7.0.15",
|
||||
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
|
||||
@@ -3917,17 +3929,6 @@
|
||||
"url": "https://opencollective.com/vitest"
|
||||
}
|
||||
},
|
||||
"node_modules/@webbtc/webln-types": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@webbtc/webln-types/-/webln-types-3.0.0.tgz",
|
||||
"integrity": "sha512-aXfTHLKz5lysd+6xTeWl+qHNh/p3qVYbeLo+yDN5cUDmhie2ZoGvkppfWxzbGkcFBzb6dJyQ2/i2cbmDHas+zQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "lightning",
|
||||
"url": "lightning:[email protected]"
|
||||
}
|
||||
},
|
||||
"node_modules/acorn": {
|
||||
"version": "8.15.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
||||
@@ -4128,26 +4129,6 @@
|
||||
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
||||
"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": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
|
||||
@@ -4216,30 +4197,6 @@
|
||||
"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": {
|
||||
"version": "6.7.14",
|
||||
"resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
|
||||
@@ -5447,28 +5404,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/happy-dom": {
|
||||
"version": "17.6.3",
|
||||
"resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-17.6.3.tgz",
|
||||
"integrity": "sha512-UVIHeVhxmxedbWPCfgS55Jg2rDfwf2BCKeylcPSqazLz5w3Kri7Q4xdBJubsr/+VUzFLh0VjIvh13RaDA2/Xug==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"webidl-conversions": "^7.0.0",
|
||||
"whatwg-mimetype": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/happy-dom/node_modules/whatwg-mimetype": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",
|
||||
"integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/has-flag": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
|
||||
@@ -5551,32 +5486,6 @@
|
||||
"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": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
@@ -8096,11 +8005,21 @@
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
|
||||
"integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/webln": {
|
||||
"version": "0.3.2",
|
||||
"resolved": "https://registry.npmjs.org/webln/-/webln-0.3.2.tgz",
|
||||
"integrity": "sha512-YYT83aOCLup2AmqvJdKtdeBTaZpjC6/JDMe8o6x1kbTYWwiwrtWHyO//PAsPixF3jwFsAkj5DmiceB6w/QSe7Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/chrome": "^0.0.74"
|
||||
}
|
||||
},
|
||||
"node_modules/webpack-virtual-modules": {
|
||||
"version": "0.6.2",
|
||||
"resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz",
|
||||
@@ -8287,9 +8206,10 @@
|
||||
}
|
||||
},
|
||||
"node_modules/ws": {
|
||||
"version": "8.18.3",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
|
||||
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
|
||||
"version": "8.18.2",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.2.tgz",
|
||||
"integrity": "sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
|
||||
+3
-5
@@ -13,8 +13,8 @@
|
||||
"@fontsource-variable/inter": "^5.2.6",
|
||||
"@getalby/sdk": "^5.1.1",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
"@nostrify/nostrify": "^0.47.1",
|
||||
"@nostrify/react": "^0.2.17",
|
||||
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
|
||||
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
||||
@@ -45,13 +45,11 @@
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
"@unhead/react": "^2.0.10",
|
||||
"buffer": "^6.0.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.0.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"idb": "^8.0.3",
|
||||
"input-otp": "^1.2.4",
|
||||
"lucide-react": "^0.462.0",
|
||||
"nostr-tools": "^2.13.0",
|
||||
@@ -67,6 +65,7 @@
|
||||
"tailwind-merge": "^2.5.2",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"vaul": "^0.9.3",
|
||||
"webln": "^0.3.2",
|
||||
"zod": "^3.25.71"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -81,7 +80,6 @@
|
||||
"@types/react": "^18.3.1",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||
"@webbtc/webln-types": "^3.0.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"eslint": "^9.9.0",
|
||||
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
User-agent: *
|
||||
Allow: /
|
||||
+8
-23
@@ -11,9 +11,7 @@ import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { NostrLoginProvider } from '@nostrify/react/login';
|
||||
import { AppProvider } from '@/components/AppProvider';
|
||||
import { NWCProvider } from '@/contexts/NWCContext';
|
||||
import { DMProvider, type DMConfig } from '@/contexts/DMContext';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import { PROTOCOL_MODE } from '@/lib/dmConstants';
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
const head = createHead({
|
||||
@@ -34,27 +32,16 @@ const queryClient = new QueryClient({
|
||||
|
||||
const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.ditto.pub",
|
||||
relayUrl: "wss://relay.primal.net",
|
||||
};
|
||||
|
||||
const presetRelays = [
|
||||
{ url: 'wss://relay.ditto.pub', name: 'Ditto' },
|
||||
{ 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' },
|
||||
];
|
||||
|
||||
const dmConfig: DMConfig = {
|
||||
// Enable or disable DMs entirely
|
||||
enabled: true, // Set to false to completely disable 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.NIP04_OR_NIP17,
|
||||
};
|
||||
|
||||
export function App() {
|
||||
return (
|
||||
<UnheadProvider head={head}>
|
||||
@@ -63,14 +50,12 @@ export function App() {
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<NWCProvider>
|
||||
<DMProvider config={dmConfig}>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</DMProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</NWCProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
|
||||
@@ -2,7 +2,6 @@ import { BrowserRouter, Route, Routes } from "react-router-dom";
|
||||
import { ScrollToTop } from "./components/ScrollToTop";
|
||||
|
||||
import Index from "./pages/Index";
|
||||
import Messages from "./pages/Messages";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
|
||||
@@ -12,7 +11,6 @@ export function AppRouter() {
|
||||
<ScrollToTop />
|
||||
<Routes>
|
||||
<Route path="/" element={<Index />} />
|
||||
<Route path="/messages" element={<Messages />} />
|
||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
||||
<Route path="/:nip19" element={<NIP19Page />} />
|
||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||
|
||||
@@ -14,10 +14,10 @@ interface AppProviderProps {
|
||||
}
|
||||
|
||||
// Zod schema for AppConfig validation
|
||||
const AppConfigSchema = z.object({
|
||||
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
|
||||
theme: z.enum(['dark', 'light', 'system']),
|
||||
relayUrl: z.string().url(),
|
||||
}) satisfies z.ZodType<AppConfig>;
|
||||
});
|
||||
|
||||
export function AppProvider(props: AppProviderProps) {
|
||||
const {
|
||||
@@ -28,25 +28,23 @@ export function AppProvider(props: AppProviderProps) {
|
||||
} = props;
|
||||
|
||||
// App configuration state with localStorage persistence
|
||||
const [rawConfig, setConfig] = useLocalStorage<Partial<AppConfig>>(
|
||||
const [config, setConfig] = useLocalStorage<AppConfig>(
|
||||
storageKey,
|
||||
{},
|
||||
defaultConfig,
|
||||
{
|
||||
serialize: JSON.stringify,
|
||||
deserialize: (value: string) => {
|
||||
const parsed = JSON.parse(value);
|
||||
return AppConfigSchema.partial().parse(parsed);
|
||||
return AppConfigSchema.parse(parsed);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Generic config updater with callback pattern
|
||||
const updateConfig = (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => {
|
||||
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
|
||||
setConfig(updater);
|
||||
};
|
||||
|
||||
const config = { ...defaultConfig, ...rawConfig };
|
||||
|
||||
const appContextValue: AppContextType = {
|
||||
config,
|
||||
updateConfig,
|
||||
|
||||
@@ -20,10 +20,10 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
// Use refs so the pool always has the latest data
|
||||
const relayUrl = useRef<string>(config.relayUrl);
|
||||
|
||||
// Invalidate Nostr queries when relayUrl changes
|
||||
// Update refs when config changes
|
||||
useEffect(() => {
|
||||
relayUrl.current = config.relayUrl;
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr'] });
|
||||
queryClient.resetQueries();
|
||||
}, [config.relayUrl, queryClient]);
|
||||
|
||||
// Initialize NPool only once
|
||||
|
||||
@@ -29,7 +29,6 @@ import { useWallet } from '@/hooks/useWallet';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
|
||||
import type { WebLNProvider } from "@webbtc/webln-types";
|
||||
|
||||
interface WalletModalProps {
|
||||
children?: React.ReactNode;
|
||||
@@ -69,7 +68,8 @@ AddWalletContent.displayName = 'AddWalletContent';
|
||||
|
||||
// Extracted WalletContent to prevent re-renders
|
||||
const WalletContent = forwardRef<HTMLDivElement, {
|
||||
webln: WebLNProvider | null;
|
||||
hasWebLN: boolean;
|
||||
isDetecting: boolean;
|
||||
hasNWC: boolean;
|
||||
connections: NWCConnection[];
|
||||
connectionInfo: Record<string, NWCInfo>;
|
||||
@@ -78,7 +78,8 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
||||
handleRemoveConnection: (cs: string) => void;
|
||||
setAddDialogOpen: (open: boolean) => void;
|
||||
}>(({
|
||||
webln,
|
||||
hasWebLN,
|
||||
isDetecting,
|
||||
hasNWC,
|
||||
connections,
|
||||
connectionInfo,
|
||||
@@ -102,9 +103,9 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{webln && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={webln ? "default" : "secondary"} className="text-xs">
|
||||
{webln ? "Ready" : "Not Found"}
|
||||
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
|
||||
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
|
||||
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
@@ -190,7 +191,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
|
||||
)}
|
||||
</div>
|
||||
{/* Help */}
|
||||
{!webln && connections.length === 0 && (
|
||||
{!hasWebLN && connections.length === 0 && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="text-center py-4 space-y-2">
|
||||
@@ -221,7 +222,7 @@ export function WalletModal({ children, className }: WalletModalProps) {
|
||||
setActiveConnection
|
||||
} = useNWC();
|
||||
|
||||
const { webln } = useWallet();
|
||||
const { hasWebLN, isDetecting } = useWallet();
|
||||
|
||||
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
|
||||
const { toast } = useToast();
|
||||
@@ -262,7 +263,8 @@ export function WalletModal({ children, className }: WalletModalProps) {
|
||||
};
|
||||
|
||||
const walletContentProps = {
|
||||
webln,
|
||||
hasWebLN,
|
||||
isDetecting,
|
||||
hasNWC,
|
||||
connections,
|
||||
connectionInfo,
|
||||
|
||||
@@ -33,7 +33,6 @@ import { useWallet } from '@/hooks/useWallet';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import QRCode from 'qrcode';
|
||||
import type { WebLNProvider } from "@webbtc/webln-types";
|
||||
|
||||
interface ZapDialogProps {
|
||||
target: Event;
|
||||
@@ -56,7 +55,7 @@ interface ZapContentProps {
|
||||
isZapping: boolean;
|
||||
qrCodeUrl: string;
|
||||
copied: boolean;
|
||||
webln: WebLNProvider | null;
|
||||
hasWebLN: boolean;
|
||||
handleZap: () => void;
|
||||
handleCopy: () => void;
|
||||
openInWallet: () => void;
|
||||
@@ -74,7 +73,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
||||
isZapping,
|
||||
qrCodeUrl,
|
||||
copied,
|
||||
webln,
|
||||
hasWebLN,
|
||||
handleZap,
|
||||
handleCopy,
|
||||
openInWallet,
|
||||
@@ -139,7 +138,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
||||
|
||||
{/* Payment buttons */}
|
||||
<div className="space-y-3 mt-4">
|
||||
{webln && (
|
||||
{hasWebLN && (
|
||||
<Button
|
||||
onClick={() => {
|
||||
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
|
||||
@@ -235,12 +234,13 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
|
||||
));
|
||||
ZapContent.displayName = 'ZapContent';
|
||||
|
||||
|
||||
export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { user } = useCurrentUser();
|
||||
const { data: author } = useAuthor(target.pubkey);
|
||||
const { toast } = useToast();
|
||||
const { webln, activeNWC } = useWallet();
|
||||
const { webln, activeNWC, hasWebLN, detectWebLN } = useWallet();
|
||||
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
|
||||
const [amount, setAmount] = useState<number | string>(100);
|
||||
const [comment, setComment] = useState<string>('');
|
||||
@@ -255,6 +255,13 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
}
|
||||
}, [target]);
|
||||
|
||||
// Detect WebLN when dialog opens
|
||||
useEffect(() => {
|
||||
if (open && !hasWebLN) {
|
||||
detectWebLN();
|
||||
}
|
||||
}, [open, hasWebLN, detectWebLN]);
|
||||
|
||||
// Generate QR code
|
||||
useEffect(() => {
|
||||
let isCancelled = false;
|
||||
@@ -338,7 +345,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
|
||||
isZapping,
|
||||
qrCodeUrl,
|
||||
copied,
|
||||
webln,
|
||||
hasWebLN,
|
||||
handleZap,
|
||||
handleCopy,
|
||||
openInWallet,
|
||||
|
||||
@@ -1,408 +0,0 @@
|
||||
import { useState, useRef, useEffect, useCallback, memo } from 'react';
|
||||
import { useConversationMessages, useDMContext } from '@/contexts/DMContext';
|
||||
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>
|
||||
);
|
||||
};
|
||||
@@ -1,266 +0,0 @@
|
||||
import { useMemo, useState, memo } from 'react';
|
||||
import { AlertTriangle, Info, Loader2 } from 'lucide-react';
|
||||
import { useDMContext } from '@/contexts/DMContext';
|
||||
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>
|
||||
);
|
||||
};
|
||||
@@ -1,84 +0,0 @@
|
||||
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 '@/contexts/DMContext';
|
||||
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>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,214 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { RefreshCw, Database, Wifi, CheckCircle2, Loader2 } from 'lucide-react';
|
||||
import { useDMContext } from '@/contexts/DMContext';
|
||||
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)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit] [&>div]:!block [&>div]:!w-full">
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
|
||||
@@ -13,7 +13,7 @@ export interface AppContextType {
|
||||
/** Current application configuration */
|
||||
config: AppConfig;
|
||||
/** Update configuration using a callback that receives current config and returns new config */
|
||||
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
|
||||
updateConfig: (updater: (currentConfig: AppConfig) => AppConfig) => void;
|
||||
/** Optional list of preset relays to display in the RelaySelector */
|
||||
presetRelays?: { name: string; url: string }[];
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -28,7 +28,6 @@ export function useAuthor(pubkey: string | undefined) {
|
||||
return { event };
|
||||
}
|
||||
},
|
||||
staleTime: 5 * 60 * 1000, // Keep cached data fresh for 5 minutes
|
||||
retry: 3,
|
||||
});
|
||||
}
|
||||
@@ -6,7 +6,7 @@ export function useComments(root: NostrEvent | URL, limit?: number) {
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id, limit],
|
||||
queryKey: ['comments', root instanceof URL ? root.toString() : root.id, limit],
|
||||
queryFn: async (c) => {
|
||||
const filter: NostrFilter = { kinds: [1111] };
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ export function useLoggedInAccounts() {
|
||||
const { logins, setLogin, removeLogin } = useNostrLogin();
|
||||
|
||||
const { data: authors = [] } = useQuery({
|
||||
queryKey: ['nostr', 'logins', logins.map((l) => l.id).join(';')],
|
||||
queryKey: ['logins', logins.map((l) => l.id).join(';')],
|
||||
queryFn: async ({ signal }) => {
|
||||
const events = await nostr.query(
|
||||
[{ kinds: [0], authors: logins.map((l) => l.pubkey) }],
|
||||
|
||||
@@ -0,0 +1,615 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
// Your VAPID public key
|
||||
const VAPID_PUBLIC_KEY = 'BIur4J9v796yU2ZUhaka6exwLAKUhAnDv0zJhrf_T1yuFs4jh4g8IaYygGAJ7u1KxZdu2Dwxh1ae5ob8yClHamc';
|
||||
|
||||
/**
|
||||
* Push subscription configuration for Web Push API
|
||||
*/
|
||||
export interface PushSubscription {
|
||||
endpoint: string;
|
||||
p256dh_key: string;
|
||||
auth_key: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Nostr event filter for push notifications
|
||||
*/
|
||||
export interface NotificationFilter {
|
||||
kinds?: number[];
|
||||
authors?: string[];
|
||||
"#p"?: string[];
|
||||
"#t"?: string[];
|
||||
since?: number;
|
||||
until?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Notification content configuration
|
||||
*/
|
||||
export interface NotificationConfig {
|
||||
title: string;
|
||||
body: string;
|
||||
icon?: string;
|
||||
badge?: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete subscription object for push notifications
|
||||
*/
|
||||
export interface PushNotificationSubscription {
|
||||
subscription_id: string;
|
||||
domain: string;
|
||||
filter: NotificationFilter;
|
||||
notification: NotificationConfig;
|
||||
push_subscription: PushSubscription;
|
||||
}
|
||||
|
||||
/**
|
||||
* RPC request structure for push notification server
|
||||
*/
|
||||
interface RPCRequest {
|
||||
method: 'register_subscription' | 'update_subscription' | 'delete_subscription' | 'list_subscriptions' | 'get_subscription';
|
||||
params: Record<string, unknown>;
|
||||
request_id: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for managing push notifications via Nostr RPC
|
||||
* Sends encrypted RPC events to a push notification worker
|
||||
*/
|
||||
export function usePush(workerPubkey?: string) {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Default worker pubkey - your actual push notification server
|
||||
const defaultWorkerPubkey = workerPubkey || '7c3be2769c76eecd6c6e27276722dfae0d8ad201825253452153b90093c41654';
|
||||
|
||||
const clearError = useCallback(() => {
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Send an encrypted RPC request to the push notification worker
|
||||
*/
|
||||
const sendRPCRequest = useCallback(async (
|
||||
method: RPCRequest['method'],
|
||||
params: Record<string, unknown>
|
||||
): Promise<void> => {
|
||||
if (!user?.signer) {
|
||||
throw new Error('User must be logged in to manage push notifications');
|
||||
}
|
||||
|
||||
if (!user.signer.nip44) {
|
||||
throw new Error('Signer must support NIP-44 encryption for push notifications');
|
||||
}
|
||||
|
||||
// Decode worker pubkey if it's in npub format
|
||||
let workerHex = defaultWorkerPubkey;
|
||||
if (defaultWorkerPubkey.startsWith('npub1')) {
|
||||
const decoded = nip19.decode(defaultWorkerPubkey);
|
||||
if (decoded.type !== 'npub') {
|
||||
throw new Error('Invalid worker pubkey format');
|
||||
}
|
||||
workerHex = decoded.data;
|
||||
}
|
||||
|
||||
const requestId = `req_${crypto.randomUUID().replace(/-/g, "").slice(0, 8)}`;
|
||||
|
||||
const request: RPCRequest = {
|
||||
method,
|
||||
params,
|
||||
request_id: requestId,
|
||||
};
|
||||
|
||||
try {
|
||||
// Encrypt the request using NIP-44
|
||||
const payload = JSON.stringify(request);
|
||||
console.log('Encrypting RPC request payload:', payload);
|
||||
|
||||
const encryptedRequest = await user.signer.nip44.encrypt(workerHex, payload);
|
||||
console.log('Encrypted request:', encryptedRequest);
|
||||
|
||||
// Create unsigned RPC event (kind 25742)
|
||||
const unsignedEvent = {
|
||||
kind: 25742,
|
||||
content: encryptedRequest,
|
||||
tags: [
|
||||
['p', workerHex],
|
||||
['rpc', requestId],
|
||||
['method', method],
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
};
|
||||
|
||||
console.log('Signing RPC event:', unsignedEvent);
|
||||
console.log('Target worker pubkey:', workerHex);
|
||||
|
||||
// Sign the event using the user's signer
|
||||
const signedEvent = await user.signer.signEvent(unsignedEvent);
|
||||
console.log('Signed RPC event:', signedEvent);
|
||||
|
||||
// Send the signed RPC event
|
||||
const result = await nostr.event(signedEvent);
|
||||
console.log('RPC event sent result:', result);
|
||||
|
||||
return;
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
|
||||
console.error('RPC send error:', err);
|
||||
throw new Error(`Failed to send push notification request: ${errorMessage}`);
|
||||
}
|
||||
}, [user, nostr, defaultWorkerPubkey]);
|
||||
|
||||
/**
|
||||
* Register a new push notification subscription
|
||||
*/
|
||||
const registerSubscription = useCallback(async (
|
||||
subscriptionId: string,
|
||||
domain: string,
|
||||
filter: NotificationFilter,
|
||||
notification: NotificationConfig,
|
||||
pushSubscription: PushSubscription
|
||||
): Promise<void> => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await sendRPCRequest('register_subscription', {
|
||||
subscription_id: subscriptionId,
|
||||
domain,
|
||||
filter,
|
||||
notification,
|
||||
push_subscription: pushSubscription,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Push notifications enabled',
|
||||
description: 'You will now receive push notifications for this content.',
|
||||
});
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to register subscription';
|
||||
setError(errorMessage);
|
||||
toast({
|
||||
title: 'Failed to enable notifications',
|
||||
description: errorMessage,
|
||||
variant: 'destructive',
|
||||
});
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [sendRPCRequest, toast]);
|
||||
|
||||
/**
|
||||
* Update an existing push notification subscription
|
||||
*/
|
||||
const updateSubscription = useCallback(async (
|
||||
subscriptionId: string,
|
||||
domain: string,
|
||||
updates: Partial<Pick<PushNotificationSubscription, 'filter' | 'notification' | 'push_subscription'> & { is_active: boolean }>
|
||||
): Promise<void> => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await sendRPCRequest('update_subscription', {
|
||||
subscription_id: subscriptionId,
|
||||
domain,
|
||||
updates,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Subscription updated',
|
||||
description: 'Your push notification settings have been updated.',
|
||||
});
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to update subscription';
|
||||
setError(errorMessage);
|
||||
toast({
|
||||
title: 'Failed to update notifications',
|
||||
description: errorMessage,
|
||||
variant: 'destructive',
|
||||
});
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [sendRPCRequest, toast]);
|
||||
|
||||
/**
|
||||
* Delete a push notification subscription
|
||||
*/
|
||||
const deleteSubscription = useCallback(async (
|
||||
subscriptionId: string,
|
||||
domain: string
|
||||
): Promise<void> => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await sendRPCRequest('delete_subscription', {
|
||||
subscription_id: subscriptionId,
|
||||
domain,
|
||||
});
|
||||
|
||||
toast({
|
||||
title: 'Push notifications disabled',
|
||||
description: 'You will no longer receive push notifications for this content.',
|
||||
});
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to delete subscription';
|
||||
setError(errorMessage);
|
||||
toast({
|
||||
title: 'Failed to disable notifications',
|
||||
description: errorMessage,
|
||||
variant: 'destructive',
|
||||
});
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [sendRPCRequest, toast]);
|
||||
|
||||
/**
|
||||
* List all subscriptions for a domain
|
||||
*/
|
||||
const listSubscriptions = useCallback(async (domain: string): Promise<void> => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await sendRPCRequest('list_subscriptions', { domain });
|
||||
// Note: This is a fire-and-forget operation - the worker logs the results
|
||||
// In a full implementation, you might want to listen for response events
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to list subscriptions';
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [sendRPCRequest]);
|
||||
|
||||
/**
|
||||
* Get a specific subscription
|
||||
*/
|
||||
const getSubscription = useCallback(async (subscriptionId: string): Promise<void> => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await sendRPCRequest('get_subscription', { subscription_id: subscriptionId });
|
||||
// Note: This is a fire-and-forget operation - the worker logs the results
|
||||
// In a full implementation, you might want to listen for response events
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to get subscription';
|
||||
setError(errorMessage);
|
||||
throw err;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [sendRPCRequest]);
|
||||
|
||||
/**
|
||||
* Request browser permission for push notifications
|
||||
*/
|
||||
const requestNotificationPermission = useCallback(async (): Promise<NotificationPermission> => {
|
||||
if (!('Notification' in window)) {
|
||||
throw new Error('This browser does not support push notifications');
|
||||
}
|
||||
|
||||
if (Notification.permission === 'granted') {
|
||||
return 'granted';
|
||||
}
|
||||
|
||||
if (Notification.permission === 'denied') {
|
||||
throw new Error('Push notifications are blocked. Please enable them in your browser settings.');
|
||||
}
|
||||
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission !== 'granted') {
|
||||
throw new Error('Push notification permission was denied');
|
||||
}
|
||||
|
||||
return permission;
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Convert npub to hex format for use in filters
|
||||
*/
|
||||
const convertNpubToHex = useCallback((pubkey: string): string => {
|
||||
if (pubkey.startsWith('npub1')) {
|
||||
try {
|
||||
const decoded = nip19.decode(pubkey);
|
||||
if (decoded.type !== 'npub') {
|
||||
throw new Error('Invalid npub format');
|
||||
}
|
||||
return decoded.data;
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to decode npub: ${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
// If it's already hex format, return as-is
|
||||
return pubkey;
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Convert VAPID key from base64url string to Uint8Array (matches working implementation)
|
||||
*/
|
||||
const convertVapidKey = useCallback((key: string): Uint8Array => {
|
||||
try {
|
||||
// Add padding if needed
|
||||
const padding = '='.repeat((4 - (key.length % 4)) % 4);
|
||||
const base64 = (key + padding).replace(/-/g, '+').replace(/_/g, '/');
|
||||
|
||||
// Decode base64 to binary string
|
||||
const rawData = window.atob(base64);
|
||||
|
||||
// Convert binary string to Uint8Array
|
||||
const outputArray = new Uint8Array(rawData.length);
|
||||
for (let i = 0; i < rawData.length; ++i) {
|
||||
outputArray[i] = rawData.charCodeAt(i);
|
||||
}
|
||||
|
||||
console.log('VAPID key converted:', {
|
||||
originalLength: key.length,
|
||||
base64Length: base64.length,
|
||||
outputLength: outputArray.length,
|
||||
firstBytes: Array.from(outputArray.slice(0, 10))
|
||||
});
|
||||
|
||||
return outputArray;
|
||||
} catch (err) {
|
||||
throw new Error(`Invalid VAPID key format: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* Subscribe to browser push notifications and get subscription details
|
||||
*/
|
||||
const subscribeToPush = useCallback(async (vapidPublicKey: string = VAPID_PUBLIC_KEY): Promise<PushSubscription> => {
|
||||
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
|
||||
throw new Error('Push notifications are not supported in this browser');
|
||||
}
|
||||
|
||||
await requestNotificationPermission();
|
||||
|
||||
// Register service worker and wait for it to be ready
|
||||
const registration = await navigator.serviceWorker.ready;
|
||||
console.log('Service worker ready:', registration);
|
||||
console.log('Service worker scope:', registration.scope);
|
||||
console.log('Service worker active:', !!registration.active);
|
||||
|
||||
// Check if already subscribed
|
||||
const existingSubscription = await registration.pushManager.getSubscription();
|
||||
console.log('Existing subscription:', existingSubscription);
|
||||
|
||||
// Convert VAPID key to proper format
|
||||
console.log('VAPID public key (base64):', vapidPublicKey);
|
||||
const applicationServerKey = convertVapidKey(vapidPublicKey);
|
||||
console.log('VAPID key converted to Uint8Array, length:', applicationServerKey.length);
|
||||
|
||||
let subscription;
|
||||
try {
|
||||
console.log('Attempting to subscribe to push manager...');
|
||||
|
||||
// Subscribe to push notifications
|
||||
subscription = await registration.pushManager.subscribe({
|
||||
userVisibleOnly: true,
|
||||
applicationServerKey,
|
||||
});
|
||||
|
||||
console.log('Push subscription successful:', subscription);
|
||||
} catch (pushError: any) {
|
||||
console.error('Push subscription failed with error:', pushError);
|
||||
console.error('Error name:', pushError.name);
|
||||
console.error('Error message:', pushError.message);
|
||||
|
||||
// Provide specific error messages based on error type
|
||||
if (pushError.name === 'InvalidStateError') {
|
||||
throw new Error('Push subscription failed: Invalid state (possibly already subscribed)');
|
||||
} else if (pushError.name === 'NotAllowedError') {
|
||||
throw new Error('Push subscription failed: Permission denied by user');
|
||||
} else if (pushError.name === 'NotSupportedError') {
|
||||
throw new Error('Push subscription failed: Push not supported by this browser/service');
|
||||
} else if (pushError.name === 'AbortError') {
|
||||
throw new Error('Push subscription failed: Request was aborted (VAPID key mismatch?)');
|
||||
} else {
|
||||
throw new Error(`Push subscription failed: ${pushError.name} - ${pushError.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Extract keys safely
|
||||
const subscriptionJson = subscription.toJSON();
|
||||
const keys = subscriptionJson.keys;
|
||||
|
||||
if (!keys?.p256dh || !keys?.auth) {
|
||||
throw new Error('Invalid subscription keys received');
|
||||
}
|
||||
|
||||
// Convert to our format
|
||||
return {
|
||||
endpoint: subscription.endpoint,
|
||||
p256dh_key: keys.p256dh,
|
||||
auth_key: keys.auth,
|
||||
};
|
||||
}, [requestNotificationPermission, convertVapidKey]);
|
||||
|
||||
/**
|
||||
* Helper function to create a subscription for following an author
|
||||
*/
|
||||
const subscribeToAuthor = useCallback(async (
|
||||
authorPubkey: string,
|
||||
vapidPublicKey: string = VAPID_PUBLIC_KEY,
|
||||
domain: string = window.location.hostname,
|
||||
customNotification?: Partial<NotificationConfig>
|
||||
): Promise<void> => {
|
||||
const pushSubscription = await subscribeToPush(vapidPublicKey);
|
||||
|
||||
// Convert npub to hex format for the filter
|
||||
const authorHex = convertNpubToHex(authorPubkey);
|
||||
|
||||
const subscriptionId = `follow-${authorHex.slice(0, 16)}-${Date.now()}`;
|
||||
|
||||
const filter: NotificationFilter = {
|
||||
kinds: [1], // Text notes
|
||||
authors: [authorHex], // Use hex format
|
||||
limit: 50,
|
||||
};
|
||||
|
||||
const notification: NotificationConfig = {
|
||||
title: '{{author_name}} posted something!',
|
||||
body: '{{content}}',
|
||||
icon: '/icon-192x192.png',
|
||||
badge: '/badge-72x72.png',
|
||||
data: {
|
||||
type: 'new_post',
|
||||
author: authorHex, // Store hex format in data as well
|
||||
},
|
||||
...customNotification,
|
||||
};
|
||||
|
||||
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
|
||||
}, [subscribeToPush, registerSubscription, convertNpubToHex]);
|
||||
|
||||
/**
|
||||
* Helper function to create a subscription for mentions
|
||||
*/
|
||||
const subscribeToMentions = useCallback(async (
|
||||
userPubkey: string,
|
||||
vapidPublicKey: string = VAPID_PUBLIC_KEY,
|
||||
domain: string = window.location.hostname,
|
||||
customNotification?: Partial<NotificationConfig>
|
||||
): Promise<void> => {
|
||||
const pushSubscription = await subscribeToPush(vapidPublicKey);
|
||||
|
||||
// Convert npub to hex format for the filter
|
||||
const userHex = convertNpubToHex(userPubkey);
|
||||
|
||||
const subscriptionId = `mentions-${userHex.slice(0, 16)}-${Date.now()}`;
|
||||
|
||||
const filter: NotificationFilter = {
|
||||
kinds: [1], // Text notes
|
||||
"#p": [userHex], // Mentions of the user (use hex format)
|
||||
limit: 50,
|
||||
};
|
||||
|
||||
const notification: NotificationConfig = {
|
||||
title: '{{author_name}} mentioned you!',
|
||||
body: '{{content}}',
|
||||
icon: '/icon-192x192.png',
|
||||
badge: '/badge-72x72.png',
|
||||
data: {
|
||||
type: 'mention',
|
||||
user: userHex, // Store hex format in data as well
|
||||
},
|
||||
...customNotification,
|
||||
};
|
||||
|
||||
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
|
||||
}, [subscribeToPush, registerSubscription, convertNpubToHex]);
|
||||
|
||||
/**
|
||||
* Helper function to create a subscription for hashtags
|
||||
*/
|
||||
const subscribeToHashtag = useCallback(async (
|
||||
hashtag: string,
|
||||
vapidPublicKey: string = VAPID_PUBLIC_KEY,
|
||||
domain: string = window.location.hostname,
|
||||
customNotification?: Partial<NotificationConfig>
|
||||
): Promise<void> => {
|
||||
const pushSubscription = await subscribeToPush(vapidPublicKey);
|
||||
|
||||
const subscriptionId = `hashtag-${hashtag}-${Date.now()}`;
|
||||
|
||||
const filter: NotificationFilter = {
|
||||
kinds: [1], // Text notes
|
||||
"#t": [hashtag], // Posts with the hashtag
|
||||
limit: 50,
|
||||
};
|
||||
|
||||
const notification: NotificationConfig = {
|
||||
title: `{{author_name}} posted about #${hashtag}`,
|
||||
body: `{{content}}`,
|
||||
icon: '/icon-192x192.png',
|
||||
badge: '/badge-72x72.png',
|
||||
data: {
|
||||
type: 'hashtag',
|
||||
hashtag,
|
||||
},
|
||||
...customNotification,
|
||||
};
|
||||
|
||||
await registerSubscription(subscriptionId, domain, filter, notification, pushSubscription);
|
||||
}, [subscribeToPush, registerSubscription]);
|
||||
|
||||
return {
|
||||
// Core RPC methods
|
||||
registerSubscription,
|
||||
updateSubscription,
|
||||
deleteSubscription,
|
||||
listSubscriptions,
|
||||
getSubscription,
|
||||
|
||||
// Browser push notification helpers
|
||||
requestNotificationPermission,
|
||||
subscribeToPush,
|
||||
|
||||
// Convenience methods for common use cases
|
||||
subscribeToAuthor,
|
||||
subscribeToMentions,
|
||||
subscribeToHashtag,
|
||||
|
||||
// State
|
||||
isLoading,
|
||||
error,
|
||||
clearError,
|
||||
|
||||
// Config
|
||||
workerPubkey: defaultWorkerPubkey,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Example usage:
|
||||
*
|
||||
* ```tsx
|
||||
* import { usePush } from '@/hooks/usePush';
|
||||
*
|
||||
* function MyComponent() {
|
||||
* const {
|
||||
* subscribeToAuthor,
|
||||
* subscribeToMentions,
|
||||
* isLoading,
|
||||
* error
|
||||
* } = usePush('npub1yourpushworkerpubkey');
|
||||
*
|
||||
* const handleFollowNotifications = async (authorPubkey: string) => {
|
||||
* try {
|
||||
* await subscribeToAuthor(authorPubkey, 'myapp.com');
|
||||
* } catch (error) {
|
||||
* console.error('Failed to enable notifications:', error);
|
||||
* }
|
||||
* };
|
||||
*
|
||||
* return (
|
||||
* <Button
|
||||
* onClick={() => handleFollowNotifications('npub1author...')}
|
||||
* disabled={isLoading}
|
||||
* >
|
||||
* {isLoading ? 'Enabling...' : 'Enable Notifications'}
|
||||
* </Button>
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
@@ -1,372 +0,0 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useCurrentUser } from './useCurrentUser';
|
||||
import type { NUser } from '@nostrify/react/login';
|
||||
|
||||
// Types for Shakespeare API (compatible with OpenAI ChatCompletionMessageParam)
|
||||
export interface ChatMessage {
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
content: string | Array<{
|
||||
type: 'text' | 'image_url';
|
||||
text?: string;
|
||||
image_url?: {
|
||||
url: string;
|
||||
};
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface ChatCompletionRequest {
|
||||
model: string;
|
||||
messages: ChatMessage[];
|
||||
stream?: boolean;
|
||||
temperature?: number;
|
||||
max_tokens?: number;
|
||||
}
|
||||
|
||||
export interface ChatCompletionResponse {
|
||||
id: string;
|
||||
object: string;
|
||||
created: number;
|
||||
model: string;
|
||||
choices: Array<{
|
||||
index: number;
|
||||
message: ChatMessage;
|
||||
finish_reason: string;
|
||||
}>;
|
||||
usage: {
|
||||
prompt_tokens: number;
|
||||
completion_tokens: number;
|
||||
total_tokens: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface Model {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
object: string;
|
||||
owned_by: string;
|
||||
created: number;
|
||||
context_window: number;
|
||||
pricing: {
|
||||
prompt: string;
|
||||
completion: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ModelsResponse {
|
||||
object: string;
|
||||
data: Model[];
|
||||
}
|
||||
|
||||
// Configuration
|
||||
const SHAKESPEARE_API_URL = 'https://ai.shakespeare.diy/v1';
|
||||
|
||||
// Helper function to create NIP-98 token
|
||||
async function createNIP98Token(
|
||||
method: string,
|
||||
url: string,
|
||||
body?: unknown,
|
||||
user?: NUser
|
||||
): Promise<string> {
|
||||
if (!user?.signer) {
|
||||
throw new Error('User signer is required for NIP-98 authentication');
|
||||
}
|
||||
|
||||
// Create the tags array
|
||||
const tags: string[][] = [
|
||||
['u', url],
|
||||
['method', method]
|
||||
];
|
||||
|
||||
// Add payload hash for requests with body (following NIP-98 spec)
|
||||
if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
|
||||
const bodyString = JSON.stringify(body);
|
||||
const encoder = new TextEncoder();
|
||||
const data = encoder.encode(bodyString);
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
|
||||
const payloadHash = Array.from(new Uint8Array(hashBuffer))
|
||||
.map(b => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
tags.push(['payload', payloadHash]);
|
||||
}
|
||||
|
||||
// Create the HTTP request event
|
||||
const event = await user.signer.signEvent({
|
||||
kind: 27235, // NIP-98 HTTP Auth
|
||||
content: '',
|
||||
tags,
|
||||
created_at: Math.floor(Date.now() / 1000)
|
||||
});
|
||||
|
||||
// Return the token (base64 encoded event)
|
||||
return btoa(JSON.stringify(event));
|
||||
}
|
||||
|
||||
// Helper function to handle API errors with user-friendly messages
|
||||
async function handleAPIError(response: Response) {
|
||||
if (response.status === 401) {
|
||||
throw new Error('Authentication failed. Please make sure you are logged in with a Nostr account.');
|
||||
} else if (response.status === 402) {
|
||||
throw new Error('Insufficient credits. Please add credits to your account to use premium models, or use the free "tybalt" model.');
|
||||
} else if (response.status === 400) {
|
||||
try {
|
||||
const error = await response.json();
|
||||
if (error.error?.type === 'invalid_request_error') {
|
||||
// Handle specific validation errors
|
||||
if (error.error.code === 'minimum_amount_not_met') {
|
||||
throw new Error(`Minimum credit amount is $${error.error.minimum_amount}. Please increase your payment amount.`);
|
||||
} else if (error.error.code === 'unsupported_method') {
|
||||
throw new Error('Payment method not supported. Please use "stripe" or "lightning".');
|
||||
} else if (error.error.code === 'invalid_url') {
|
||||
throw new Error('Invalid redirect URL provided for Stripe payment.');
|
||||
}
|
||||
}
|
||||
throw new Error(`Invalid request: ${error.error?.message || error.details || error.error || 'Please check your request parameters.'}`);
|
||||
} catch (parseError) {
|
||||
throw new Error('Invalid request. Please check your parameters and try again.');
|
||||
}
|
||||
} else if (response.status === 404) {
|
||||
throw new Error('Resource not found. Please check the payment ID or try again.');
|
||||
} else if (response.status >= 500) {
|
||||
throw new Error('Server error. Please try again in a few moments.');
|
||||
} else if (!response.ok) {
|
||||
try {
|
||||
const errorData = await response.json();
|
||||
throw new Error(`API error: ${errorData.error?.message || errorData.details || errorData.error || response.statusText}`);
|
||||
} catch (parseError) {
|
||||
throw new Error(`Network error: ${response.statusText}. Please check your connection and try again.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function useShakespeare() {
|
||||
const { user } = useCurrentUser();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Clear error helper
|
||||
const clearError = useCallback(() => {
|
||||
setError(null);
|
||||
}, []);
|
||||
|
||||
// Chat completion function
|
||||
const sendChatMessage = useCallback(async (
|
||||
messages: ChatMessage[],
|
||||
model: string = 'shakespeare',
|
||||
options?: Partial<ChatCompletionRequest>
|
||||
): Promise<ChatCompletionResponse> => {
|
||||
if (!user) {
|
||||
throw new Error('User must be logged in to use AI features');
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const requestBody: ChatCompletionRequest = {
|
||||
model,
|
||||
messages,
|
||||
...options
|
||||
};
|
||||
|
||||
const token = await createNIP98Token(
|
||||
'POST',
|
||||
`${SHAKESPEARE_API_URL}/chat/completions`,
|
||||
requestBody,
|
||||
user
|
||||
);
|
||||
|
||||
const response = await fetch(`${SHAKESPEARE_API_URL}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Nostr ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
|
||||
await handleAPIError(response);
|
||||
return await response.json();
|
||||
} catch (err) {
|
||||
let errorMessage = 'An unexpected error occurred';
|
||||
|
||||
if (err instanceof Error) {
|
||||
errorMessage = err.message;
|
||||
} else if (typeof err === 'string') {
|
||||
errorMessage = err;
|
||||
}
|
||||
|
||||
// Add context for common issues
|
||||
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
|
||||
errorMessage = 'Network error: Please check your internet connection and try again.';
|
||||
} else if (errorMessage.includes('signer')) {
|
||||
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
|
||||
}
|
||||
|
||||
setError(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
// Streaming chat completion function
|
||||
const sendStreamingMessage = useCallback(async (
|
||||
messages: ChatMessage[],
|
||||
model: string = 'shakespeare',
|
||||
onChunk: (chunk: string) => void,
|
||||
options?: Partial<ChatCompletionRequest>
|
||||
): Promise<void> => {
|
||||
if (!user) {
|
||||
throw new Error('User must be logged in to use AI features');
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const requestBody: ChatCompletionRequest = {
|
||||
model,
|
||||
messages,
|
||||
stream: true,
|
||||
...options
|
||||
};
|
||||
|
||||
const token = await createNIP98Token(
|
||||
'POST',
|
||||
`${SHAKESPEARE_API_URL}/chat/completions`,
|
||||
requestBody,
|
||||
user
|
||||
);
|
||||
|
||||
const response = await fetch(`${SHAKESPEARE_API_URL}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Nostr ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
|
||||
await handleAPIError(response);
|
||||
|
||||
if (!response.body) {
|
||||
throw new Error('No response body');
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
const chunk = decoder.decode(value);
|
||||
const lines = chunk.split('\n');
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data: ')) {
|
||||
const data = line.slice(6);
|
||||
if (data === '[DONE]') return;
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
const content = parsed.choices?.[0]?.delta?.content;
|
||||
if (content) {
|
||||
onChunk(content);
|
||||
}
|
||||
} catch {
|
||||
// Ignore parsing errors for incomplete chunks
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
} catch (err) {
|
||||
let errorMessage = 'An unexpected error occurred';
|
||||
|
||||
if (err instanceof Error) {
|
||||
errorMessage = err.message;
|
||||
} else if (typeof err === 'string') {
|
||||
errorMessage = err;
|
||||
}
|
||||
|
||||
// Add context for common issues
|
||||
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
|
||||
errorMessage = 'Network error: Please check your internet connection and try again.';
|
||||
} else if (errorMessage.includes('signer')) {
|
||||
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
|
||||
}
|
||||
|
||||
setError(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
// Get available models
|
||||
const getAvailableModels = useCallback(async (): Promise<ModelsResponse> => {
|
||||
if (!user) {
|
||||
throw new Error('User must be logged in to use AI features');
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const token = await createNIP98Token(
|
||||
'GET',
|
||||
`${SHAKESPEARE_API_URL}/models`,
|
||||
undefined,
|
||||
user
|
||||
);
|
||||
|
||||
const response = await fetch(`${SHAKESPEARE_API_URL}/models`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': `Nostr ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
await handleAPIError(response);
|
||||
return await response.json();
|
||||
} catch (err) {
|
||||
let errorMessage = 'An unexpected error occurred';
|
||||
|
||||
if (err instanceof Error) {
|
||||
errorMessage = err.message;
|
||||
} else if (typeof err === 'string') {
|
||||
errorMessage = err;
|
||||
}
|
||||
|
||||
// Add context for common issues
|
||||
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
|
||||
errorMessage = 'Network error: Please check your internet connection and try again.';
|
||||
} else if (errorMessage.includes('signer')) {
|
||||
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
|
||||
}
|
||||
|
||||
setError(errorMessage);
|
||||
throw new Error(errorMessage);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
return {
|
||||
// State
|
||||
isLoading,
|
||||
error,
|
||||
isAuthenticated: !!user,
|
||||
|
||||
// Actions
|
||||
sendChatMessage,
|
||||
sendStreamingMessage,
|
||||
getAvailableModels,
|
||||
clearError,
|
||||
};
|
||||
}
|
||||
+58
-5
@@ -1,22 +1,68 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { useNWC } from '@/hooks/useNWCContext';
|
||||
import type { WebLNProvider } from '@webbtc/webln-types';
|
||||
import type { WebLNProvider } from 'webln';
|
||||
import { requestProvider } from 'webln';
|
||||
|
||||
export interface WalletStatus {
|
||||
hasWebLN: boolean;
|
||||
hasNWC: boolean;
|
||||
webln: WebLNProvider | null;
|
||||
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
|
||||
isDetecting: boolean;
|
||||
preferredMethod: 'nwc' | 'webln' | 'manual';
|
||||
}
|
||||
|
||||
export function useWallet() {
|
||||
const [webln, setWebln] = useState<WebLNProvider | null>(null);
|
||||
const [isDetecting, setIsDetecting] = useState(false);
|
||||
const [hasAttemptedDetection, setHasAttemptedDetection] = useState(false);
|
||||
const { connections, getActiveConnection } = useNWC();
|
||||
|
||||
// Get the active connection directly - no memoization to avoid stale state
|
||||
const activeNWC = getActiveConnection();
|
||||
|
||||
// Access WebLN directly from browser global scope
|
||||
const webln = (globalThis as { webln?: WebLNProvider }).webln || null;
|
||||
// Detect WebLN
|
||||
const detectWebLN = useCallback(async () => {
|
||||
if (webln || isDetecting) return webln;
|
||||
|
||||
setIsDetecting(true);
|
||||
try {
|
||||
const provider = await requestProvider();
|
||||
setWebln(provider);
|
||||
setHasAttemptedDetection(true);
|
||||
return provider;
|
||||
} catch (error) {
|
||||
// Only log the error if it's not the common "no provider" error
|
||||
if (error instanceof Error && !error.message.includes('no WebLN provider')) {
|
||||
console.warn('WebLN detection error:', error);
|
||||
}
|
||||
setWebln(null);
|
||||
setHasAttemptedDetection(true);
|
||||
return null;
|
||||
} finally {
|
||||
setIsDetecting(false);
|
||||
}
|
||||
}, [webln, isDetecting]);
|
||||
|
||||
// Only auto-detect once on mount
|
||||
useEffect(() => {
|
||||
if (!hasAttemptedDetection) {
|
||||
detectWebLN();
|
||||
}
|
||||
}, [detectWebLN, hasAttemptedDetection]);
|
||||
|
||||
// Test WebLN connection
|
||||
const testWebLN = useCallback(async (): Promise<boolean> => {
|
||||
if (!webln) return false;
|
||||
|
||||
try {
|
||||
await webln.enable();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('WebLN test failed:', error);
|
||||
return false;
|
||||
}
|
||||
}, [webln]);
|
||||
|
||||
// Calculate status values reactively
|
||||
const hasNWC = useMemo(() => {
|
||||
@@ -31,11 +77,18 @@ export function useWallet() {
|
||||
: 'manual';
|
||||
|
||||
const status: WalletStatus = {
|
||||
hasWebLN: !!webln,
|
||||
hasNWC,
|
||||
webln,
|
||||
activeNWC,
|
||||
isDetecting,
|
||||
preferredMethod,
|
||||
};
|
||||
|
||||
return status;
|
||||
return {
|
||||
...status,
|
||||
hasAttemptedDetection,
|
||||
detectWebLN,
|
||||
testWebLN,
|
||||
};
|
||||
}
|
||||
+4
-16
@@ -7,7 +7,7 @@ import { useNWC } from '@/hooks/useNWCContext';
|
||||
import type { NWCConnection } from '@/hooks/useNWC';
|
||||
import { nip57 } from 'nostr-tools';
|
||||
import type { Event } from 'nostr-tools';
|
||||
import type { WebLNProvider } from '@webbtc/webln-types';
|
||||
import type { WebLNProvider } from 'webln';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
@@ -263,22 +263,10 @@ export function useZaps(
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (webln) { // Try WebLN next
|
||||
try {
|
||||
// For native WebLN, we may need to enable it first
|
||||
let webLnProvider = webln;
|
||||
if (webln.enable && typeof webln.enable === 'function') {
|
||||
const enabledProvider = await webln.enable();
|
||||
// Some implementations return the provider, others return void
|
||||
// Cast to WebLNProvider to handle both cases
|
||||
const provider = enabledProvider as WebLNProvider | undefined;
|
||||
if (provider) {
|
||||
webLnProvider = provider;
|
||||
}
|
||||
}
|
||||
|
||||
await webLnProvider.sendPayment(newInvoice);
|
||||
await webln.sendPayment(newInvoice);
|
||||
|
||||
// Clear states immediately on success
|
||||
setIsZapping(false);
|
||||
@@ -295,7 +283,7 @@ export function useZaps(
|
||||
// Close dialog last to ensure clean state
|
||||
onZapSuccess?.();
|
||||
} catch (weblnError) {
|
||||
console.error('WebLN payment failed, falling back:', weblnError);
|
||||
console.error('webln payment failed, falling back:', weblnError);
|
||||
|
||||
// Show specific WebLN error to user for debugging
|
||||
const errorMessage = weblnError instanceof Error ? weblnError.message : 'Unknown WebLN error';
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
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,15 +1,3 @@
|
||||
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()
|
||||
*
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
import { DMMessagingInterface } from '@/components/dm/DMMessagingInterface';
|
||||
import { RelaySelector } from '@/components/RelaySelector';
|
||||
|
||||
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>
|
||||
<RelaySelector />
|
||||
</div>
|
||||
|
||||
<DMMessagingInterface className="flex-1" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Messages;
|
||||
Reference in new issue
Block a user