|
| 1 | +import type { DiscordMessageSummary, EnvironmentId, ThreadId } from "@t3tools/contracts"; |
| 2 | +import { useAtomValue } from "@effect/atom-react"; |
| 3 | +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; |
| 4 | +import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences"; |
| 5 | +import { discordThreadContextRecord } from "@t3tools/shared/integrationContextRecords"; |
| 6 | +import * as Cause from "effect/Cause"; |
| 7 | +import * as Option from "effect/Option"; |
| 8 | +import { AsyncResult } from "effect/reactivity"; |
| 9 | +import { useState, type ReactNode } from "react"; |
| 10 | +import { ActivityIndicator, Alert, FlatList, Pressable, View } from "react-native"; |
| 11 | +import { useSafeAreaInsets } from "react-native-safe-area-context"; |
| 12 | + |
| 13 | +import { relativeTime } from "../lib/time"; |
| 14 | +import { discordEnvironment } from "../state/discord"; |
| 15 | +import { useEnvironmentServerConfig } from "../state/entities"; |
| 16 | +import { useDebouncedValue } from "../state/queries"; |
| 17 | +import { useEnvironmentQuery } from "../state/query"; |
| 18 | +import { useAtomCommand } from "../state/use-atom-command"; |
| 19 | +import { |
| 20 | + captureComposerDraftInsertion, |
| 21 | + insertComposerDraftContext, |
| 22 | + type ComposerDraftInsertion, |
| 23 | +} from "../state/use-composer-drafts"; |
| 24 | +import { AppText as Text, AppTextInput } from "./ui/AppText"; |
| 25 | +import { PickerSheet } from "./PickerSheet"; |
| 26 | + |
| 27 | +/** Each search reads every server the bot is in, so typing settles before it queries. */ |
| 28 | +const SEARCH_DEBOUNCE_MS = 400; |
| 29 | + |
| 30 | +/** Discord's failures carry a reason; a rate limit deserves a clearer hint than its detail. */ |
| 31 | +function discordErrorMessage(error: unknown, fallback: string): string { |
| 32 | + if (typeof error === "object" && error !== null && "reason" in error) { |
| 33 | + if (error.reason === "rate-limited") return "Discord is busy. Try again shortly."; |
| 34 | + if (error.reason === "not-connected" || error.reason === "revoked") { |
| 35 | + return "Discord is not connected. Connect it from Settings > Integrations on desktop or web."; |
| 36 | + } |
| 37 | + if (error.reason === "not-found") return "That message is gone or not visible to the bot."; |
| 38 | + } |
| 39 | + return error instanceof Error && error.message.trim() ? error.message : fallback; |
| 40 | +} |
| 41 | + |
| 42 | +/** Attach inserts the message's thread into a composer draft; link links it to the thread's tab group. */ |
| 43 | +export type DiscordMessagePickerTarget = |
| 44 | + | { readonly mode?: "attach"; readonly environmentId: EnvironmentId; readonly draftKey: string } |
| 45 | + | { readonly mode: "link"; readonly environmentId: EnvironmentId; readonly threadId: ThreadId }; |
| 46 | + |
| 47 | +type OpenedDiscordMessagePicker = |
| 48 | + | { |
| 49 | + readonly mode: "attach"; |
| 50 | + readonly environmentId: EnvironmentId; |
| 51 | + readonly draftKey: string; |
| 52 | + readonly insertion: ComposerDraftInsertion; |
| 53 | + } |
| 54 | + | { readonly mode: "link"; readonly environmentId: EnvironmentId; readonly threadId: ThreadId }; |
| 55 | + |
| 56 | +/** |
| 57 | + * A Discord message picker. The owner renders `sheet` somewhere that outlives composer focus: |
| 58 | + * opening the sheet blurs the editor, which can unmount a focus-dependent toolbar. |
| 59 | + */ |
| 60 | +export function useDiscordMessagePicker(target: DiscordMessagePickerTarget | null): { |
| 61 | + readonly open: (() => void) | undefined; |
| 62 | + readonly sheet: ReactNode; |
| 63 | +} { |
| 64 | + const [opened, setOpened] = useState<OpenedDiscordMessagePicker | null>(null); |
| 65 | + const serverConfig = useEnvironmentServerConfig(target?.environmentId ?? null); |
| 66 | + const enabled = serverConfig?.settings.enableDiscordIntegration === true; |
| 67 | + const openedServerConfig = useEnvironmentServerConfig(opened?.environmentId ?? null); |
| 68 | + return { |
| 69 | + open: |
| 70 | + target && enabled |
| 71 | + ? () => |
| 72 | + setOpened( |
| 73 | + target.mode === "link" |
| 74 | + ? target |
| 75 | + : { |
| 76 | + ...target, |
| 77 | + mode: "attach", |
| 78 | + insertion: captureComposerDraftInsertion(target.draftKey), |
| 79 | + }, |
| 80 | + ) |
| 81 | + : undefined, |
| 82 | + sheet: |
| 83 | + opened && openedServerConfig?.settings.enableDiscordIntegration ? ( |
| 84 | + <DiscordMessagePickerSheet {...opened} onClose={() => setOpened(null)} /> |
| 85 | + ) : null, |
| 86 | + }; |
| 87 | +} |
| 88 | + |
| 89 | +/** |
| 90 | + * Attaches a Discord thread at the caret the composer had when the sheet opened, or links it to |
| 91 | + * the thread's tab group. Mobile has no Discord settings, so an unconnected environment points at |
| 92 | + * desktop or web. |
| 93 | + */ |
| 94 | +function DiscordMessagePickerSheet( |
| 95 | + props: OpenedDiscordMessagePicker & { readonly onClose: () => void }, |
| 96 | +) { |
| 97 | + const connection = useEnvironmentQuery( |
| 98 | + discordEnvironment.connection({ environmentId: props.environmentId, input: {} }), |
| 99 | + ); |
| 100 | + const phase = connection.data?.phase; |
| 101 | + return ( |
| 102 | + <PickerSheet |
| 103 | + title={props.mode === "link" ? "Link Discord thread" : "Discord message"} |
| 104 | + onClose={props.onClose} |
| 105 | + > |
| 106 | + {phase === "connected" ? ( |
| 107 | + <DiscordMessageSearch {...props} /> |
| 108 | + ) : ( |
| 109 | + <View className="flex-1 items-center justify-center p-6"> |
| 110 | + {phase === undefined && !connection.error ? ( |
| 111 | + <ActivityIndicator /> |
| 112 | + ) : ( |
| 113 | + <Text className="text-center text-foreground-muted"> |
| 114 | + {connection.error ?? |
| 115 | + "Discord is not connected on this environment. Connect it from Settings > Integrations on desktop or web."} |
| 116 | + </Text> |
| 117 | + )} |
| 118 | + </View> |
| 119 | + )} |
| 120 | + </PickerSheet> |
| 121 | + ); |
| 122 | +} |
| 123 | + |
| 124 | +function DiscordMessageSearch( |
| 125 | + props: OpenedDiscordMessagePicker & { readonly onClose: () => void }, |
| 126 | +) { |
| 127 | + const [query, setQuery] = useState(""); |
| 128 | + const trimmed = query.trim(); |
| 129 | + const settled = useDebouncedValue(trimmed, SEARCH_DEBOUNCE_MS); |
| 130 | + const getThread = useAtomCommand(discordEnvironment.getThread, { |
| 131 | + label: "discord thread fetch", |
| 132 | + reportFailure: false, |
| 133 | + }); |
| 134 | + const linkThread = useAtomCommand(discordEnvironment.linkThread, { |
| 135 | + label: "discord thread link", |
| 136 | + reportFailure: false, |
| 137 | + }); |
| 138 | + const [attaching, setAttaching] = useState<string | null>(null); |
| 139 | + |
| 140 | + const link = async (threadId: ThreadId, message: DiscordMessageSummary) => { |
| 141 | + const result = await linkThread({ |
| 142 | + environmentId: props.environmentId, |
| 143 | + input: { |
| 144 | + threadId, |
| 145 | + guildId: message.guildId, |
| 146 | + channelId: message.channelId, |
| 147 | + messageId: message.messageId, |
| 148 | + url: message.url, |
| 149 | + }, |
| 150 | + }); |
| 151 | + if (result._tag === "Failure") { |
| 152 | + Alert.alert( |
| 153 | + "Could not link Discord thread", |
| 154 | + discordErrorMessage(squashAtomCommandFailure(result), "Try again."), |
| 155 | + ); |
| 156 | + return; |
| 157 | + } |
| 158 | + props.onClose(); |
| 159 | + }; |
| 160 | + |
| 161 | + const attach = async (message: DiscordMessageSummary) => { |
| 162 | + if (attaching) return; |
| 163 | + setAttaching(message.url); |
| 164 | + try { |
| 165 | + if (props.mode === "link") { |
| 166 | + await link(props.threadId, message); |
| 167 | + return; |
| 168 | + } |
| 169 | + const fetched = await getThread({ |
| 170 | + environmentId: props.environmentId, |
| 171 | + input: { |
| 172 | + guildId: message.guildId, |
| 173 | + channelId: message.channelId, |
| 174 | + messageId: message.messageId, |
| 175 | + url: message.url, |
| 176 | + scope: "thread", |
| 177 | + }, |
| 178 | + }); |
| 179 | + if (fetched._tag === "Failure") { |
| 180 | + Alert.alert( |
| 181 | + "Could not attach Discord message", |
| 182 | + discordErrorMessage(squashAtomCommandFailure(fetched), "Try again."), |
| 183 | + ); |
| 184 | + return; |
| 185 | + } |
| 186 | + const record = discordThreadContextRecord(fetched.value); |
| 187 | + if ( |
| 188 | + !insertComposerDraftContext( |
| 189 | + props.draftKey, |
| 190 | + { |
| 191 | + text: formatComposerContextReference(record), |
| 192 | + context: { version: 1, records: [record] }, |
| 193 | + }, |
| 194 | + props.insertion, |
| 195 | + ) |
| 196 | + ) { |
| 197 | + Alert.alert("Too many context items", "Remove some context from the draft and try again."); |
| 198 | + return; |
| 199 | + } |
| 200 | + props.onClose(); |
| 201 | + } finally { |
| 202 | + setAttaching(null); |
| 203 | + } |
| 204 | + }; |
| 205 | + |
| 206 | + return ( |
| 207 | + <View className="flex-1"> |
| 208 | + <View className="px-4 pb-3"> |
| 209 | + <AppTextInput |
| 210 | + accessibilityLabel="Search Discord messages" |
| 211 | + autoFocus |
| 212 | + autoCapitalize="none" |
| 213 | + autoCorrect={false} |
| 214 | + clearButtonMode="while-editing" |
| 215 | + placeholder="Search Discord" |
| 216 | + returnKeyType="search" |
| 217 | + value={query} |
| 218 | + onChangeText={setQuery} |
| 219 | + /> |
| 220 | + </View> |
| 221 | + {settled ? ( |
| 222 | + <DiscordMessageResults |
| 223 | + environmentId={props.environmentId} |
| 224 | + query={settled} |
| 225 | + pendingInput={settled !== trimmed} |
| 226 | + attaching={attaching} |
| 227 | + onPick={(message) => void attach(message)} |
| 228 | + /> |
| 229 | + ) : ( |
| 230 | + <View className="items-center p-6"> |
| 231 | + {trimmed ? ( |
| 232 | + <ActivityIndicator /> |
| 233 | + ) : ( |
| 234 | + <Text className="text-center text-foreground-muted"> |
| 235 | + Search messages in every server the bot is in. |
| 236 | + </Text> |
| 237 | + )} |
| 238 | + </View> |
| 239 | + )} |
| 240 | + </View> |
| 241 | + ); |
| 242 | +} |
| 243 | + |
| 244 | +/** Mounted only for a settled, non-empty query, so an empty box never spends a search. */ |
| 245 | +function DiscordMessageResults(props: { |
| 246 | + readonly environmentId: EnvironmentId; |
| 247 | + readonly query: string; |
| 248 | + readonly pendingInput: boolean; |
| 249 | + readonly attaching: string | null; |
| 250 | + readonly onPick: (message: DiscordMessageSummary) => void; |
| 251 | +}) { |
| 252 | + const insets = useSafeAreaInsets(); |
| 253 | + const result = useAtomValue( |
| 254 | + discordEnvironment.messages({ |
| 255 | + environmentId: props.environmentId, |
| 256 | + input: { query: props.query }, |
| 257 | + }), |
| 258 | + ); |
| 259 | + const messages = Option.getOrNull(AsyncResult.value(result))?.messages ?? []; |
| 260 | + const pending = props.pendingInput || result.waiting; |
| 261 | + const error = |
| 262 | + result._tag === "Failure" |
| 263 | + ? discordErrorMessage(Cause.squash(result.cause), "Could not search Discord.") |
| 264 | + : null; |
| 265 | + return ( |
| 266 | + <FlatList |
| 267 | + data={messages} |
| 268 | + keyExtractor={(message) => message.url} |
| 269 | + keyboardShouldPersistTaps="handled" |
| 270 | + contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) }} |
| 271 | + ListEmptyComponent={ |
| 272 | + <View className="items-center p-6"> |
| 273 | + {pending ? ( |
| 274 | + <ActivityIndicator /> |
| 275 | + ) : ( |
| 276 | + <Text |
| 277 | + selectable={error !== null} |
| 278 | + className={ |
| 279 | + error ? "text-center text-danger-foreground" : "text-center text-foreground-muted" |
| 280 | + } |
| 281 | + > |
| 282 | + {error ?? "No matching messages."} |
| 283 | + </Text> |
| 284 | + )} |
| 285 | + </View> |
| 286 | + } |
| 287 | + renderItem={({ item }) => ( |
| 288 | + <Pressable |
| 289 | + accessibilityRole="button" |
| 290 | + accessibilityLabel={`${item.authorName} in ${item.channelLabel}: ${item.text}`} |
| 291 | + disabled={props.attaching !== null} |
| 292 | + onPress={() => props.onPick(item)} |
| 293 | + className="flex-row items-center gap-3 px-4 py-3 active:bg-subtle disabled:opacity-60" |
| 294 | + > |
| 295 | + <View className="min-w-0 flex-1 gap-0.5"> |
| 296 | + <Text className="text-sm text-foreground-muted" numberOfLines={1}> |
| 297 | + <Text className="text-sm font-t3-semibold text-foreground">{item.authorName}</Text> |
| 298 | + {` · ${item.channelLabel} · ${relativeTime(item.postedAt)}`} |
| 299 | + </Text> |
| 300 | + <Text className="text-base text-foreground" numberOfLines={2}> |
| 301 | + {item.text} |
| 302 | + </Text> |
| 303 | + </View> |
| 304 | + {props.attaching === item.url ? <ActivityIndicator /> : null} |
| 305 | + </Pressable> |
| 306 | + )} |
| 307 | + /> |
| 308 | + ); |
| 309 | +} |
0 commit comments