| 1 | import { useNavigation } from "@react-navigation/native"; |
| 2 | import { parseThreadLinkPrompt } from "@t3tools/shared/promptLinks"; |
| 3 | import { useEffect, useRef } from "react"; |
| 4 | import { Alert } from "react-native"; |
| 5 | |
| 6 | import { applyLinkedPromptToThreadDraft } from "./prompt-link-actions"; |
| 7 | import { |
| 8 | clearedPromptLinkParams, |
| 9 | promptLinkNotice, |
| 10 | promptLinkSearchFromParams, |
| 11 | } from "./prompt-link-model"; |
| 12 | |
| 13 | const THREAD_LINK_KEYS = ["prompt"]; |
| 14 | |
| 15 | /** |
| 16 | * Applies the `prompt` of a `t3code://threads/<environmentId>/<threadId>?prompt=…` link to that |
| 17 | * thread's composer draft, once per link. Used by `ThreadRouteScreen`. |
| 18 | */ |
| 19 | export function useThreadPromptLink( |
| 20 | params: Readonly<Record<string, unknown>> | undefined, |
| 21 | threadDraftKey: string | null, |
| 22 | ) { |
| 23 | const navigation = useNavigation(); |
| 24 | const search = promptLinkSearchFromParams(params, THREAD_LINK_KEYS); |
| 25 | const handledSearchRef = useRef<string | null>(null); |
| 26 | useEffect(() => { |
| 27 | if (search === null) { |
| 28 | handledSearchRef.current = null; |
| 29 | return; |
| 30 | } |
| 31 | if (threadDraftKey === null || handledSearchRef.current === search) return; |
| 32 | handledSearchRef.current = search; |
| 33 | navigation.setParams(clearedPromptLinkParams(THREAD_LINK_KEYS)); |
| 34 | const parsed = parseThreadLinkPrompt(search); |
| 35 | if (!parsed.ok) { |
| 36 | Alert.alert("Could not open link", parsed.error); |
| 37 | return; |
| 38 | } |
| 39 | if (parsed.value === null) return; |
| 40 | void applyLinkedPromptToThreadDraft( |
| 41 | threadDraftKey, |
| 42 | parsed.value, |
| 43 | promptLinkNotice({ hiddenCharacters: parsed.value.hiddenCharacters }), |
| 44 | ); |
| 45 | }, [navigation, search, threadDraftKey]); |
| 46 | } |