Skip to content
This repository was archived by the owner on Jul 11, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions features/conversation/conversation-chat/conversation.nav.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { IXmtpConversationId, IXmtpInboxId } from "@features/xmtp/xmtp.types"
import { ConversationScreen } from "@/features/conversation/conversation-chat/conversation.screen"
import { translate } from "@/i18n"
import { AppNativeStack } from "@/navigation/app-navigator"
import { logger } from "@/utils/logger"

export type ConversationNavParams = {
xmtpConversationId?: IXmtpConversationId
composerTextPrefill?: string
searchSelectedUserInboxIds?: IXmtpInboxId[]
isNew?: boolean
}

export const ConversationScreenConfig = {
path: "/conversation/:inboxId?",
parse: {
inboxId: (value: string | undefined) => {
if (!value) return undefined;

const inboxId = decodeURIComponent(value) as IXmtpInboxId;
logger.info(`Parsing inboxId from URL: ${inboxId}`);
return inboxId;
},
composerTextPrefill: (value: string | undefined) => {
if (!value) return undefined;

const text = decodeURIComponent(value);
logger.info(`Parsing composerTextPrefill from URL: ${text}`);
return text;
}
},
stringify: {
inboxId: (value: IXmtpInboxId | undefined) => value ? encodeURIComponent(String(value)) : "",
composerTextPrefill: (value: string | undefined) => value ? encodeURIComponent(value) : "",
}
}

export function ConversationNav() {
return (
<AppNativeStack.Screen
options={{
title: "",
headerTitle: translate("chat"),
}}
name="Conversation"
component={ConversationScreen}
/>
)
}
41 changes: 41 additions & 0 deletions features/deep-linking/conversation-links.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { IXmtpConversationId, IXmtpInboxId } from "@/features/xmtp/xmtp.types"
import { findConversationByInboxIds } from "@/features/conversation/utils/find-conversations-by-inbox-ids"
import { useMultiInboxStore } from "@/features/authentication/multi-inbox.store"
import { logger } from "@/utils/logger"

/**
* Check if a conversation exists with the given inboxId
* @param inboxId The inbox ID to check
* @returns Promise with { exists, conversationId } - where conversationId is set if exists is true
*/
export async function checkConversationExists(inboxId: IXmtpInboxId): Promise<{ exists: boolean, conversationId?: IXmtpConversationId }> {
try {
// Get active user's inbox ID
const state = useMultiInboxStore.getState()
const activeInboxId = state.currentSender?.inboxId

if (!activeInboxId) {
logger.warn("Cannot check conversation existence - no active inbox")
return { exists: false }
}

// Try to find an existing conversation
const conversation = await findConversationByInboxIds({
inboxIds: [inboxId],
clientInboxId: activeInboxId,
})

if (conversation) {
logger.info(`Found existing conversation with ID: ${conversation.xmtpId}`)
return {
exists: true,
conversationId: conversation.xmtpId as IXmtpConversationId
}
}

return { exists: false }
} catch (error) {
logger.warn(`Error checking conversation existence: ${error}`)
return { exists: false }
}
}
107 changes: 107 additions & 0 deletions features/deep-linking/conversation-navigator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { useCallback } from "react"
import { useNavigation } from "@react-navigation/native"
import { captureError } from "@/utils/capture-error"
import { GenericError } from "@/utils/error"
import { IXmtpInboxId, IXmtpConversationId } from "@/features/xmtp/xmtp.types"
import { logger } from "@/utils/logger"
import { checkConversationExists } from "./conversation-links"

/**
* Custom hook to handle conversation deep links
* This is used by the DeepLinkHandler component to navigate to conversations from deep links
*/
export function useConversationDeepLinkHandler() {
const navigation = useNavigation()

/**
* Process an inbox ID from a deep link and navigate to the appropriate conversation
* @param inboxId The inbox ID from the deep link
* @param composerTextPrefill Optional text to prefill in the composer
*/
const handleConversationDeepLink = useCallback(async (
inboxId: IXmtpInboxId,
composerTextPrefill?: string
) => {
if (!inboxId) {
logger.warn("Cannot handle conversation deep link - missing inboxId")
return
}

try {
logger.info(`Handling conversation deep link for inboxId: ${inboxId}${composerTextPrefill ? ' with prefill text' : ''}`)

// Check if the conversation exists
const { exists, conversationId } = await checkConversationExists(inboxId)

if (exists && conversationId) {
// We have an existing conversation - navigate to it
logger.info(`Found existing conversation with ID: ${conversationId}`)

navigation.navigate("Conversation", {
xmtpConversationId: conversationId,
isNew: false,
composerTextPrefill
})
} else {
// No existing conversation - start a new one
logger.info(`No existing conversation found with inboxId: ${inboxId}, creating new conversation`)

navigation.navigate("Conversation", {
searchSelectedUserInboxIds: [inboxId],
isNew: true,
composerTextPrefill
})
}
} catch (error) {
captureError(
new GenericError({
error,
additionalMessage: `Failed to handle conversation deep link for inboxId: ${inboxId}`,
extra: { inboxId }
})
)
}
}, [navigation])

return { handleConversationDeepLink }
}

/**
* Global function to process a new deep link that uses the ConversationScreenConfig format
* This function is called by the navigation library when it receives a deep link
*/
export function processConversationDeepLink(
params: Record<string, string | undefined>
): Promise<boolean> {
return new Promise(async (resolve) => {
const { inboxId, composerTextPrefill } = params

if (!inboxId) {
// Skip if no inboxId
logger.warn("Cannot process conversation deep link - missing inboxId")
resolve(false)
return
}

try {
logger.info(`Processing Conversation deep link via navigation for inboxId: ${inboxId}${composerTextPrefill ? ' with prefill text' : ''}`)

// Check if the conversation exists
const { exists, conversationId } = await checkConversationExists(inboxId as IXmtpInboxId)

if (exists && conversationId) {
logger.info(`Navigation found existing conversation with ID: ${conversationId}`)
resolve(true)
return
}

// We didn't find an existing conversation, so we'll create a new one
logger.info(`No existing conversation found with inboxId: ${inboxId}, navigation will create a new conversation`)
resolve(true)
} catch (error) {
logger.error(`Error in processConversationDeepLink: ${error}`)
// Still return true to indicate we're handling it, even though there was an error
resolve(true)
}
})
}
73 changes: 73 additions & 0 deletions features/deep-linking/deep-link-handler.component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { useCallback, useEffect } from "react"
import { Linking } from "react-native"
import { IXmtpInboxId } from "@/features/xmtp/xmtp.types"
import { useAppState } from "@/stores/use-app-state-store"
import { logger } from "@/utils/logger"
import { parseURL } from "./link-parser"
import { useConversationDeepLinkHandler } from "./conversation-navigator"

/**
* Component that handles deep links for the app
* This should be included at the app root to handle incoming links
*/
export function DeepLinkHandler() {
const { currentState } = useAppState.getState()
const { handleConversationDeepLink } = useConversationDeepLinkHandler()

/**
* Handle a URL by parsing it and routing to the appropriate handler
*/
const handleUrl = useCallback(async (url: string) => {
logger.info(`Handling deep link URL: ${url}`)

const { segments, params } = parseURL(url)

// Handle different types of deep links based on the URL pattern
if (segments[0] === "conversation" && segments[1]) {
// Pattern: converse://conversation/{inboxId}
const inboxId = segments[1] as IXmtpInboxId
const composerTextPrefill = params.composerTextPrefill

logger.info(`Deep link matches conversation pattern, inboxId: ${inboxId}${
composerTextPrefill ? `, composerTextPrefill: ${composerTextPrefill}` : ''
}`)

// Use the conversation deep link handler
await handleConversationDeepLink(inboxId, composerTextPrefill)
} else {
logger.info(`Unhandled deep link pattern: ${segments.join('/')}`)
}
}, [handleConversationDeepLink])

// Handle initial URL when the app is first launched
useEffect(() => {
const getInitialURL = async () => {
try {
const initialUrl = await Linking.getInitialURL()
if (initialUrl) {
logger.info(`App launched from deep link: ${initialUrl}`)
handleUrl(initialUrl)
}
} catch (error) {
logger.warn(`Error getting initial URL: ${error}`)
}
}

getInitialURL()
}, [handleUrl])

// Listen for URL events when the app is running
useEffect(() => {
const subscription = Linking.addEventListener("url", ({ url }) => {
logger.info(`Received deep link while running: ${url}`)
handleUrl(url)
})

return () => {
subscription.remove()
}
}, [handleUrl, currentState])

// This is a utility component with no UI
return null
}
43 changes: 43 additions & 0 deletions features/deep-linking/link-parser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { logger } from "@/utils/logger"

/**
* Deep link URL parsing
* Takes a URL string and extracts information needed for handling deep links
*
* @param url The URL to parse
* @returns An object with parsed information from the URL, including:
* - path: The path of the URL
* - segments: The path segments
* - params: URL query parameters
*/
export function parseURL(url: string) {
try {
const parsedURL = new URL(url)
logger.info(`Parsing deep link URL: ${url}`)

// Extract the path without leading slash
const path = parsedURL.pathname.replace(/^\/+/, "")

// Split path into segments
const segments = path.split("/").filter(Boolean)

// Parse query parameters
const params: Record<string, string> = {}
parsedURL.searchParams.forEach((value, key) => {
params[key] = value
})

return {
path,
segments,
params
}
} catch (error) {
logger.warn(`Error parsing URL: ${url}, error: ${error}`)
return {
path: "",
segments: [],
params: {}
}
}
}
Loading