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

PullRequestsScreen.tsx

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