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