Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

MarkdownThreadLink.tsx

66 lines2.5 KB

1import type { EnvironmentId } from "@t3tools/contracts";
2import {
3 formatHostedThreadLink,
4 guessThreadLinkRef,
5 threadLinkCandidates,
6 type ThreadLink,
7 unknownThreadLinkLabel,
8} from "@t3tools/shared/threadLinks";
9​
10import { configuredHostedAppUrl } from "../../hostedPairing";
11import { useThreadRefs, useThreadShell } from "../../state/entities";
12import { orchestrationEnvironment } from "../../state/orchestration";
13import { useEnvironmentQuery } from "../../state/query";
14import { UnresolvedChip } from "../contextChipParts";
15import { ThreadContextChip } from "../ThreadContextChip";
16​
17/** `label` is the link's written text; an autolink has none. */
18export function MarkdownThreadLink(props: {
19 readonly environmentId: EnvironmentId;
20 readonly link: ThreadLink;
21 readonly label: string | null;
22}) {
23 const candidates = threadLinkCandidates(props.link, props.environmentId);
24 const writtenRef = candidates[0]!;
25 const written = useThreadShell(writtenRef);
26 const lookup = useEnvironmentQuery(
27 written === null
28 ? orchestrationEnvironment.threadLinkMetadata({
29 environmentId: writtenRef.environmentId,
30 input: { threadIds: candidates.map((ref) => ref.threadId) },
31 })
32 : null,
33 );
34 const settled = lookup.isSuccess && !lookup.isPending;
35 const target =
36 written !== null
37 ? { ref: writtenRef, metadata: written }
38 : (candidates.flatMap((ref) => {
39 const metadata = lookup.data?.[ref.threadId];
40 return metadata ? [{ ref, metadata }] : [];
41 })[0] ?? null);
42 const missing = target === null && settled;
43 const guess = missing && props.link.environmentId === null;
44 const refs = useThreadRefs(guess);
45 const remoteRef = guess
46 ? guessThreadLinkRef(
47 props.link,
48 refs.filter((ref) => ref.environmentId !== writtenRef.environmentId),
49 )
50 : null;
51 const remote = useThreadShell(remoteRef);
52 const resolved = target ?? (remoteRef && remote ? { ref: remoteRef, metadata: remote } : null);
53 if (missing && resolved === null) {
54 const unknown = unknownThreadLinkLabel(props.link, props.environmentId);
55 return <UnresolvedChip label={props.label ?? unknown} tooltip={unknown} />;
56 }
57 const ref = resolved?.ref ?? writtenRef;
58 const title = resolved?.metadata.title.trim() || props.label || "Thread";
59 return (
60 <ThreadContextChip
61 record={{ ...ref, title }}
62 projectId={resolved?.metadata.projectId ?? null}
63 copyMarkdown={formatHostedThreadLink(ref, title, configuredHostedAppUrl())}
64 />
65 );