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

PullRequestsScreen.tsx

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