Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import {
3 type AtomCommandResult,
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import {
8 AuthOrchestrationOperateScope,
9 type ChatAttachment,
10 type ScopedThreadRef,
11 type ThreadGuestMessage,
12 type ThreadGuestShare,
13} from "@t3tools/contracts";
14import { Atom } from "effect/reactivity";
15import { type ReactNode, useEffect, useMemo, useState } from "react";
16import { View } from "react-native";
17
18import { Button } from "../../components/ui/Button";
19import { AppText as Text } from "../../components/ui/AppText";
20import { SymbolView } from "../../components/ui/AppSymbol";
21import * as Dialog from "../../components/ui/Dialog";
22import { useEnvironmentScope } from "../../state/session";
23import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
24import { useAtomCommand } from "../../state/use-atom-command";
25import { GUEST_PENDING_BUBBLE_CLASS_NAME, GuestMessageName } from "./guestMessageStyle";
26
27const NO_GUEST_SHARE_ATOM = Atom.make<ThreadGuestShare | null>(null);
28
29function guestShareAtom(ref: ScopedThreadRef) {
30 let previous: ThreadGuestShare | null = null;
31 return Atom.make((get) => {
32 const next =
33 get(environmentThreadDetails.threadAtom(ref))?.projection.thread.guestShare ?? null;
34 // The thread record is replaced on unrelated updates; only share changes matter here.
35 if (JSON.stringify(next) !== JSON.stringify(previous)) previous = next;
36 return previous;
37 });
38}
39
40export function useThreadGuestShare(threadRef: ScopedThreadRef | null): ThreadGuestShare | null {
41 const shareAtom = useMemo(
42 () => (threadRef === null ? NO_GUEST_SHARE_ATOM : guestShareAtom(threadRef)),
43 [threadRef],
44 );
45 return useAtomValue(shareAtom);
46}
47
48function alertOnFailure(failureTitle: string, result: AtomCommandResult<unknown, unknown>) {
49 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
50 const error = squashAtomCommandFailure(result);
51 Dialog.alert(failureTitle, error instanceof Error ? error.message : "Try again.");
52 }
53}
54
55/**
56 * Owner controls for a guest link, above the composer: who the link is for and a way to stop
57 * sharing. Links are created on web. Waiting messages show in the feed, see
58 * `ThreadGuestPendingMessage`.
59 */
60export function ThreadGuestShareBar(props: {
61 readonly threadRef: ScopedThreadRef | null;
62 readonly canOperateThread: boolean;
63}) {
64 const { threadRef } = props;
65 const share = useThreadGuestShare(threadRef);
66 const closeGuestShare = useAtomCommand(threadEnvironment.closeGuestShare, "stop guest sharing");
67 const [busy, setBusy] = useState(false);
68 // The server keeps an expired link so waiting messages stay resolvable; the label flips when
69 // it expires.
70 // Keyed by the expiry, so a replaced link (even one already expired) gets its own timer.
71 const [expiredAt, setExpiredAt] = useState<string | null>(null);
72 const expiresAt = share?.expiresAt;
73 useEffect(() => {
74 if (expiresAt === undefined) return;
75 const timer = setTimeout(
76 () => setExpiredAt(expiresAt),
77 Math.max(0, Date.parse(expiresAt) - Date.now()),
78 );
79 return () => clearTimeout(timer);
80 }, [expiresAt]);
81 if (threadRef === null || !share) return null;
82
83 const disabled = busy || !props.canOperateThread;
84 const stopSharing = () =>
85 Dialog.confirm({
86 title: "Stop sharing?",
87 message: "The guest loses access and the link stops working.",
88 confirmText: "Stop sharing",
89 destructive: true,
90 onConfirm: () => {
91 if (disabled) return;
92 setBusy(true);
93 void closeGuestShare({
94 environmentId: threadRef.environmentId,
95 input: { threadId: threadRef.threadId },
96 }).then((result) => {
97 setBusy(false);
98 alertOnFailure("Could not stop sharing", result);
99 });
100 },
101 });
102
103 return (
104 <View className="flex-row items-center gap-2 px-4 pb-2">
105 <SymbolView name="person.2" size={12} tintColorClassName="accent-foreground-muted" />
106 <Text className="min-w-0 flex-1 text-xs text-foreground-muted" numberOfLines={1}>
107 {expiredAt === share.expiresAt
108 ? "Guest link expired"
109 : share.guestName === null
110 ? "Guest link active"
111 : `${share.guestName} is a guest`}
112 </Text>
113 <Button label="Stop sharing" tone="text" disabled={disabled} onPress={stopSharing} />
114 </View>
115 );
116}
117
118/**
119 * One guest message waiting at the end of the feed until the owner sends or dismisses it. Sent
120 * ones then show in the feed as user messages with the guest's name.
121 */
122export function ThreadGuestPendingMessage(props: {
123 readonly threadRef: ScopedThreadRef;
124 readonly guestName: string;
125 readonly message: ThreadGuestMessage;
126 readonly bubbleMaxWidth: number | `${number}%`;
127 /** The feed's own attachment rendering, so the owner sees the files before Send. */
128 readonly renderAttachments: (attachments: ReadonlyArray<ChatAttachment>) => ReactNode;
129}) {
130 const { threadRef, guestName, message } = props;
131 const canOperate = useEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope);
132 const resolveGuestMessage = useAtomCommand(
133 threadEnvironment.resolveGuestMessage,
134 "resolve guest message",
135 );
136 // One request at a time: a second tap while the first is in flight would double-send.
137 const [busy, setBusy] = useState(false);
138
139 const resolve = async (decision: "send" | "dismiss") => {
140 if (busy) return;
141 setBusy(true);
142 const result = await resolveGuestMessage({
143 environmentId: threadRef.environmentId,
144 input: {
145 threadId: threadRef.threadId,
146 guestMessageId: message.id,
147 decision,
148 creationSource: "mobile",
149 },
150 });
151 setBusy(false);
152 alertOnFailure(
153 decision === "send" ? "Could not send guest message" : "Could not dismiss guest message",
154 result,
155 );
156 };
157
158 return (
159 <View className="items-end pb-5">
160 <GuestMessageName name={guestName} />
161 <View className={GUEST_PENDING_BUBBLE_CLASS_NAME} style={{ maxWidth: props.bubbleMaxWidth }}>
162 {message.text ? (
163 <Text selectable className="text-base text-foreground">
164 {message.text}
165 </Text>
166 ) : null}
167 {props.renderAttachments(message.attachments ?? [])}
168 </View>
169 {canOperate ? (
170 <View className="mt-1.5 flex-row gap-2">
171 <Button
172 label="Dismiss"
173 tone="secondary"
174 accessibilityLabel={`Dismiss message from ${guestName}`}
175 disabled={busy}
176 onPress={() => void resolve("dismiss")}
177 />
178 <Button
179 label="Send"
180 tone="primary"
181 accessibilityLabel={`Send message from ${guestName}`}
182 disabled={busy}
183 onPress={() => void resolve("send")}
184 />
185 </View>
186 ) : null}
187 </View>
188 );
189}