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