|
| 1 | +import type { |
| 2 | + EnvironmentId, |
| 3 | + GitHubIssueStateFilter, |
| 4 | + GitHubIssueSummary, |
| 5 | + OrchestrationMessageContext, |
| 6 | + ProjectId, |
| 7 | +} from "@t3tools/contracts"; |
| 8 | +import { |
| 9 | + gitHubIssueContextRecord, |
| 10 | + gitHubIssueLabel, |
| 11 | + threadsForGitHubIssue, |
| 12 | +} from "@t3tools/client-runtime/state/github-issues"; |
| 13 | +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; |
| 14 | +import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences"; |
| 15 | +import { useAtomValue } from "@effect/atom-react"; |
| 16 | +import * as Cause from "effect/Cause"; |
| 17 | +import * as Option from "effect/Option"; |
| 18 | +import { AsyncResult } from "effect/unstable/reactivity"; |
| 19 | +import { StackActions, useNavigation } from "@react-navigation/native"; |
| 20 | +import { useState, type ReactNode } from "react"; |
| 21 | +import { ActivityIndicator, Alert, FlatList, Pressable, View } from "react-native"; |
| 22 | +import { useSafeAreaInsets } from "react-native-safe-area-context"; |
| 23 | + |
| 24 | +import { useThreadShells } from "../state/entities"; |
| 25 | +import { gitHubIssueEnvironment } from "../state/githubIssues"; |
| 26 | +import { useDebouncedValue } from "../state/queries"; |
| 27 | +import { useEnvironmentQuery } from "../state/query"; |
| 28 | +import { useAtomCommand } from "../state/use-atom-command"; |
| 29 | +import { |
| 30 | + captureComposerDraftInsertion, |
| 31 | + insertComposerDraftContext, |
| 32 | + type ComposerDraftInsertion, |
| 33 | +} from "../state/use-composer-drafts"; |
| 34 | +import { confirmOpenExistingThread } from "./confirmOpenExistingThread"; |
| 35 | +import { AppText as Text, AppTextInput } from "./AppText"; |
| 36 | +import { PickerSheet } from "./PickerSheet"; |
| 37 | +import { SegmentedControl } from "./SegmentedControl"; |
| 38 | + |
| 39 | +/** Each search runs `gh` on the host, so typing settles before it queries. */ |
| 40 | +const SEARCH_DEBOUNCE_MS = 300; |
| 41 | + |
| 42 | +const STATE_OPTIONS = [ |
| 43 | + { value: "open", label: "Open" }, |
| 44 | + { value: "closed", label: "Closed" }, |
| 45 | + { value: "all", label: "All" }, |
| 46 | +] as const satisfies ReadonlyArray<{ value: GitHubIssueStateFilter; label: string }>; |
| 47 | + |
| 48 | +/** GitHub's failures carry a reason; the host's `gh` setup deserves a clearer hint than its detail. */ |
| 49 | +function gitHubIssueErrorMessage(error: unknown, fallback: string): string { |
| 50 | + if (typeof error === "object" && error !== null && "reason" in error) { |
| 51 | + if (error.reason === "rate-limited") return "GitHub is busy. Try again shortly."; |
| 52 | + if (error.reason === "unavailable") { |
| 53 | + return "The GitHub CLI (gh) is not installed on the computer running T3 Code."; |
| 54 | + } |
| 55 | + if (error.reason === "not-authenticated") { |
| 56 | + return "The GitHub CLI is not signed in. Run `gh auth login` on the computer running T3 Code."; |
| 57 | + } |
| 58 | + } |
| 59 | + return error instanceof Error && error.message.trim() ? error.message : fallback; |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Attach inserts the issue into a composer draft. `cwd` is the checkout whose repository lists |
| 64 | + * issues. With `startFrom` it starts a new thread from the issue: it first offers threads already |
| 65 | + * linked to it, and the thread the draft creates is linked once it sends. |
| 66 | + */ |
| 67 | +export interface GitHubIssuePickerTarget { |
| 68 | + readonly environmentId: EnvironmentId; |
| 69 | + readonly draftKey: string; |
| 70 | + readonly cwd: string; |
| 71 | + readonly startFrom?: { readonly projectId: ProjectId }; |
| 72 | +} |
| 73 | + |
| 74 | +type OpenedGitHubIssuePicker = GitHubIssuePickerTarget & { |
| 75 | + readonly insertion: ComposerDraftInsertion; |
| 76 | +}; |
| 77 | + |
| 78 | +/** Issues picked to start a draft's thread from, by draft key, until the draft sends. */ |
| 79 | +const startFromIssueUrls = new Map<string, string>(); |
| 80 | + |
| 81 | +/** |
| 82 | + * The issue URL the draft was started from, if its chip is still in the draft. Clears it: the |
| 83 | + * caller links the thread the draft just created. |
| 84 | + */ |
| 85 | +export function takeStartFromGitHubIssue( |
| 86 | + draftKey: string, |
| 87 | + context: OrchestrationMessageContext | undefined, |
| 88 | +): string | null { |
| 89 | + const url = startFromIssueUrls.get(draftKey); |
| 90 | + startFromIssueUrls.delete(draftKey); |
| 91 | + if (url === undefined) return null; |
| 92 | + const attached = context?.records.some( |
| 93 | + (record) => record.kind === "github-issue" && "url" in record && record.url === url, |
| 94 | + ); |
| 95 | + return attached ? url : null; |
| 96 | +} |
| 97 | + |
| 98 | +/** |
| 99 | + * A GitHub issue picker. The owner renders `sheet` somewhere that outlives composer focus: |
| 100 | + * opening the sheet blurs the editor, which can unmount a focus-dependent toolbar. |
| 101 | + */ |
| 102 | +export function useGitHubIssuePicker(target: GitHubIssuePickerTarget | null): { |
| 103 | + readonly open: () => void; |
| 104 | + readonly sheet: ReactNode; |
| 105 | +} { |
| 106 | + const [opened, setOpened] = useState<OpenedGitHubIssuePicker | null>(null); |
| 107 | + return { |
| 108 | + open: () => { |
| 109 | + if (target) { |
| 110 | + setOpened({ ...target, insertion: captureComposerDraftInsertion(target.draftKey) }); |
| 111 | + } |
| 112 | + }, |
| 113 | + sheet: opened ? <GitHubIssuePickerSheet {...opened} onClose={() => setOpened(null)} /> : null, |
| 114 | + }; |
| 115 | +} |
| 116 | + |
| 117 | +/** Attaches a GitHub issue at the caret the composer had when the sheet opened. */ |
| 118 | +function GitHubIssuePickerSheet(props: OpenedGitHubIssuePicker & { readonly onClose: () => void }) { |
| 119 | + const insets = useSafeAreaInsets(); |
| 120 | + const navigation = useNavigation(); |
| 121 | + const { startFrom } = props; |
| 122 | + const [query, setQuery] = useState(""); |
| 123 | + const [state, setState] = useState<GitHubIssueStateFilter>("open"); |
| 124 | + const trimmed = query.trim(); |
| 125 | + const settled = useDebouncedValue(trimmed, SEARCH_DEBOUNCE_MS); |
| 126 | + const result = useAtomValue( |
| 127 | + gitHubIssueEnvironment.issues({ |
| 128 | + environmentId: props.environmentId, |
| 129 | + input: { cwd: props.cwd, state, ...(settled ? { query: settled } : {}) }, |
| 130 | + }), |
| 131 | + ); |
| 132 | + const threadLinks = useEnvironmentQuery( |
| 133 | + gitHubIssueEnvironment.threadLinks({ environmentId: props.environmentId, input: {} }), |
| 134 | + ).data; |
| 135 | + // Starting from an issue offers the project's threads; attaching only marks issues in use. |
| 136 | + const candidateThreads = useThreadShells().filter( |
| 137 | + (thread) => |
| 138 | + thread.environmentId === props.environmentId && |
| 139 | + (!startFrom || thread.projectId === startFrom.projectId), |
| 140 | + ); |
| 141 | + const getIssue = useAtomCommand(gitHubIssueEnvironment.getIssue, { |
| 142 | + label: "github issue fetch", |
| 143 | + reportFailure: false, |
| 144 | + }); |
| 145 | + const [attaching, setAttaching] = useState<string | null>(null); |
| 146 | + const issues = Option.getOrNull(AsyncResult.value(result))?.issues ?? []; |
| 147 | + const pending = settled !== trimmed || result.waiting; |
| 148 | + const error = |
| 149 | + result._tag === "Failure" |
| 150 | + ? gitHubIssueErrorMessage(Cause.squash(result.cause), "Could not load GitHub issues.") |
| 151 | + : null; |
| 152 | + |
| 153 | + const pick = async (issue: GitHubIssueSummary) => { |
| 154 | + if (attaching) return; |
| 155 | + if (startFrom) { |
| 156 | + const choice = await confirmOpenExistingThread( |
| 157 | + gitHubIssueLabel(issue), |
| 158 | + threadsForGitHubIssue(candidateThreads, threadLinks, issue.url), |
| 159 | + ); |
| 160 | + if (choice === "cancel") return; |
| 161 | + if (choice !== "start") { |
| 162 | + props.onClose(); |
| 163 | + navigation.dispatch( |
| 164 | + StackActions.replace("Thread", { |
| 165 | + environmentId: String(choice.environmentId), |
| 166 | + threadId: String(choice.id), |
| 167 | + }), |
| 168 | + ); |
| 169 | + return; |
| 170 | + } |
| 171 | + } |
| 172 | + await attach(issue); |
| 173 | + }; |
| 174 | + |
| 175 | + const attach = async (issue: GitHubIssueSummary) => { |
| 176 | + setAttaching(issue.url); |
| 177 | + try { |
| 178 | + const fetched = await getIssue({ |
| 179 | + environmentId: props.environmentId, |
| 180 | + input: { url: issue.url }, |
| 181 | + }); |
| 182 | + if (fetched._tag === "Failure") { |
| 183 | + Alert.alert( |
| 184 | + "Could not attach issue", |
| 185 | + gitHubIssueErrorMessage(squashAtomCommandFailure(fetched), "Try again."), |
| 186 | + ); |
| 187 | + return; |
| 188 | + } |
| 189 | + const record = gitHubIssueContextRecord(fetched.value); |
| 190 | + if ( |
| 191 | + !insertComposerDraftContext( |
| 192 | + props.draftKey, |
| 193 | + { |
| 194 | + text: formatComposerContextReference(record), |
| 195 | + context: { version: 1, records: [record] }, |
| 196 | + }, |
| 197 | + props.insertion, |
| 198 | + ) |
| 199 | + ) { |
| 200 | + Alert.alert("Too many context items", "Remove some context from the draft and try again."); |
| 201 | + return; |
| 202 | + } |
| 203 | + if (startFrom) startFromIssueUrls.set(props.draftKey, issue.url); |
| 204 | + props.onClose(); |
| 205 | + } finally { |
| 206 | + setAttaching(null); |
| 207 | + } |
| 208 | + }; |
| 209 | + |
| 210 | + return ( |
| 211 | + <PickerSheet title={startFrom ? "Start from issue" : "GitHub issue"} onClose={props.onClose}> |
| 212 | + <View className="gap-3 px-4 pb-3"> |
| 213 | + <AppTextInput |
| 214 | + accessibilityLabel="Search GitHub issues" |
| 215 | + autoFocus |
| 216 | + autoCapitalize="none" |
| 217 | + autoCorrect={false} |
| 218 | + clearButtonMode="while-editing" |
| 219 | + placeholder="Search, or paste #123 or an issue link" |
| 220 | + returnKeyType="search" |
| 221 | + value={query} |
| 222 | + onChangeText={setQuery} |
| 223 | + /> |
| 224 | + <SegmentedControl |
| 225 | + options={STATE_OPTIONS} |
| 226 | + selected={state} |
| 227 | + onSelect={setState} |
| 228 | + size="compact" |
| 229 | + /> |
| 230 | + </View> |
| 231 | + <FlatList |
| 232 | + data={issues} |
| 233 | + keyExtractor={(issue) => issue.url} |
| 234 | + keyboardShouldPersistTaps="handled" |
| 235 | + contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) }} |
| 236 | + ListEmptyComponent={ |
| 237 | + <View className="items-center p-6"> |
| 238 | + {pending ? ( |
| 239 | + <ActivityIndicator /> |
| 240 | + ) : ( |
| 241 | + <Text |
| 242 | + selectable={error !== null} |
| 243 | + className={ |
| 244 | + error ? "text-center text-danger-foreground" : "text-center text-foreground-muted" |
| 245 | + } |
| 246 | + > |
| 247 | + {error ?? (trimmed ? "No matching issues." : "No issues.")} |
| 248 | + </Text> |
| 249 | + )} |
| 250 | + </View> |
| 251 | + } |
| 252 | + renderItem={({ item }) => { |
| 253 | + const inUse = threadsForGitHubIssue(candidateThreads, threadLinks, item.url).length > 0; |
| 254 | + return ( |
| 255 | + <Pressable |
| 256 | + accessibilityRole="button" |
| 257 | + accessibilityLabel={`${gitHubIssueLabel(item)} ${item.title}, ${item.state}${inUse ? ", in use" : ""}`} |
| 258 | + disabled={attaching !== null} |
| 259 | + onPress={() => void pick(item)} |
| 260 | + className="flex-row items-center gap-3 px-4 py-3 active:bg-subtle disabled:opacity-60" |
| 261 | + > |
| 262 | + <View className="min-w-0 flex-1 gap-0.5"> |
| 263 | + <Text className="text-base text-foreground" numberOfLines={2}> |
| 264 | + {item.title} |
| 265 | + </Text> |
| 266 | + <Text className="text-sm text-foreground-muted" numberOfLines={1}> |
| 267 | + {gitHubIssueLabel(item)} · {item.state === "open" ? "Open" : "Closed"} |
| 268 | + {inUse ? " · In use" : ""} |
| 269 | + </Text> |
| 270 | + </View> |
| 271 | + {attaching === item.url ? <ActivityIndicator /> : null} |
| 272 | + </Pressable> |
| 273 | + ); |
| 274 | + }} |
| 275 | + /> |
| 276 | + </PickerSheet> |
| 277 | + ); |
| 278 | +} |
0 commit comments