Open History to see the last commit
1import { Button } from "../../components/ui/Button";
2import {
3 applyPullRequestDraftFilterChange,
4 parsePullRequestQuery,
5} from "@t3tools/client-runtime/pull-request-query";
6import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
7import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
8import { useNavigation } from "@react-navigation/native";
9import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";
10import { useAtomValue } from "@effect/atom-react";
11import {
12 Keyboard,
13 Platform,
14 RefreshControl,
15 ScrollView,
16 View,
17 type ScrollViewProps,
18} from "react-native";
19import { ScrollViewMarker } from "react-native-screens";
20import { useSafeAreaInsets } from "react-native-safe-area-context";
21
22import { AppText as Text } from "../../components/ui/AppText";
23import { EmptyState } from "../../components/ui/EmptyState";
24import { useRestingTopOffset } from "../../native/useRestingTopOffset";
25import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
26import { useWorkspaceState } from "../../state/workspace";
27import { useProjects } from "../../state/entities";
28import { environmentServerConfigsAtom } from "../../state/server";
29import { PullRequestListRow } from "./PullRequestListRow";
30import { PullRequestListFilters } from "./PullRequestListFilters";
31import { PullRequestCardRow } from "./PullRequestControls";
32import { usePullRequestList } from "./usePullRequestList";
33import { usePullRequestListControls } from "./usePullRequestListControls";
34import { usePullRequestListActions } from "./usePullRequestListActions";
35import {
36 filterPullRequestList,
37 pullRequestListFacets,
38 pullRequestListInput,
39 pullRequestListRowsAreEqual,
40 scopedPullRequestListKey as pullRequestKey,
41 type EnvironmentPullRequestListEntry,
42 withoutScratchProjectScope,
43} from "./pullRequestList";
44import { useDebouncedValue } from "../../state/queries";
45import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
46import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";
47
48function PullRequestScrollView(props: ScrollViewProps) {
49 const insets = useSafeAreaInsets();
50 const restingOffset = useRestingTopOffset(insets.top, props);
51 return (
52 <ScrollViewMarker style={{ flex: 1 }}>
53 <ScrollView
54 {...props}
55 {...restingOffset}
56 automaticallyAdjustContentInsets={false}
57 contentInsetAdjustmentBehavior="never"
58 />
59 </ScrollViewMarker>
60 );
61}
62
63function PullRequestListErrors(props: { readonly messages: readonly string[] }) {
64 const [expanded, setExpanded] = useState(false);
65 const title = `${props.messages.length} ${props.messages.length === 1 ? "error" : "errors"} loading pull requests`;
66 return (
67 <View>
68 <PullRequestCardRow
69 title={title}
70 icon="exclamationmark.triangle"
71 compact
72 last
73 expanded={expanded}
74 accessibilityLabel={`${title}. ${expanded ? "Hide" : "Show"} details`}
75 onPress={() => setExpanded((value) => !value)}
76 />
77 {expanded ? (
78 <Text selectable className="px-4 pb-3 text-sm text-foreground-muted">
79 {props.messages.join("\n")}
80 </Text>
81 ) : null}
82 </View>
83 );
84}
85
86export function PullRequestsScreen(
87 props: {
88 readonly sidebar?: boolean;
89 readonly selectedPullRequestKey?: string | null;
90 } = {},
91) {
92 const navigation = useNavigation();
93 const primaryColumn = use(NativePrimaryColumnContext);
94 const workspace = useWorkspaceTabs()!;
95 const { environments } = useWorkspaceState();
96 const configs = useAtomValue(environmentServerConfigsAtom);
97 const insets = useSafeAreaInsets();
98 const [initialOffset] = useState(() => workspace.getScrollOffset("pullRequests"));
99 const listRef = useRef<LegendListRef>(null);
100 const tab = workspace.state.tabs.pullRequests;
101 const maintainVisiblePosition = useMemo(
102 () => ({
103 data: tab.searchMode === "resting",
104 shouldRestorePosition: () => workspace.getScrollOffset("pullRequests") > 0,
105 }),
106 [tab.searchMode, workspace],
107 );
108 const debouncedQuery = useDebouncedValue(tab.query.trim(), 180);
109 const query = tab.searchMode === "resting" ? "" : debouncedQuery;
110 const typedQuery = tab.searchMode === "resting" ? "" : tab.query;
111 const typedDraft = parsePullRequestQuery(typedQuery).filters.draft;
112 const listControls = usePullRequestListControls();
113 const selectedEnvironmentId = listControls.environmentId;
114 const environmentId = environments.some((item) => item.environmentId === selectedEnvironmentId)
115 ? selectedEnvironmentId
116 : null;
117 const selectAndroidWorkspace = useAndroidWorkspaceSelection();
118 const selectPullRequest = useCallback(
119 (item: EnvironmentPullRequestListEntry) => {
120 Keyboard.dismiss();
121 const params = {
122 environmentId: String(item.environmentId),
123 projectId: String(item.projectId),
124 repository: item.repository,
125 number: item.number,
126 host: item.host,
127 initialSummary: item,
128 };
129 if (Platform.OS === "android") selectAndroidWorkspace({ name: "PullRequest", params });
130 else navigation.navigate("PullRequest", params);
131 },
132 [navigation, selectAndroidWorkspace],
133 );
134 const allProjects = useProjects();
135 const savedControls = listControls.controlsFor(environmentId);
136 const controls = useMemo(
137 () => withoutScratchProjectScope(savedControls, allProjects),
138 [allProjects, savedControls],
139 );
140 const targets = useMemo(
141 () =>
142 environments
143 .filter(
144 (environment) =>
145 configs.get(environment.environmentId)?.environment.capabilities.pullRequests ===
146 true &&
147 (environmentId === null || environment.environmentId === environmentId) &&
148 (!controls.projectEnvironmentId ||
149 environment.environmentId === controls.projectEnvironmentId),
150 )
151 .sort((left, right) => left.environmentId.localeCompare(right.environmentId))
152 .map((environment) => ({
153 environmentId: environment.environmentId,
154 input: pullRequestListInput(controls, query),
155 })),
156 [environments, environmentId, configs, controls, query],
157 );
158 const result = usePullRequestList(targets);
159 const connectedTargets = targets.filter((target) =>
160 environments.some(
161 (environment) =>
162 environment.environmentId === target.environmentId &&
163 environment.connectionState === "connected",
164 ),
165 );
166 const { actions, select, busyKey } = usePullRequestListActions(
167 connectedTargets.map((target) => target.environmentId),
168 result.updateEntry,
169 );
170 const sidebar = props.sidebar === true || primaryColumn !== null;
171 const selectedKey = props.selectedPullRequestKey ?? primaryColumn?.selectedPullRequestKey;
172 const connectedKey = connectedTargets.map((target) => target.environmentId).join("\n");
173 const entries = useMemo(
174 () =>
175 filterPullRequestList(
176 result.entries,
177 controls,
178 result.data?.viewers ?? {},
179 query,
180 result.data.localSearchHosts,
181 new Set(connectedKey.split("\n")),
182 ),
183 [result.entries, controls, query, result.data, connectedKey],
184 );
185 const facets = useMemo(() => pullRequestListFacets(result.entries), [result.entries]);
186 const [knownFacets, setKnownFacets] = useState({ environmentId, source: facets, ...facets });
187 if (knownFacets.environmentId !== environmentId || knownFacets.source !== facets) {
188 setKnownFacets((previous) => ({
189 source: facets,
190 environmentId,
191 authors: [
192 ...new Set([
193 ...(previous.environmentId === environmentId ? previous.authors : []),
194 ...facets.authors,
195 ]),
196 ].sort(),
197 labels: [
198 ...new Set([
199 ...(previous.environmentId === environmentId ? previous.labels : []),
200 ...facets.labels,
201 ]),
202 ].sort(),
203 }));
204 }
205 const projects = allProjects.filter(
206 (project) =>
207 !project.isScratch && (environmentId === null || project.environmentId === environmentId),
208 );
209 const renderPullRequest = useCallback(
210 ({ item }: { readonly item: EnvironmentPullRequestListEntry }) => (
211 <PullRequestListRow
212 item={item}
213 onSelect={selectPullRequest}
214 getActions={actions}
215 onAction={select}
216 busy={busyKey === pullRequestKey(item)}
217 selected={selectedKey === pullRequestKey(item)}
218 sidebar={sidebar}
219 />
220 ),
221 [selectPullRequest, selectedKey, actions, select, busyKey, sidebar],
222 );
223 const previousSearchMode = useRef(tab.searchMode);
224 useEffect(() => {
225 const restoringSearch =
226 previousSearchMode.current !== "resting" && tab.searchMode === "resting";
227 previousSearchMode.current = tab.searchMode;
228 if (restoringSearch)
229 void listRef.current?.scrollToOffset({
230 offset: tab.scrollOffset - (Platform.OS === "ios" ? insets.top : 0),
231 animated: false,
232 });
233 }, [tab.searchMode, tab.scrollOffset, insets.top]);
234
235 return (
236 <View className={sidebar ? "flex-1 bg-drawer" : "flex-1 bg-screen"}>
237 <LegendList
238 ref={listRef}
239 data={entries}
240 extraData={`${selectedKey}:${busyKey}`}
241 keyExtractor={pullRequestKey}
242 itemsAreEqual={pullRequestListRowsAreEqual}
243 estimatedItemSize={88}
244 drawDistance={1_000}
245 maintainVisibleContentPosition={result.continued ? maintainVisiblePosition : false}
246 onEndReached={() => void result.loadMore()}
247 onEndReachedThreshold={0.5}
248 onViewableItemsChanged={result.onViewableItemsChanged}
249 refreshControl={
250 <RefreshControl
251 refreshing={result.refreshing}
252 onRefresh={() => void result.onRefresh()}
253 // The list already accounts for the navigation header in its content inset.
254 progressViewOffset={Platform.OS === "ios" ? 60 : undefined}
255 />
256 }
257 alwaysBounceVertical
258 // Android flashes a list's scrollbar whenever it becomes visible, which was every return
259 // to this tab. The thread list shows none either.
260 showsVerticalScrollIndicator={Platform.OS !== "android"}
261 recycleItems
262 renderScrollComponent={Platform.OS === "ios" ? PullRequestScrollView : undefined}
263 contentInsetAdjustmentBehavior="never"
264 contentInset={Platform.OS === "ios" ? { top: insets.top } : undefined}
265 // A plain offset: LegendList adds the list header to an index-based restore, which
266 // landed every return one header lower.
267 initialScrollOffset={
268 initialOffset > 0 ? initialOffset - (Platform.OS === "ios" ? insets.top : 0) : undefined
269 }
270 contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0}
271 contentContainerStyle={{
272 paddingBottom: Math.max(insets.bottom, workspace.bottomClearance),
273 }}
274 onScroll={(event) => {
275 workspace.recordScrollOffset(
276 "pullRequests",
277 Math.max(
278 0,
279 event.nativeEvent.contentOffset.y + (Platform.OS === "ios" ? insets.top : 0),
280 ),
281 );
282 }}
283 keyboardDismissMode="on-drag"
284 keyboardShouldPersistTaps="handled"
285 renderItem={renderPullRequest}
286 ListHeaderComponent={
287 <>
288 <PullRequestListFilters
289 sidebar={sidebar}
290 environments={environments.map((item) => ({
291 id: String(item.environmentId),
292 label: item.environmentLabel,
293 }))}
294 environmentId={environmentId}
295 onEnvironmentChange={listControls.setEnvironmentId}
296 value={
297 typedDraft
298 ? { ...controls, filters: { ...controls.filters, draft: typedDraft } }
299 : controls
300 }
301 onChange={(next) => {
302 const update = applyPullRequestDraftFilterChange(
303 typedQuery,
304 controls.filters,
305 next.filters,
306 );
307 listControls.setControls(environmentId, { ...next, filters: update.filters });
308 if (update.query !== typedQuery)
309 workspace.dispatch({ type: "query", tab: "pullRequests", query: update.query });
310 void listRef.current?.scrollToOffset({
311 offset: Platform.OS === "ios" ? -insets.top : 0,
312 animated: false,
313 });
314 }}
315 authors={
316 knownFacets.environmentId === environmentId ? knownFacets.authors : facets.authors
317 }
318 labels={
319 knownFacets.environmentId === environmentId ? knownFacets.labels : facets.labels
320 }
321 projects={projects}
322 />
323 {result.data?.errors.length ? (
324 <PullRequestListErrors
325 key={JSON.stringify(targets)}
326 messages={result.data.errors.map(
327 (error) =>
328 `${error.projectTitle || environments.find((environment) => environment.environmentId === error.environmentId)?.environmentLabel || "Environment"}: ${error.message}`,
329 )}
330 />
331 ) : null}
332 </>
333 }
334 ListFooterComponent={
335 result.loadingMore ? (
336 <View className="items-center py-5">
337 <AppActivityIndicator
338 colorClassName="accent-icon"
339 accessibilityLabel="Loading more pull requests"
340 />
341 </View>
342 ) : result.loadMoreError ? (
343 <View className="items-center gap-2 px-8 py-4">
344 <Text className="text-xs text-foreground-muted">{result.loadMoreError}</Text>
345 <Button
346 label="Try again"
347 accessibilityLabel="Retry loading more pull requests"
348 onPress={() => void result.loadMore(true)}
349 />
350 </View>
351 ) : undefined
352 }
353 ListEmptyComponent={
354 result.isPending && connectedTargets.length > 0 ? (
355 <View className="items-center py-12">
356 <AppActivityIndicator colorClassName="accent-icon" />
357 </View>
358 ) : (
359 <View className="px-8 py-12">
360 <EmptyState
361 title={
362 result.error
363 ? "Couldn't load pull requests"
364 : targets.length && connectedTargets.length === 0
365 ? "Environment offline"
366 : targets.length
367 ? query
368 ? "No results"
369 : "No matching pull requests"
370 : "Connect an environment"
371 }
372 detail={
373 result.error ??
374 (targets.length && connectedTargets.length === 0
375 ? "Reconnect to load pull requests that aren't saved on this device."
376 : targets.length
377 ? "Pull requests from the selected environments' projects appear here."
378 : "Add an environment in Settings to browse its pull requests.")
379 }
380 variant="plain"
381 />
382 </View>
383 )
384 }
385 />
386 </View>
387 );
388}