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