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