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