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