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 { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";
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 selectAndroidWorkspace = useAndroidWorkspaceSelection();
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 if (Platform.OS === "android") selectAndroidWorkspace({ name: "PullRequest", params });
122 else navigation.navigate("PullRequest", params);
123 },
124 [navigation, selectAndroidWorkspace],
125 );
126 const allProjects = useProjects();
127 const savedControls = listControls.controlsFor(environmentId);
128 const controls = useMemo(
129 () => withoutScratchProjectScope(savedControls, allProjects),
130 [allProjects, savedControls],
131 );
132 const targets = useMemo(
133 () =>
134 environments
135 .filter(
136 (environment) =>
137 configs.get(environment.environmentId)?.environment.capabilities.pullRequests ===
138 true &&
139 (environmentId === null || environment.environmentId === environmentId) &&
140 (!controls.projectEnvironmentId ||
141 environment.environmentId === controls.projectEnvironmentId),
142 )
143 .sort((left, right) => left.environmentId.localeCompare(right.environmentId))
144 .map((environment) => ({
145 environmentId: environment.environmentId,
146 input: pullRequestListInput(controls, query),
147 })),
148 [environments, environmentId, configs, controls, query],
149 );
150 const result = usePullRequestList(targets);
151 const connectedTargets = targets.filter((target) =>
152 environments.some(
153 (environment) =>
154 environment.environmentId === target.environmentId &&
155 environment.connectionState === "connected",
156 ),
157 );
158 const { actions, select, busyKey } = usePullRequestListActions(
159 connectedTargets.map((target) => target.environmentId),
160 result.updateEntry,
161 );
162 const sidebar = props.sidebar === true || primaryColumn !== null;
163 const selectedKey = props.selectedPullRequestKey ?? primaryColumn?.selectedPullRequestKey;
164 const connectedKey = connectedTargets.map((target) => target.environmentId).join("\n");
165 const entries = useMemo(
166 () =>
167 filterPullRequestList(
168 result.entries,
169 controls,
170 result.data?.viewers ?? {},
171 query,
172 result.data.localSearchHosts,
173 new Set(connectedKey.split("\n")),
174 ),
175 [result.entries, controls, query, result.data, connectedKey],
176 );
177 const facets = useMemo(() => pullRequestListFacets(result.entries), [result.entries]);
178 const [knownFacets, setKnownFacets] = useState({ environmentId, source: facets, ...facets });
179 if (knownFacets.environmentId !== environmentId || knownFacets.source !== facets) {
180 setKnownFacets((previous) => ({
181 source: facets,
182 environmentId,
183 authors: [
184 ...new Set([
185 ...(previous.environmentId === environmentId ? previous.authors : []),
186 ...facets.authors,
187 ]),
188 ].sort(),
189 labels: [
190 ...new Set([
191 ...(previous.environmentId === environmentId ? previous.labels : []),
192 ...facets.labels,
193 ]),
194 ].sort(),
195 labelColors: {
196 ...facets.labelColors,
197 ...(previous.environmentId === environmentId ? previous.labelColors : {}),
198 },
199 }));
200 }
201 const labelColors =
202 knownFacets.environmentId === environmentId ? knownFacets.labelColors : facets.labelColors;
203 const projects = allProjects.filter(
204 (project) =>
205 !project.isScratch && (environmentId === null || project.environmentId === environmentId),
206 );
207 const renderPullRequest = useCallback(
208 ({ item }: { readonly item: EnvironmentPullRequestListEntry }) => (
209 <PullRequestListRow
210 item={item}
211 onSelect={selectPullRequest}
212 getActions={actions}
213 onAction={select}
214 busy={busyKey === pullRequestKey(item)}
215 selected={selectedKey === pullRequestKey(item)}
216 sidebar={sidebar}
217 />
218 ),
219 [selectPullRequest, selectedKey, actions, select, busyKey, sidebar],
220 );
221 const previousSearchMode = useRef(tab.searchMode);
222 useEffect(() => {
223 const restoringSearch =
224 previousSearchMode.current !== "resting" && tab.searchMode === "resting";
225 previousSearchMode.current = tab.searchMode;
226 if (restoringSearch)
227 void listRef.current?.scrollToOffset({
228 offset: tab.scrollOffset - (Platform.OS === "ios" ? insets.top : 0),
229 animated: false,
230 });
231 }, [tab.searchMode, tab.scrollOffset, insets.top]);
232
233 return (
234 <View className={sidebar ? "flex-1 bg-drawer" : "flex-1 bg-screen"}>
235 <LegendList
236 ref={listRef}
237 data={entries}
238 extraData={`${selectedKey}:${busyKey}`}
239 keyExtractor={pullRequestKey}
240 itemsAreEqual={pullRequestListRowsAreEqual}
241 estimatedItemSize={88}
242 drawDistance={1_000}
243 maintainVisibleContentPosition={result.continued ? maintainVisiblePosition : false}
244 onEndReached={() => void result.loadMore()}
245 onEndReachedThreshold={0.5}
246 onViewableItemsChanged={result.onViewableItemsChanged}
247 refreshControl={
248 <RefreshControl
249 refreshing={result.refreshing}
250 onRefresh={() => void result.onRefresh()}
251 // The list already accounts for the navigation header in its content inset.
252 progressViewOffset={Platform.OS === "ios" ? 60 : undefined}
253 />
254 }
255 alwaysBounceVertical
256 // Android flashes a list's scrollbar whenever it becomes visible, which was every return
257 // to this tab. The thread list shows none either.
258 showsVerticalScrollIndicator={Platform.OS !== "android"}
259 recycleItems
260 renderScrollComponent={Platform.OS === "ios" ? PullRequestScrollView : undefined}
261 // UIKit owns the bar's inset, so a minimizing bar and a resized column move
262 // the list in the same frame as the bar.
263 contentInsetAdjustmentBehavior="automatic"
264 // A plain offset: LegendList adds the list header to an index-based restore, which
265 // landed every return one header lower.
266 initialScrollOffset={
267 initialOffset > 0 ? initialOffset - (Platform.OS === "ios" ? insets.top : 0) : undefined
268 }
269 contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0}
270 contentContainerStyle={{
271 paddingBottom:
272 Math.max(insets.bottom, workspace.bottomClearance) -
273 (Platform.OS === "ios" ? insets.bottom : 0),
274 }}
275 onScroll={(event) => {
276 workspace.recordScrollOffset(
277 "pullRequests",
278 Math.max(
279 0,
280 event.nativeEvent.contentOffset.y + (Platform.OS === "ios" ? insets.top : 0),
281 ),
282 );
283 }}
284 keyboardDismissMode="on-drag"
285 keyboardShouldPersistTaps="handled"
286 renderItem={renderPullRequest}
287 ListHeaderComponent={
288 <>
289 <PullRequestListFilters
290 sidebar={sidebar}
291 environments={environments.map((item) => ({
292 id: String(item.environmentId),
293 label: item.environmentLabel,
294 }))}
295 environmentId={environmentId}
296 onEnvironmentChange={listControls.setEnvironmentId}
297 value={
298 typedDraft
299 ? { ...controls, filters: { ...controls.filters, draft: typedDraft } }
300 : controls
301 }
302 onChange={(next) => {
303 const update = applyPullRequestDraftFilterChange(
304 typedQuery,
305 controls.filters,
306 next.filters,
307 );
308 listControls.setControls(environmentId, { ...next, filters: update.filters });
309 if (update.query !== typedQuery)
310 workspace.dispatch({ type: "query", tab: "pullRequests", query: update.query });
311 void listRef.current?.scrollToOffset({
312 offset: Platform.OS === "ios" ? -insets.top : 0,
313 animated: false,
314 });
315 }}
316 authors={
317 knownFacets.environmentId === environmentId ? knownFacets.authors : facets.authors
318 }
319 labels={
320 knownFacets.environmentId === environmentId ? knownFacets.labels : facets.labels
321 }
322 labelColors={labelColors}
323 projects={projects}
324 onSearch={(kind) =>
325 navigation.navigate("PullRequestFilterSearch", {
326 kind,
327 environmentId,
328 environmentIds: targets.map((target) => String(target.environmentId)),
329 suggestions:
330 knownFacets.environmentId === environmentId ? knownFacets[kind] : facets[kind],
331 labelColors,
332 })
333 }
334 />
335 {result.data?.errors.length ? (
336 <PullRequestListErrors
337 key={JSON.stringify(targets)}
338 messages={result.data.errors.map(
339 (error) =>
340 `${error.projectTitle || environments.find((environment) => environment.environmentId === error.environmentId)?.environmentLabel || "Environment"}: ${error.message}`,
341 )}
342 />
343 ) : null}
344 </>
345 }
346 ListFooterComponent={
347 result.loadingMore ? (
348 <View className="items-center py-5">
349 <AppActivityIndicator
350 colorClassName="accent-icon"
351 accessibilityLabel="Loading more pull requests"
352 />
353 </View>
354 ) : result.loadMoreError ? (
355 <View className="items-center gap-2 px-8 py-4">
356 <Text className="text-xs text-foreground-muted">{result.loadMoreError}</Text>
357 <Button
358 label="Try again"
359 accessibilityLabel="Retry loading more pull requests"
360 onPress={() => void result.loadMore(true)}
361 />
362 </View>
363 ) : result.hasMore ? (
364 // A filtered page can be too short to scroll, which leaves nothing to reach the end of.
365 <View className="items-center py-4">
366 <Button
367 label="Load more"
368 accessibilityLabel="Load more pull requests"
369 onPress={() => void result.loadMore()}
370 />
371 </View>
372 ) : undefined
373 }
374 ListEmptyComponent={
375 result.isPending && connectedTargets.length > 0 ? (
376 <View className="items-center py-12">
377 <AppActivityIndicator colorClassName="accent-icon" />
378 </View>
379 ) : (
380 <View className="px-8 py-12">
381 <EmptyState
382 title={
383 result.error
384 ? "Couldn't load pull requests"
385 : targets.length && connectedTargets.length === 0
386 ? "Environment offline"
387 : targets.length
388 ? query
389 ? "No results"
390 : "No matching pull requests"
391 : "Connect an environment"
392 }
393 detail={
394 result.error ??
395 (targets.length && connectedTargets.length === 0
396 ? "Reconnect to load pull requests that aren't saved on this device."
397 : targets.length
398 ? "Pull requests from the selected environments' projects appear here."
399 : "Add an environment in Settings to browse its pull requests.")
400 }
401 variant="plain"
402 />
403 </View>
404 )
405 }
406 />
407 </View>
408 );
409}