Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PullRequestsScreen.tsx

425 lines16.9 KB

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