Move DM conversations to secondary panel with improvements

- Open DM conversations in secondary panel (dual-pane) or overlay (mobile)
- Add relay selection toggles in message composer
- Add background DM subscriptions for real-time updates
- Add close buttons on conversation items and message view header
- Replace conversation view instead of stacking when switching

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
woikos
2025-12-31 17:04:30 +01:00
parent ad5f9cccf9
commit 9820a1c6c0
10 changed files with 278 additions and 65 deletions

View File

@@ -3,7 +3,7 @@ import { formatTimestamp } from '@/lib/timestamp'
import { cn } from '@/lib/utils'
import client from '@/services/client.service'
import { TConversation, TProfile } from '@/types'
import { Lock, Users } from 'lucide-react'
import { Lock, Users, X } from 'lucide-react'
import { useEffect, useState } from 'react'
interface ConversationItemProps {
@@ -11,13 +11,15 @@ interface ConversationItemProps {
isActive: boolean
isFollowing: boolean
onClick: () => void
onClose?: () => void
}
export default function ConversationItem({
conversation,
isActive,
isFollowing,
onClick
onClick,
onClose
}: ConversationItemProps) {
const [profile, setProfile] = useState<TProfile | null>(null)
@@ -58,7 +60,21 @@ export default function ConversationItem({
</span>
)}
</div>
<span className="text-xs text-muted-foreground flex-shrink-0">{formattedTime}</span>
<div className="flex items-center gap-1 flex-shrink-0">
<span className="text-xs text-muted-foreground">{formattedTime}</span>
{isActive && onClose && (
<button
onClick={(e) => {
e.stopPropagation()
onClose()
}}
className="p-0.5 rounded hover:bg-muted-foreground/20 transition-colors"
title="Close conversation"
>
<X className="size-4 text-muted-foreground" />
</button>
)}
</div>
</div>
<div className="flex items-center gap-1.5 mt-0.5">

View File

@@ -1,3 +1,5 @@
import { toDMConversation } from '@/lib/link'
import { useSecondaryPage } from '@/PageManager'
import { useDM } from '@/providers/DMProvider'
import { useFollowList } from '@/providers/FollowListProvider'
import { useMuteList } from '@/providers/MuteListProvider'
@@ -17,6 +19,7 @@ import ConversationItem from './ConversationItem'
export default function ConversationList() {
const { t } = useTranslation()
const { push, pop } = useSecondaryPage()
const {
conversations,
currentConversation,
@@ -128,7 +131,17 @@ export default function ConversationList() {
conversation={conversation}
isActive={currentConversation === conversation.partnerPubkey}
isFollowing={followingSet.has(conversation.partnerPubkey)}
onClick={() => selectConversation(conversation.partnerPubkey)}
onClick={() => {
// If already viewing a different conversation, pop first to replace
if (currentConversation && currentConversation !== conversation.partnerPubkey) {
pop()
}
push(toDMConversation(conversation.partnerPubkey))
}}
onClose={() => {
selectConversation(null)
pop()
}}
/>
))}
{/* Sentinel element for infinite scroll */}

View File

@@ -1,27 +1,14 @@
import { useDM } from '@/providers/DMProvider'
import { Loader2, RefreshCw } from 'lucide-react'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import ConversationList from './ConversationList'
import MessageView from './MessageView'
import { Button } from '../ui/button'
export default function InboxContent() {
const { t } = useTranslation()
const { isLoading, error, refreshConversations, currentConversation, selectConversation } =
useDM()
const [isMobileView, setIsMobileView] = useState(false)
const { isLoading, error, refreshConversations } = useDM()
useEffect(() => {
const checkMobile = () => {
setIsMobileView(window.innerWidth < 768)
}
checkMobile()
window.addEventListener('resize', checkMobile)
return () => window.removeEventListener('resize', checkMobile)
}, [])
if (isLoading && !currentConversation) {
if (isLoading) {
return (
<div className="flex items-center justify-center h-64">
<div className="flex flex-col items-center gap-2 text-muted-foreground">
@@ -44,37 +31,10 @@ export default function InboxContent() {
)
}
// Mobile view: show either list or conversation
if (isMobileView) {
if (currentConversation) {
return (
<div className="h-[calc(100vh-8rem)]">
<MessageView onBack={() => selectConversation(null)} />
</div>
)
}
return (
<div className="h-[calc(100vh-8rem)]">
<ConversationList />
</div>
)
}
// Desktop view: split pane
// Conversations list - clicking opens in secondary panel (or overlay on mobile)
return (
<div className="flex h-[calc(100vh-8rem)]">
<div className="w-80 border-r flex-shrink-0 overflow-hidden">
<ConversationList />
</div>
<div className="flex-1 overflow-hidden">
{currentConversation ? (
<MessageView />
) : (
<div className="flex items-center justify-center h-full text-muted-foreground">
<p>{t('Select a conversation to view messages')}</p>
</div>
)}
</div>
<div className="h-[calc(100vh-8rem)]">
<ConversationList />
</div>
)
}

View File

@@ -1,6 +1,8 @@
import { cn } from '@/lib/utils'
import { useDM } from '@/providers/DMProvider'
import { AlertCircle, Loader2, Send } from 'lucide-react'
import { useRef, useState } from 'react'
import { useNostr } from '@/providers/NostrProvider'
import { AlertCircle, ChevronDown, ChevronUp, Loader2, Send } from 'lucide-react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Button } from '../ui/button'
import { Textarea } from '../ui/textarea'
@@ -8,18 +10,47 @@ import { Textarea } from '../ui/textarea'
export default function MessageComposer() {
const { t } = useTranslation()
const { sendMessage, currentConversation } = useDM()
const { relayList } = useNostr()
const [message, setMessage] = useState('')
const [isSending, setIsSending] = useState(false)
const [error, setError] = useState<string | null>(null)
const [showRelays, setShowRelays] = useState(false)
const [selectedRelays, setSelectedRelays] = useState<Set<string>>(new Set())
const textareaRef = useRef<HTMLTextAreaElement>(null)
// Get user's write relays
const writeRelays = useMemo(() => relayList?.write || [], [relayList])
// Initialize selected relays when write relays change
useEffect(() => {
if (writeRelays.length > 0 && selectedRelays.size === 0) {
setSelectedRelays(new Set(writeRelays))
}
}, [writeRelays])
const toggleRelay = (url: string) => {
setSelectedRelays((prev) => {
const next = new Set(prev)
if (next.has(url)) {
// Don't allow deselecting all relays
if (next.size > 1) {
next.delete(url)
}
} else {
next.add(url)
}
return next
})
}
const handleSend = async () => {
if (!message.trim() || !currentConversation || isSending) return
setIsSending(true)
setError(null)
try {
await sendMessage(message.trim())
const relaysToUse = Array.from(selectedRelays)
await sendMessage(message.trim(), relaysToUse.length > 0 ? relaysToUse : undefined)
setMessage('')
// Return focus to input after sending
textareaRef.current?.focus()
@@ -38,6 +69,11 @@ export default function MessageComposer() {
}
}
// Format relay URL for display
const formatRelayUrl = (url: string) => {
return url.replace(/^wss?:\/\//, '').replace(/\/$/, '')
}
return (
<div className="p-3 space-y-2">
{error && (
@@ -46,6 +82,41 @@ export default function MessageComposer() {
<span>{error}</span>
</div>
)}
{/* Relay selector */}
{writeRelays.length > 0 && (
<div className="space-y-1">
<button
onClick={() => setShowRelays(!showRelays)}
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
{showRelays ? <ChevronUp className="size-3" /> : <ChevronDown className="size-3" />}
<span>
{t('Relays')} ({selectedRelays.size}/{writeRelays.length})
</span>
</button>
{showRelays && (
<div className="flex flex-wrap gap-1">
{writeRelays.map((url) => (
<button
key={url}
onClick={() => toggleRelay(url)}
className={cn(
'text-xs px-2 py-0.5 rounded-full border transition-colors',
selectedRelays.has(url)
? 'bg-primary text-primary-foreground border-primary'
: 'bg-muted text-muted-foreground border-muted hover:border-primary/50'
)}
title={url}
>
{formatRelayUrl(url)}
</button>
))}
</div>
)}
</div>
)}
<div className="flex items-end gap-2">
<Textarea
ref={textareaRef}

View File

@@ -6,7 +6,7 @@ import { useNostr } from '@/providers/NostrProvider'
import client from '@/services/client.service'
import indexedDb from '@/services/indexed-db.service'
import { TDirectMessage, TProfile } from '@/types'
import { ArrowLeft, ChevronDown, ChevronUp, Loader2, MoreVertical, RefreshCw, Settings, Trash2, Undo2, Users, X } from 'lucide-react'
import { ChevronDown, ChevronUp, Loader2, MoreVertical, RefreshCw, Settings, Trash2, Undo2, Users, X } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Button } from '../ui/button'
@@ -232,11 +232,6 @@ export default function MessageView({ onBack }: MessageViewProps) {
) : (
// Normal header
<>
{onBack && (
<Button variant="ghost" size="icon" onClick={onBack} className="size-8">
<ArrowLeft className="size-4" />
</Button>
)}
<UserAvatar userId={currentConversation} className="size-8" />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
@@ -291,6 +286,17 @@ export default function MessageView({ onBack }: MessageViewProps) {
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{onBack && (
<Button
variant="ghost"
size="icon"
className="size-8"
title={t('Close conversation')}
onClick={onBack}
>
<X className="size-4" />
</Button>
)}
</>
)}
</div>

View File

@@ -92,3 +92,7 @@ export const toUserAggregationDetail = (feedId: string, pubkey: string) => {
}
export const toLogin = () => '/login'
export const toLogout = () => '/logout'
export const toDMConversation = (pubkey: string) => {
const npub = pubkey.startsWith('npub') ? pubkey : nip19.npubEncode(pubkey)
return `/dm/${npub}`
}

View File

@@ -0,0 +1,66 @@
import MessageView from '@/components/Inbox/MessageView'
import SecondaryPageLayout from '@/layouts/SecondaryPageLayout'
import { useSecondaryPage } from '@/PageManager'
import { useDM } from '@/providers/DMProvider'
import { TPageRef } from '@/types'
import { nip19 } from 'nostr-tools'
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
interface DMConversationPageProps {
pubkey?: string
index?: number
}
const DMConversationPage = forwardRef<TPageRef, DMConversationPageProps>(({ pubkey, index }, ref) => {
const { t } = useTranslation()
const layoutRef = useRef<TPageRef>(null)
const { selectConversation, currentConversation } = useDM()
const { pop } = useSecondaryPage()
// Decode npub to hex if needed
const hexPubkey = useMemo(() => {
if (!pubkey) return null
if (pubkey.startsWith('npub')) {
try {
const decoded = nip19.decode(pubkey)
return decoded.type === 'npub' ? decoded.data : null
} catch {
return null
}
}
return pubkey
}, [pubkey])
useImperativeHandle(ref, () => layoutRef.current as TPageRef)
// Select the conversation when this page mounts
useEffect(() => {
if (hexPubkey && hexPubkey !== currentConversation) {
selectConversation(hexPubkey)
}
}, [hexPubkey, selectConversation, currentConversation])
// Clear conversation when page unmounts
useEffect(() => {
return () => {
selectConversation(null)
}
}, [])
const handleBack = () => {
selectConversation(null)
pop()
}
return (
<SecondaryPageLayout ref={layoutRef} index={index} title={t('Conversation')}>
<div className="h-full">
<MessageView onBack={handleBack} />
</div>
</SecondaryPageLayout>
)
})
DMConversationPage.displayName = 'DMConversationPage'
export default DMConversationPage

View File

@@ -24,7 +24,7 @@ type TDMContext = {
error: string | null
selectConversation: (partnerPubkey: string | null) => void
startConversation: (partnerPubkey: string) => void
sendMessage: (content: string) => Promise<void>
sendMessage: (content: string, customRelayUrls?: string[]) => Promise<void>
refreshConversations: () => Promise<void>
reloadConversation: () => void
loadMoreConversations: () => Promise<void>
@@ -98,6 +98,10 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
// Track if we've already initialized to avoid reloading on navigation
const hasInitializedRef = useRef(false)
const lastPubkeyRef = useRef<string | null>(null)
// Background subscription for real-time DM updates
const dmSubscriptionRef = useRef<{ close: () => void } | null>(null)
// Track newest message timestamp from subscription (to update hasNewMessages)
const [newestIncomingTimestamp, setNewestIncomingTimestamp] = useState(0)
// Create encryption wrapper object for dm.service
const encryption: IDMEncryption | null = useMemo(() => {
@@ -180,6 +184,16 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
// Step 4: Background refresh from network (don't clear existing data)
backgroundRefreshConversations()
// Step 5: Start real-time subscription for new DMs
if (dmSubscriptionRef.current) {
dmSubscriptionRef.current.close()
}
const relayUrls = relayList?.read || []
dmSubscriptionRef.current = dmService.subscribeToDMs(pubkey, relayUrls, (event) => {
// New DM event received - update timestamp to trigger hasNewMessages
setNewestIncomingTimestamp(event.created_at)
})
}
loadDeletedStateAndConversations()
@@ -196,11 +210,16 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
setIsSelectionMode(false)
// Clear in-memory plaintext cache
clearPlaintextCache()
// Stop DM subscription
if (dmSubscriptionRef.current) {
dmSubscriptionRef.current.close()
dmSubscriptionRef.current = null
}
// Reset initialization flag so we reload on next login
hasInitializedRef.current = false
lastPubkeyRef.current = null
}
}, [pubkey, encryption])
}, [pubkey, encryption, relayList])
// Load full conversation when selected
useEffect(() => {
@@ -598,12 +617,15 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
}, [currentConversation])
const sendMessage = useCallback(
async (content: string) => {
async (content: string, customRelayUrls?: string[]) => {
if (!pubkey || !encryption || !currentConversation) {
throw new Error('Cannot send message: not logged in or no conversation selected')
}
const relayUrls = relayList?.write || []
// Use custom relays if provided, otherwise fall back to user's write relays
const relayUrls = customRelayUrls && customRelayUrls.length > 0
? customRelayUrls
: (relayList?.write || [])
// Find existing encryption type for this conversation
const conversation = conversations.find((c) => c.partnerPubkey === currentConversation)
@@ -867,9 +889,12 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
// Check if there are new messages since last seen
const newestMessageTimestamp = useMemo(() => {
if (filteredConversations.length === 0) return 0
return Math.max(...filteredConversations.map((c) => c.lastMessageAt))
}, [filteredConversations])
const fromConversations = filteredConversations.length === 0
? 0
: Math.max(...filteredConversations.map((c) => c.lastMessageAt))
// Also consider real-time incoming messages
return Math.max(fromConversations, newestIncomingTimestamp)
}, [filteredConversations, newestIncomingTimestamp])
const hasNewMessages = newestMessageTimestamp > lastSeenTimestamp
@@ -878,6 +903,8 @@ export function DMProvider({ children }: { children: React.ReactNode }) {
if (!pubkey || newestMessageTimestamp === 0) return
setLastSeenTimestamp(newestMessageTimestamp)
storage.setDMLastSeenTimestamp(pubkey, newestMessageTimestamp)
// Reset incoming timestamp so indicator clears
setNewestIncomingTimestamp(0)
}, [pubkey, newestMessageTimestamp])
return (

View File

@@ -1,5 +1,6 @@
import AppearanceSettingsPage from '@/pages/secondary/AppearanceSettingsPage'
import BookmarkPage from '@/pages/secondary/BookmarkPage'
import DMConversationPage from '@/pages/secondary/DMConversationPage'
import EmojiPackSettingsPage from '@/pages/secondary/EmojiPackSettingsPage'
import ExternalContentPage from '@/pages/secondary/ExternalContentPage'
import FollowingListPage from '@/pages/secondary/FollowingListPage'
@@ -53,6 +54,7 @@ const SECONDARY_ROUTE_CONFIGS = [
{ path: '/mutes', element: <MuteListPage /> },
{ path: '/rizful', element: <RizfulPage /> },
{ path: '/bookmarks', element: <BookmarkPage /> },
{ path: '/dm/:pubkey', element: <DMConversationPage /> },
{ path: '/follow-packs/:id', element: <FollowPackPage /> },
{ path: '/user-aggregation/:feedId/:npub', element: <UserAggregationDetailPage /> }
]

View File

@@ -877,6 +877,54 @@ class DMService {
const pTag = tags.find((t) => t[0] === 'p')
return pTag ? pTag[1] : null
}
/**
* Subscribe to incoming DMs in real-time
* Returns a close function to stop the subscription
*/
subscribeToDMs(
pubkey: string,
relayUrls: string[],
onEvent: (event: Event) => void
): { close: () => void } {
const allRelays = [...new Set([...relayUrls, ...BIG_RELAY_URLS])]
const since = Math.floor(Date.now() / 1000) - 60 // Start from 1 minute ago to catch recent
// Subscribe to NIP-04 DMs (kind 4) addressed to user
const nip04Sub = client.subscribe(
allRelays,
[
{ kinds: [KIND_ENCRYPTED_DM], '#p': [pubkey], since },
{ kinds: [KIND_ENCRYPTED_DM], authors: [pubkey], since }
],
{
onevent: (event) => {
indexedDb.putDMEvent(event).catch(() => {})
onEvent(event)
}
}
)
// Subscribe to NIP-17 gift wraps (kind 1059) addressed to user
const giftWrapSub = client.subscribe(
allRelays,
{ kinds: [KIND_GIFT_WRAP], '#p': [pubkey], since },
{
onevent: (event) => {
indexedDb.putDMEvent(event).catch(() => {})
onEvent(event)
}
}
)
return {
close: async () => {
const [nip04, giftWrap] = await Promise.all([nip04Sub, giftWrapSub])
nip04.close()
giftWrap.close()
}
}
}
}
const dmService = new DMService()