mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-05 16:33:36 +00:00
wip - document DMs to the LLM
This commit is contained in:
1 parent
50ed58730c
commit
69b314c831
3 files changed
+524
-1
No files matched your search
@@ -38,9 +38,11 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
|||||||
- `useNWC`: Nostr Wallet Connect connection management
|
- `useNWC`: Nostr Wallet Connect connection management
|
||||||
- `useNWCContext`: Access NWC context provider
|
- `useNWCContext`: Access NWC context provider
|
||||||
- `useShakespeare`: AI chat completions with Shakespeare AI API
|
- `useShakespeare`: AI chat completions with Shakespeare AI API
|
||||||
|
- `useDMContext`: Direct messaging system (NIP-04 & NIP-17)
|
||||||
|
- `useConversationMessages`: Paginated messages for specific conversations
|
||||||
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
- `/src/pages/`: Page components used by React Router (Index, NotFound)
|
||||||
- `/src/lib/`: Utility functions and shared logic
|
- `/src/lib/`: Utility functions and shared logic
|
||||||
- `/src/contexts/`: React context providers (AppContext, NWCContext)
|
- `/src/contexts/`: React context providers (AppContext, NWCContext, DMContext)
|
||||||
- `/src/test/`: Testing utilities including TestApp component
|
- `/src/test/`: Testing utilities including TestApp component
|
||||||
- `/public/`: Static assets
|
- `/public/`: Static assets
|
||||||
- `App.tsx`: Main app component with provider setup
|
- `App.tsx`: Main app component with provider setup
|
||||||
@@ -109,6 +111,8 @@ The project includes a **`docs/`** directory containing specialized documentatio
|
|||||||
|
|
||||||
- **`docs/NOSTR_INFINITE_SCROLL.md`**: Read when building feed interfaces, implementing pagination for Nostr events, or creating social media-style infinite scroll experiences.
|
- **`docs/NOSTR_INFINITE_SCROLL.md`**: Read when building feed interfaces, implementing pagination for Nostr events, or creating social media-style infinite scroll experiences.
|
||||||
|
|
||||||
|
- **`docs/NOSTR_DIRECT_MESSAGES.md`**: Read when implementing direct messaging features, building chat interfaces, or working with encrypted peer-to-peer communication (NIP-04 and NIP-17).
|
||||||
|
|
||||||
## System Prompt Management
|
## System Prompt Management
|
||||||
|
|
||||||
The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
|
||||||
@@ -744,6 +748,74 @@ function EditProfilePage() {
|
|||||||
|
|
||||||
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
|
||||||
|
|
||||||
|
### Direct Messaging (NIP-04 & NIP-17)
|
||||||
|
|
||||||
|
The project includes a complete direct messaging system with real-time updates, encrypted storage, and support for both NIP-04 (legacy) and NIP-17 (modern private messaging) protocols.
|
||||||
|
|
||||||
|
**Quick Setup:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { DMProvider } from '@/contexts/DMContext';
|
||||||
|
import { PROTOCOL_MODE } from '@/lib/dmConstants';
|
||||||
|
|
||||||
|
// Wrap your app with DMProvider
|
||||||
|
<DMProvider config={{ protocolMode: PROTOCOL_MODE.NIP17_ONLY }}>
|
||||||
|
{children}
|
||||||
|
</DMProvider>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Send Messages:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useDMContext } from '@/contexts/DMContext';
|
||||||
|
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
||||||
|
|
||||||
|
function MyComponent() {
|
||||||
|
const { sendMessage } = useDMContext();
|
||||||
|
|
||||||
|
await sendMessage({
|
||||||
|
recipientPubkey: 'hex-pubkey',
|
||||||
|
content: 'Hello!',
|
||||||
|
protocol: MESSAGE_PROTOCOL.NIP17 // or NIP04
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Display Conversations:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
const { conversations, isLoading } = useDMContext();
|
||||||
|
|
||||||
|
// conversations = Array of conversation summaries with:
|
||||||
|
// - pubkey: The other participant
|
||||||
|
// - lastMessage: Most recent message
|
||||||
|
// - lastActivity: Unix timestamp
|
||||||
|
// - isKnown: User has sent messages
|
||||||
|
// - isRequest: Only received messages
|
||||||
|
```
|
||||||
|
|
||||||
|
**Display Messages:**
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { useConversationMessages } from '@/contexts/DMContext';
|
||||||
|
|
||||||
|
const { messages, hasMoreMessages, loadEarlierMessages } = useConversationMessages(pubkey);
|
||||||
|
|
||||||
|
// messages = Paginated array of messages (25/page)
|
||||||
|
// hasMoreMessages = true if earlier messages available
|
||||||
|
// loadEarlierMessages() = Load next 25 messages
|
||||||
|
```
|
||||||
|
|
||||||
|
**Features:**
|
||||||
|
- **Dual Protocol Support**: NIP-04 (legacy) and NIP-17 (private with gift wrapping)
|
||||||
|
- **Real-time Updates**: WebSocket subscriptions for live messages
|
||||||
|
- **Encrypted Storage**: IndexedDB with NIP-44 encryption
|
||||||
|
- **Optimistic UI**: Instant message display with background confirmation
|
||||||
|
- **File Attachments**: Full support with `attachments` parameter
|
||||||
|
- **Cache-First Loading**: Instant UI with background sync
|
||||||
|
|
||||||
|
For complete implementation details, file attachments, and advanced features, see **`docs/NOSTR_DIRECT_MESSAGES.md`**.
|
||||||
|
|
||||||
### Uploading Files on Nostr
|
### Uploading Files on Nostr
|
||||||
|
|
||||||
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
|
||||||
|
|||||||
@@ -0,0 +1,330 @@
|
|||||||
|
### 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. Wrap Your App with DMProvider
|
||||||
|
|
||||||
|
```tsx
|
||||||
|
import { DMProvider } from '@/contexts/DMContext';
|
||||||
|
import { PROTOCOL_MODE } from '@/lib/dmConstants';
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
return (
|
||||||
|
<DMProvider config={{ protocolMode: PROTOCOL_MODE.NIP17_ONLY }}>
|
||||||
|
{/* Your app components */}
|
||||||
|
</DMProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Protocol Modes:**
|
||||||
|
- `PROTOCOL_MODE.NIP04_ONLY` - Legacy encryption only
|
||||||
|
- `PROTOCOL_MODE.NIP17_ONLY` - Modern private messages (recommended)
|
||||||
|
- `PROTOCOL_MODE.BOTH` - Support both protocols
|
||||||
|
|
||||||
|
### 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 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
|
||||||
|
|
||||||
@@ -116,6 +116,21 @@ const createErrorLogger = (name: string) => {
|
|||||||
|
|
||||||
const nip17ErrorLogger = createErrorLogger('NIP-17');
|
const nip17ErrorLogger = createErrorLogger('NIP-17');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Direct Messaging context interface providing access to all DM functionality.
|
||||||
|
*
|
||||||
|
* @property messages - Raw message state (Map of pubkey -> participant data)
|
||||||
|
* @property isLoading - True during initial load phases
|
||||||
|
* @property loadingPhase - Current loading phase (CACHE, RELAYS, SUBSCRIPTIONS, READY, IDLE)
|
||||||
|
* @property isDoingInitialLoad - True only during cache/relay loading (not subscriptions)
|
||||||
|
* @property lastSync - Unix timestamps of last successful sync for each protocol
|
||||||
|
* @property subscriptions - Connection status for real-time message subscriptions
|
||||||
|
* @property conversations - Array of conversation summaries sorted by last activity
|
||||||
|
* @property sendMessage - Send an encrypted direct message (NIP-04 or NIP-17)
|
||||||
|
* @property protocolMode - Current protocol mode (NIP04_ONLY, NIP17_ONLY, or BOTH)
|
||||||
|
* @property scanProgress - Progress info for large message history scans
|
||||||
|
* @property clearCacheAndRefetch - Clear IndexedDB cache and reload all messages from relays
|
||||||
|
*/
|
||||||
interface DMContextType {
|
interface DMContextType {
|
||||||
messages: MessagesState;
|
messages: MessagesState;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
@@ -137,6 +152,41 @@ interface DMContextType {
|
|||||||
|
|
||||||
const DMContext = createContext<DMContextType | null>(null);
|
const DMContext = createContext<DMContextType | null>(null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hook to access the direct messaging system.
|
||||||
|
*
|
||||||
|
* Provides access to conversations, message sending, loading states, and cache management.
|
||||||
|
* Must be used within a DMProvider.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* import { useDMContext } from '@/contexts/DMContext';
|
||||||
|
* import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
||||||
|
*
|
||||||
|
* function MyComponent() {
|
||||||
|
* const { conversations, sendMessage, isLoading } = useDMContext();
|
||||||
|
*
|
||||||
|
* // Send a message
|
||||||
|
* await sendMessage({
|
||||||
|
* recipientPubkey: 'hex-pubkey',
|
||||||
|
* content: 'Hello!',
|
||||||
|
* protocol: MESSAGE_PROTOCOL.NIP17
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* // Display conversations
|
||||||
|
* return (
|
||||||
|
* <div>
|
||||||
|
* {isLoading ? 'Loading...' : conversations.map(c => (
|
||||||
|
* <div key={c.pubkey}>{c.lastMessage?.decryptedContent}</div>
|
||||||
|
* ))}
|
||||||
|
* </div>
|
||||||
|
* );
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @returns DMContextType - The direct messaging context
|
||||||
|
* @throws Error if used outside DMProvider
|
||||||
|
*/
|
||||||
export function useDMContext(): DMContextType {
|
export function useDMContext(): DMContextType {
|
||||||
const context = useContext(DMContext);
|
const context = useContext(DMContext);
|
||||||
if (!context) {
|
if (!context) {
|
||||||
@@ -147,6 +197,42 @@ export function useDMContext(): DMContextType {
|
|||||||
|
|
||||||
const MESSAGES_PER_PAGE = 25;
|
const MESSAGES_PER_PAGE = 25;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hook to access paginated messages for a specific conversation.
|
||||||
|
*
|
||||||
|
* Returns the most recent messages (default 25) with the ability to load earlier messages.
|
||||||
|
* Automatically resets to default page size when switching conversations.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* import { useConversationMessages } from '@/contexts/DMContext';
|
||||||
|
*
|
||||||
|
* function MessageThread({ recipientPubkey }: { recipientPubkey: string }) {
|
||||||
|
* const {
|
||||||
|
* messages,
|
||||||
|
* hasMoreMessages,
|
||||||
|
* loadEarlierMessages,
|
||||||
|
* totalCount
|
||||||
|
* } = useConversationMessages(recipientPubkey);
|
||||||
|
*
|
||||||
|
* return (
|
||||||
|
* <div>
|
||||||
|
* {hasMoreMessages && (
|
||||||
|
* <button onClick={loadEarlierMessages}>
|
||||||
|
* Load Earlier ({totalCount - messages.length} more)
|
||||||
|
* </button>
|
||||||
|
* )}
|
||||||
|
* {messages.map(msg => (
|
||||||
|
* <div key={msg.id}>{msg.decryptedContent}</div>
|
||||||
|
* ))}
|
||||||
|
* </div>
|
||||||
|
* );
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @param conversationId - The pubkey of the conversation participant
|
||||||
|
* @returns Paginated message data with loading function
|
||||||
|
*/
|
||||||
export function useConversationMessages(conversationId: string) {
|
export function useConversationMessages(conversationId: string) {
|
||||||
const { messages: allMessages } = useDMContext();
|
const { messages: allMessages } = useDMContext();
|
||||||
const [visibleCount, setVisibleCount] = useState(MESSAGES_PER_PAGE);
|
const [visibleCount, setVisibleCount] = useState(MESSAGES_PER_PAGE);
|
||||||
@@ -208,6 +294,41 @@ interface DMProviderProps {
|
|||||||
// Message Sending Types and Helpers (Internal)
|
// Message Sending Types and Helpers (Internal)
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* File attachment for direct messages (NIP-92 compatible).
|
||||||
|
*
|
||||||
|
* All fields are required. Use with `useUploadFile` hook to upload files
|
||||||
|
* and generate the proper tags format.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* import { useUploadFile } from '@/hooks/useUploadFile';
|
||||||
|
* import type { FileAttachment } from '@/contexts/DMContext';
|
||||||
|
*
|
||||||
|
* const { mutateAsync: uploadFile } = useUploadFile();
|
||||||
|
*
|
||||||
|
* const tags = await uploadFile(file);
|
||||||
|
* const attachment: FileAttachment = {
|
||||||
|
* url: tags[0][1],
|
||||||
|
* mimeType: file.type,
|
||||||
|
* size: file.size,
|
||||||
|
* name: file.name,
|
||||||
|
* tags: tags
|
||||||
|
* };
|
||||||
|
*
|
||||||
|
* await sendMessage({
|
||||||
|
* recipientPubkey: 'hex-pubkey',
|
||||||
|
* content: 'Check out this file!',
|
||||||
|
* attachments: [attachment]
|
||||||
|
* });
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @property url - Blossom server URL where file is hosted
|
||||||
|
* @property mimeType - MIME type of the file (e.g., 'image/png')
|
||||||
|
* @property size - File size in bytes
|
||||||
|
* @property name - Original filename
|
||||||
|
* @property tags - NIP-94 file metadata tags (includes hashes)
|
||||||
|
*/
|
||||||
export interface FileAttachment {
|
export interface FileAttachment {
|
||||||
url: string;
|
url: string;
|
||||||
mimeType: string;
|
mimeType: string;
|
||||||
|
|||||||
Reference in new issue
Block a user