mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-06 00:37:23 +00:00
Split DM context up into multiple files
This commit is contained in:
11 files changed
+285
-222
No files matched your search
@@ -9,7 +9,7 @@ This project includes a complete direct messaging system supporting both NIP-04
|
|||||||
The `DMProvider` is already added to your app, but **disabled by default**. To enable messaging, pass `enabled: true` in the config:
|
The `DMProvider` is already added to your app, but **disabled by default**. To enable messaging, pass `enabled: true` in the config:
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
import { DMProvider } from '@/contexts/DMContext';
|
import { DMProvider } from '@/components/DMProvider';
|
||||||
import { PROTOCOL_MODE } from '@/lib/dmConstants';
|
import { PROTOCOL_MODE } from '@/lib/dmConstants';
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
@@ -36,7 +36,7 @@ function App() {
|
|||||||
### 2. Send Messages
|
### 2. Send Messages
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
import { useDMContext } from '@/contexts/DMContext';
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
||||||
|
|
||||||
function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
|
function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
|
||||||
@@ -68,7 +68,7 @@ function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
|
|||||||
### 3. Display Conversations
|
### 3. Display Conversations
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
import { useDMContext } from '@/contexts/DMContext';
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
import { useAuthor } from '@/hooks/useAuthor';
|
import { useAuthor } from '@/hooks/useAuthor';
|
||||||
import { genUserName } from '@/lib/genUserName';
|
import { genUserName } from '@/lib/genUserName';
|
||||||
|
|
||||||
@@ -122,7 +122,7 @@ function ConversationItem({ conversation, onClick }: {
|
|||||||
### 4. Display Messages in a Conversation
|
### 4. Display Messages in a Conversation
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
import { useConversationMessages } from '@/contexts/DMContext';
|
import { useConversationMessages } from '@/hooks/useConversationMessages';
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
|
|
||||||
function MessageThread({ conversationPubkey }: { conversationPubkey: string }) {
|
function MessageThread({ conversationPubkey }: { conversationPubkey: string }) {
|
||||||
@@ -201,9 +201,10 @@ It requires no props and works automatically when wrapped in `DMProvider`.
|
|||||||
## Sending Files with Messages
|
## Sending Files with Messages
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
import { useDMContext, type FileAttachment } from '@/contexts/DMContext';
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
import { useUploadFile } from '@/hooks/useUploadFile';
|
import { useUploadFile } from '@/hooks/useUploadFile';
|
||||||
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
||||||
|
import type { FileAttachment } from '@/contexts/DMContext';
|
||||||
|
|
||||||
function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
|
function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
|
||||||
const { sendMessage } = useDMContext();
|
const { sendMessage } = useDMContext();
|
||||||
@@ -321,7 +322,7 @@ if (scanProgress.nip17) {
|
|||||||
### Clear Cache and Refresh
|
### Clear Cache and Refresh
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
import { useDMContext } from '@/contexts/DMContext';
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
|
|
||||||
function SettingsButton() {
|
function SettingsButton() {
|
||||||
const { clearCacheAndRefetch } = useDMContext();
|
const { clearCacheAndRefetch } = useDMContext();
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ export default tseslint.config(
|
|||||||
globals: globals.browser,
|
globals: globals.browser,
|
||||||
},
|
},
|
||||||
linterOptions: {
|
linterOptions: {
|
||||||
noInlineConfig: true, // Prevents all eslint-disable comments
|
|
||||||
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
|
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
|
||||||
},
|
},
|
||||||
plugins: {
|
plugins: {
|
||||||
|
|||||||
+1
-1
@@ -11,7 +11,7 @@ import { TooltipProvider } from "@/components/ui/tooltip";
|
|||||||
import { NostrLoginProvider } from '@nostrify/react/login';
|
import { NostrLoginProvider } from '@nostrify/react/login';
|
||||||
import { AppProvider } from '@/components/AppProvider';
|
import { AppProvider } from '@/components/AppProvider';
|
||||||
import { NWCProvider } from '@/contexts/NWCContext';
|
import { NWCProvider } from '@/contexts/NWCContext';
|
||||||
import { DMProvider, type DMConfig } from '@/contexts/DMContext';
|
import { DMProvider, type DMConfig } from '@/components/DMProvider';
|
||||||
import { AppConfig } from '@/contexts/AppContext';
|
import { AppConfig } from '@/contexts/AppContext';
|
||||||
import { PROTOCOL_MODE } from '@/lib/dmConstants';
|
import { PROTOCOL_MODE } from '@/lib/dmConstants';
|
||||||
import AppRouter from './AppRouter';
|
import AppRouter from './AppRouter';
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { createContext, useContext, useEffect, useState, ReactNode, useCallback, useMemo, useRef } from 'react';
|
import { useEffect, useState, ReactNode, useCallback, useMemo, useRef } from 'react';
|
||||||
import { useMutation } from '@tanstack/react-query';
|
import { useMutation } from '@tanstack/react-query';
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
import { useNostr } from '@nostrify/react';
|
import { useNostr } from '@nostrify/react';
|
||||||
@@ -11,6 +11,7 @@ import { NSecSigner, type NostrEvent } from '@nostrify/nostrify';
|
|||||||
import { generateSecretKey } from 'nostr-tools';
|
import { generateSecretKey } from 'nostr-tools';
|
||||||
import type { MessageProtocol } from '@/lib/dmConstants';
|
import type { MessageProtocol } from '@/lib/dmConstants';
|
||||||
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
||||||
|
import { DMContext, DMContextType, FileAttachment } from '@/contexts/DMContext';
|
||||||
|
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
// DM Types and Constants
|
// DM Types and Constants
|
||||||
@@ -117,172 +118,6 @@ 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 {
|
|
||||||
messages: MessagesState;
|
|
||||||
isLoading: boolean;
|
|
||||||
loadingPhase: LoadingPhase;
|
|
||||||
isDoingInitialLoad: boolean;
|
|
||||||
lastSync: LastSyncData;
|
|
||||||
subscriptions: SubscriptionStatus;
|
|
||||||
conversations: ConversationSummary[];
|
|
||||||
sendMessage: (params: {
|
|
||||||
recipientPubkey: string;
|
|
||||||
content: string;
|
|
||||||
protocol?: MessageProtocol;
|
|
||||||
attachments?: FileAttachment[];
|
|
||||||
}) => Promise<void>;
|
|
||||||
protocolMode: ProtocolMode;
|
|
||||||
scanProgress: ScanProgressState;
|
|
||||||
clearCacheAndRefetch: () => Promise<void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
*/
|
|
||||||
// eslint-disable-next-line react-refresh/only-export-components
|
|
||||||
export function useDMContext(): DMContextType {
|
|
||||||
const context = useContext(DMContext);
|
|
||||||
if (!context) {
|
|
||||||
throw new Error('useDMContext must be used within DMProvider');
|
|
||||||
}
|
|
||||||
return context;
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
*/
|
|
||||||
// eslint-disable-next-line react-refresh/only-export-components
|
|
||||||
export function useConversationMessages(conversationId: string) {
|
|
||||||
const { messages: allMessages } = useDMContext();
|
|
||||||
const [visibleCount, setVisibleCount] = useState(MESSAGES_PER_PAGE);
|
|
||||||
|
|
||||||
const result = useMemo(() => {
|
|
||||||
const conversationData = allMessages.get(conversationId);
|
|
||||||
|
|
||||||
if (!conversationData) {
|
|
||||||
return {
|
|
||||||
messages: [],
|
|
||||||
hasMoreMessages: false,
|
|
||||||
totalCount: 0,
|
|
||||||
lastMessage: null,
|
|
||||||
lastActivity: 0,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const totalMessages = conversationData.messages.length;
|
|
||||||
const hasMore = totalMessages > visibleCount;
|
|
||||||
|
|
||||||
// Return the most recent N messages (slice from the end)
|
|
||||||
const visibleMessages = conversationData.messages.slice(-visibleCount);
|
|
||||||
|
|
||||||
return {
|
|
||||||
messages: visibleMessages,
|
|
||||||
hasMoreMessages: hasMore,
|
|
||||||
totalCount: totalMessages,
|
|
||||||
lastMessage: conversationData.lastMessage,
|
|
||||||
lastActivity: conversationData.lastActivity,
|
|
||||||
};
|
|
||||||
}, [allMessages, conversationId, visibleCount]);
|
|
||||||
|
|
||||||
const loadEarlierMessages = useCallback(() => {
|
|
||||||
setVisibleCount(prev => prev + MESSAGES_PER_PAGE);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
// Reset visible count when conversation changes
|
|
||||||
useEffect(() => {
|
|
||||||
setVisibleCount(MESSAGES_PER_PAGE);
|
|
||||||
}, [conversationId]);
|
|
||||||
|
|
||||||
return {
|
|
||||||
...result,
|
|
||||||
loadEarlierMessages,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DMConfig {
|
export interface DMConfig {
|
||||||
enabled?: boolean;
|
enabled?: boolean;
|
||||||
protocolMode?: ProtocolMode;
|
protocolMode?: ProtocolMode;
|
||||||
@@ -297,49 +132,6 @@ 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 {
|
|
||||||
url: string;
|
|
||||||
mimeType: string;
|
|
||||||
size: number;
|
|
||||||
name: string;
|
|
||||||
tags: string[][];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Prepare message content with file URLs appended
|
* Prepare message content with file URLs appended
|
||||||
*/
|
*/
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useState, useRef, useEffect, useCallback, memo } from 'react';
|
import { useState, useRef, useEffect, useCallback, memo } from 'react';
|
||||||
import { useConversationMessages, useDMContext } from '@/contexts/DMContext';
|
import { useConversationMessages } from '@/hooks/useConversationMessages';
|
||||||
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
import { useAuthor } from '@/hooks/useAuthor';
|
import { useAuthor } from '@/hooks/useAuthor';
|
||||||
import { genUserName } from '@/lib/genUserName';
|
import { genUserName } from '@/lib/genUserName';
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useMemo, useState, memo } from 'react';
|
import { useMemo, useState, memo } from 'react';
|
||||||
import { AlertTriangle, Info, Loader2 } from 'lucide-react';
|
import { AlertTriangle, Info, Loader2 } from 'lucide-react';
|
||||||
import { useDMContext } from '@/contexts/DMContext';
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
import { useAuthor } from '@/hooks/useAuthor';
|
import { useAuthor } from '@/hooks/useAuthor';
|
||||||
import { genUserName } from '@/lib/genUserName';
|
import { genUserName } from '@/lib/genUserName';
|
||||||
import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils';
|
import { formatConversationTime, formatFullDateTime } from '@/lib/dmUtils';
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { useState, useCallback } from 'react';
|
|||||||
import { DMConversationList } from '@/components/dm/DMConversationList';
|
import { DMConversationList } from '@/components/dm/DMConversationList';
|
||||||
import { DMChatArea } from '@/components/dm/DMChatArea';
|
import { DMChatArea } from '@/components/dm/DMChatArea';
|
||||||
import { DMStatusInfo } from '@/components/dm/DMStatusInfo';
|
import { DMStatusInfo } from '@/components/dm/DMStatusInfo';
|
||||||
import { useDMContext } from '@/contexts/DMContext';
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import {
|
import {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { RefreshCw, Database, Wifi, CheckCircle2, Loader2 } from 'lucide-react';
|
import { RefreshCw, Database, Wifi, CheckCircle2, Loader2 } from 'lucide-react';
|
||||||
import { useDMContext } from '@/contexts/DMContext';
|
import { useDMContext } from '@/hooks/useDMContext';
|
||||||
import { LOADING_PHASES } from '@/lib/dmConstants';
|
import { LOADING_PHASES } from '@/lib/dmConstants';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Card, CardContent } from '@/components/ui/card';
|
import { Card, CardContent } from '@/components/ui/card';
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import { createContext } from 'react';
|
||||||
|
import { type LoadingPhase, type ProtocolMode } from '@/lib/dmConstants';
|
||||||
|
import { type NostrEvent } from '@nostrify/nostrify';
|
||||||
|
import type { MessageProtocol } from '@/lib/dmConstants';
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// DM Types and Constants
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
interface ParticipantData {
|
||||||
|
messages: DecryptedMessage[];
|
||||||
|
lastActivity: number;
|
||||||
|
lastMessage: DecryptedMessage | null;
|
||||||
|
hasNIP4: boolean;
|
||||||
|
hasNIP17: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
type MessagesState = Map<string, ParticipantData>;
|
||||||
|
|
||||||
|
interface LastSyncData {
|
||||||
|
nip4: number | null;
|
||||||
|
nip17: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SubscriptionStatus {
|
||||||
|
isNIP4Connected: boolean;
|
||||||
|
isNIP17Connected: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ScanProgress {
|
||||||
|
current: number;
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ScanProgressState {
|
||||||
|
nip4: ScanProgress | null;
|
||||||
|
nip17: ScanProgress | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ConversationSummary {
|
||||||
|
id: string;
|
||||||
|
pubkey: string;
|
||||||
|
lastMessage: DecryptedMessage | null;
|
||||||
|
lastActivity: number;
|
||||||
|
hasNIP4Messages: boolean;
|
||||||
|
hasNIP17Messages: boolean;
|
||||||
|
isKnown: boolean;
|
||||||
|
isRequest: boolean;
|
||||||
|
lastMessageFromUser: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DecryptedMessage extends NostrEvent {
|
||||||
|
decryptedContent?: string;
|
||||||
|
error?: string;
|
||||||
|
isSending?: boolean;
|
||||||
|
clientFirstSeen?: number;
|
||||||
|
decryptedEvent?: NostrEvent; // For NIP-17: the inner kind 14/15 event
|
||||||
|
originalGiftWrapId?: string; // Store gift wrap ID for NIP-17 deduplication
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* File attachment for direct messages (NIP-92 compatible).
|
||||||
|
*
|
||||||
|
* All fields are required. Use with `useUploadFile` hook to upload files
|
||||||
|
* and generate the proper tags format.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* import { useUploadFile } from '@/hooks/useUploadFile';
|
||||||
|
* import type { FileAttachment } from '@/contexts/DMContext';
|
||||||
|
*
|
||||||
|
* const { mutateAsync: uploadFile } = useUploadFile();
|
||||||
|
*
|
||||||
|
* const tags = await uploadFile(file);
|
||||||
|
* const attachment: FileAttachment = {
|
||||||
|
* url: tags[0][1],
|
||||||
|
* mimeType: file.type,
|
||||||
|
* size: file.size,
|
||||||
|
* name: file.name,
|
||||||
|
* tags: tags
|
||||||
|
* };
|
||||||
|
*
|
||||||
|
* await sendMessage({
|
||||||
|
* recipientPubkey: 'hex-pubkey',
|
||||||
|
* content: 'Check out this file!',
|
||||||
|
* attachments: [attachment]
|
||||||
|
* });
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @property url - Blossom server URL where file is hosted
|
||||||
|
* @property mimeType - MIME type of the file (e.g., 'image/png')
|
||||||
|
* @property size - File size in bytes
|
||||||
|
* @property name - Original filename
|
||||||
|
* @property tags - NIP-94 file metadata tags (includes hashes)
|
||||||
|
*/
|
||||||
|
export interface FileAttachment {
|
||||||
|
url: string;
|
||||||
|
mimeType: string;
|
||||||
|
size: number;
|
||||||
|
name: string;
|
||||||
|
tags: string[][];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Direct Messaging context interface providing access to all DM functionality.
|
||||||
|
*
|
||||||
|
* @property messages - Raw message state (Map of pubkey -> participant data)
|
||||||
|
* @property isLoading - True during initial load phases
|
||||||
|
* @property loadingPhase - Current loading phase (CACHE, RELAYS, SUBSCRIPTIONS, READY, IDLE)
|
||||||
|
* @property isDoingInitialLoad - True only during cache/relay loading (not subscriptions)
|
||||||
|
* @property lastSync - Unix timestamps of last successful sync for each protocol
|
||||||
|
* @property subscriptions - Connection status for real-time message subscriptions
|
||||||
|
* @property conversations - Array of conversation summaries sorted by last activity
|
||||||
|
* @property sendMessage - Send an encrypted direct message (NIP-04 or NIP-17)
|
||||||
|
* @property protocolMode - Current protocol mode (NIP04_ONLY, NIP17_ONLY, or BOTH)
|
||||||
|
* @property scanProgress - Progress info for large message history scans
|
||||||
|
* @property clearCacheAndRefetch - Clear IndexedDB cache and reload all messages from relays
|
||||||
|
*/
|
||||||
|
export interface DMContextType {
|
||||||
|
messages: MessagesState;
|
||||||
|
isLoading: boolean;
|
||||||
|
loadingPhase: LoadingPhase;
|
||||||
|
isDoingInitialLoad: boolean;
|
||||||
|
lastSync: LastSyncData;
|
||||||
|
subscriptions: SubscriptionStatus;
|
||||||
|
conversations: ConversationSummary[];
|
||||||
|
sendMessage: (params: {
|
||||||
|
recipientPubkey: string;
|
||||||
|
content: string;
|
||||||
|
protocol?: MessageProtocol;
|
||||||
|
attachments?: FileAttachment[];
|
||||||
|
}) => Promise<void>;
|
||||||
|
protocolMode: ProtocolMode;
|
||||||
|
scanProgress: ScanProgressState;
|
||||||
|
clearCacheAndRefetch: () => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DMContext = createContext<DMContextType | null>(null);
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
|
import { useDMContext } from "@/hooks/useDMContext";
|
||||||
|
|
||||||
|
const MESSAGES_PER_PAGE = 25;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hook to access paginated messages for a specific conversation.
|
||||||
|
*
|
||||||
|
* Returns the most recent messages (default 25) with the ability to load earlier messages.
|
||||||
|
* Automatically resets to default page size when switching conversations.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* import { useConversationMessages } from '@/contexts/DMContext';
|
||||||
|
*
|
||||||
|
* function MessageThread({ recipientPubkey }: { recipientPubkey: string }) {
|
||||||
|
* const {
|
||||||
|
* messages,
|
||||||
|
* hasMoreMessages,
|
||||||
|
* loadEarlierMessages,
|
||||||
|
* totalCount
|
||||||
|
* } = useConversationMessages(recipientPubkey);
|
||||||
|
*
|
||||||
|
* return (
|
||||||
|
* <div>
|
||||||
|
* {hasMoreMessages && (
|
||||||
|
* <button onClick={loadEarlierMessages}>
|
||||||
|
* Load Earlier ({totalCount - messages.length} more)
|
||||||
|
* </button>
|
||||||
|
* )}
|
||||||
|
* {messages.map(msg => (
|
||||||
|
* <div key={msg.id}>{msg.decryptedContent}</div>
|
||||||
|
* ))}
|
||||||
|
* </div>
|
||||||
|
* );
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @param conversationId - The pubkey of the conversation participant
|
||||||
|
* @returns Paginated message data with loading function
|
||||||
|
*/
|
||||||
|
export function useConversationMessages(conversationId: string) {
|
||||||
|
const { messages: allMessages } = useDMContext();
|
||||||
|
const [visibleCount, setVisibleCount] = useState(MESSAGES_PER_PAGE);
|
||||||
|
|
||||||
|
const result = useMemo(() => {
|
||||||
|
const conversationData = allMessages.get(conversationId);
|
||||||
|
|
||||||
|
if (!conversationData) {
|
||||||
|
return {
|
||||||
|
messages: [],
|
||||||
|
hasMoreMessages: false,
|
||||||
|
totalCount: 0,
|
||||||
|
lastMessage: null,
|
||||||
|
lastActivity: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalMessages = conversationData.messages.length;
|
||||||
|
const hasMore = totalMessages > visibleCount;
|
||||||
|
|
||||||
|
// Return the most recent N messages (slice from the end)
|
||||||
|
const visibleMessages = conversationData.messages.slice(-visibleCount);
|
||||||
|
|
||||||
|
return {
|
||||||
|
messages: visibleMessages,
|
||||||
|
hasMoreMessages: hasMore,
|
||||||
|
totalCount: totalMessages,
|
||||||
|
lastMessage: conversationData.lastMessage,
|
||||||
|
lastActivity: conversationData.lastActivity,
|
||||||
|
};
|
||||||
|
}, [allMessages, conversationId, visibleCount]);
|
||||||
|
|
||||||
|
const loadEarlierMessages = useCallback(() => {
|
||||||
|
setVisibleCount(prev => prev + MESSAGES_PER_PAGE);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Reset visible count when conversation changes
|
||||||
|
useEffect(() => {
|
||||||
|
setVisibleCount(MESSAGES_PER_PAGE);
|
||||||
|
}, [conversationId]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...result,
|
||||||
|
loadEarlierMessages,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { useContext } from "react";
|
||||||
|
import { DMContext, DMContextType } from "@/contexts/DMContext";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hook to access the direct messaging system.
|
||||||
|
*
|
||||||
|
* Provides access to conversations, message sending, loading states, and cache management.
|
||||||
|
* Must be used within a DMProvider.
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* import { useDMContext } from '@/hooks/useDMContext';
|
||||||
|
* import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
|
||||||
|
*
|
||||||
|
* function MyComponent() {
|
||||||
|
* const { conversations, sendMessage, isLoading } = useDMContext();
|
||||||
|
*
|
||||||
|
* // Send a message
|
||||||
|
* await sendMessage({
|
||||||
|
* recipientPubkey: 'hex-pubkey',
|
||||||
|
* content: 'Hello!',
|
||||||
|
* protocol: MESSAGE_PROTOCOL.NIP17
|
||||||
|
* });
|
||||||
|
*
|
||||||
|
* // Display conversations
|
||||||
|
* return (
|
||||||
|
* <div>
|
||||||
|
* {isLoading ? 'Loading...' : conversations.map(c => (
|
||||||
|
* <div key={c.pubkey}>{c.lastMessage?.decryptedContent}</div>
|
||||||
|
* ))}
|
||||||
|
* </div>
|
||||||
|
* );
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @returns DMContextType - The direct messaging context
|
||||||
|
* @throws Error if used outside DMProvider
|
||||||
|
*/
|
||||||
|
export function useDMContext(): DMContextType {
|
||||||
|
const context = useContext(DMContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useDMContext must be used within DMProvider');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user