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

PullRequestsScreen.tsx

386 lines15.0 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 } 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 { ScrollViewMarker } from "react-native-screens";
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 { useWorkspaceState } from "../../state/workspace";
26import { useProjects } from "../../state/entities";
27import { environmentServerConfigsAtom } from "../../state/server";
28import { PullRequestListRow } from "./PullRequestListRow";
29import { PullRequestListFilters } from "./PullRequestListFilters";
30import { PullRequestCardRow } from "./PullRequestControls";
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} from "./pullRequestList";
43import { useDebouncedValue } from "../../state/queries";
44import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
45import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";
46​
47function PullRequestScrollView(props: ScrollViewProps) {
48 const insets = useSafeAreaInsets();
49 return (
50 <ScrollViewMarker style={{ flex: 1 }}>
51 <ScrollView
52 {...props}
53 automaticallyAdjustContentInsets={false}
54 contentInsetAdjustmentBehavior="never"
55 contentOffset={props.contentOffset ?? { x: 0, y: -insets.top }}
56 />
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) {
90 const navigation = useNavigation();
91 const primaryColumn = use(NativePrimaryColumnContext);
92 const workspace = useWorkspaceTabs()!;
93 const { environments } = useWorkspaceState();
94 const configs = useAtomValue(environmentServerConfigsAtom);
95 const insets = useSafeAreaInsets();
96 const [initialOffset] = useState(() => workspace.getScrollOffset("pullRequests"));
97 const listRef = useRef<LegendListRef>(null);
98 const tab = workspace.state.tabs.pullRequests;
99 const maintainVisiblePosition = useMemo(
100 () => ({
101 data: tab.searchMode === "resting",
102 shouldRestorePosition: () => workspace.getScrollOffset("pullRequests") > 0,
103 }),
104 [tab.searchMode, workspace],
105 );
106 const debouncedQuery = useDebouncedValue(tab.query.trim(), 180);
107 const query = tab.searchMode === "resting" ? "" : debouncedQuery;
108 const typedQuery = tab.searchMode === "resting" ? "" : tab.query;
109 const typedDraft = parsePullRequestQuery(typedQuery).filters.draft;
110 const listControls = usePullRequestListControls();
111 const selectedEnvironmentId = listControls.environmentId;
112 const environmentId = environments.some((item) => item.environmentId === selectedEnvironmentId)
113 ? selectedEnvironmentId
114 : null;
115 const selectAndroidWorkspace = useAndroidWorkspaceSelection();
116 const selectPullRequest = useCallback(
117 (item: EnvironmentPullRequestListEntry) => {
118 Keyboard.dismiss();
119 const params = {
120 environmentId: String(item.environmentId),
121 projectId: String(item.projectId),
122 repository: item.repository,
123 number: item.number,
124 host: item.host,
125 initialSummary: item,
126 };
127 if (Platform.OS === "android") selectAndroidWorkspace({ name: "PullRequest", params });
128 else navigation.navigate("PullRequest", params);
129 },
130 [navigation, selectAndroidWorkspace],
131 );
132 const allProjects = useProjects();
133 const savedControls = listControls.controlsFor(environmentId);
134 const controls = useMemo(
135 () => withoutScratchProjectScope(savedControls, allProjects),
136 [allProjects, savedControls],
137 );
138 const targets = useMemo(
139 () =>
140 environments
141 .filter(
142 (environment) =>
143 configs.get(environment.environmentId)?.environment.capabilities.pullRequests ===
144 true &&
145 (environmentId === null || environment.environmentId === environmentId) &&
146 (!controls.projectEnvironmentId ||
147 environment.environmentId === controls.projectEnvironmentId),
148 )
149 .sort((left, right) => left.environmentId.localeCompare(right.environmentId))
150 .map((environment) => ({
151 environmentId: environment.environmentId,
152 input: pullRequestListInput(controls, query),
153 })),
154 [environments, environmentId, configs, controls, query],
155 );
156 const result = usePullRequestList(targets);
157 const connectedTargets = targets.filter((target) =>
158 environments.some(
159 (environment) =>
160 environment.environmentId === target.environmentId &&
161 environment.connectionState === "connected",
162 ),
163 );
164 const { actions, select, busyKey } = usePullRequestListActions(
165 connectedTargets.map((target) => target.environmentId),
166 result.updateEntry,
167 );
168 const sidebar = props.sidebar === true || primaryColumn !== null;
169 const selectedKey = props.selectedPullRequestKey ?? primaryColumn?.selectedPullRequestKey;
170 const connectedKey = connectedTargets.map((target) => target.environmentId).join("\n");
171 const entries = useMemo(
172 () =>
173 filterPullRequestList(
174 result.entries,
175 controls,
176 result.data?.viewers ?? {},
177 query,
178 result.data.localSearchHosts,
179 new Set(connectedKey.split("\n")),
180 ),
181 [result.entries, controls, query, result.data, connectedKey],
182 );
183 const facets = useMemo(() => pullRequestListFacets(result.entries), [result.entries]);
184 const [knownFacets, setKnownFacets] = useState({ environmentId, source: facets, ...facets });
185 if (knownFacets.environmentId !== environmentId || knownFacets.source !== facets) {
186 setKnownFacets((previous) => ({
187 source: facets,
188 environmentId,
189 authors: [
190 ...new Set([
191 ...(previous.environmentId === environmentId ? previous.authors : []),
192 ...facets.authors,
193 ]),
194 ].sort(),
195 labels: [
196 ...new Set([
197 ...(previous.environmentId === environmentId ? previous.labels : []),
198 ...facets.labels,
199 ]),
200 ].sort(),
201 }));
202 }
203 const projects = allProjects.filter(
204 (project) =>
205 !project.isScratch && (environmentId === null || project.environmentId === environmentId),
206 );
207 const renderPullRequest = useCallback(
208 ({ item }: { readonly item: EnvironmentPullRequestListEntry }) => (
209 <PullRequestListRow
210 item={item}
211 onSelect={selectPullRequest}
212 getActions={actions}
213 onAction={select}
214 busy={busyKey === pullRequestKey(item)}
215 selected={selectedKey === pullRequestKey(item)}
216 sidebar={sidebar}
217 />
218 ),
219 [selectPullRequest, selectedKey, actions, select, busyKey, sidebar],
220 );
221 const previousSearchMode = useRef(tab.searchMode);
222 useEffect(() => {
223 const restoringSearch =
224 previousSearchMode.current !== "resting" && tab.searchMode === "resting";
225 previousSearchMode.current = tab.searchMode;
226 if (restoringSearch)
227 void listRef.current?.scrollToOffset({
228 offset: tab.scrollOffset - (Platform.OS === "ios" ? insets.top : 0),
229 animated: false,
230 });
231 }, [tab.searchMode, tab.scrollOffset, insets.top]);
232​
233 return (
234 <View className={sidebar ? "flex-1 bg-drawer" : "flex-1 bg-screen"}>
235 <LegendList
236 ref={listRef}
237 data={entries}
238 extraData={`${selectedKey}:${busyKey}`}
239 keyExtractor={pullRequestKey}
240 itemsAreEqual={pullRequestListRowsAreEqual}
241 estimatedItemSize={88}
242 drawDistance={1_000}
243 maintainVisibleContentPosition={result.continued ? maintainVisiblePosition : false}
244 onEndReached={() => void result.loadMore()}
245 onEndReachedThreshold={0.5}
246 onViewableItemsChanged={result.onViewableItemsChanged}
247 refreshControl={
248 <RefreshControl
249 refreshing={result.refreshing}
250 onRefresh={() => void result.onRefresh()}
251 // The list already accounts for the navigation header in its content inset.
252 progressViewOffset={Platform.OS === "ios" ? 60 : undefined}
253 />
254 }
255 alwaysBounceVertical
256 // Android flashes a list's scrollbar whenever it becomes visible, which was every return
257 // to this tab. The thread list shows none either.
258 showsVerticalScrollIndicator={Platform.OS !== "android"}
259 recycleItems
260 renderScrollComponent={Platform.OS === "ios" ? PullRequestScrollView : undefined}
261 contentInsetAdjustmentBehavior="never"
262 contentInset={Platform.OS === "ios" ? { top: insets.top } : undefined}
263 // A plain offset: LegendList adds the list header to an index-based restore, which
264 // landed every return one header lower.
265 initialScrollOffset={
266 initialOffset > 0 ? initialOffset - (Platform.OS === "ios" ? insets.top : 0) : undefined
267 }
268 contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0}
269 contentContainerStyle={{
270 paddingBottom: Math.max(insets.bottom, workspace.bottomClearance),
271 }}
272 onScroll={(event) => {
273 workspace.recordScrollOffset(
274 "pullRequests",
275 Math.max(
276 0,
277 event.nativeEvent.contentOffset.y + (Platform.OS === "ios" ? insets.top : 0),
278 ),
279 );
280 }}
281 keyboardDismissMode="on-drag"
282 keyboardShouldPersistTaps="handled"
283 renderItem={renderPullRequest}
284 ListHeaderComponent={
285 <>
286 <PullRequestListFilters
287 sidebar={sidebar}
288 environments={environments.map((item) => ({
289 id: String(item.environmentId),
290 label: item.environmentLabel,
291 }))}
292 environmentId={environmentId}
293 onEnvironmentChange={listControls.setEnvironmentId}
294 value={
295 typedDraft
296 ? { ...controls, filters: { ...controls.filters, draft: typedDraft } }
297 : controls
298 }
299 onChange={(next) => {
300 const update = applyPullRequestDraftFilterChange(
301 typedQuery,
302 controls.filters,
303 next.filters,
304 );
305 listControls.setControls(environmentId, { ...next, filters: update.filters });
306 if (update.query !== typedQuery)
307 workspace.dispatch({ type: "query", tab: "pullRequests", query: update.query });
308 void listRef.current?.scrollToOffset({
309 offset: Platform.OS === "ios" ? -insets.top : 0,
310 animated: false,
311 });
312 }}
313 authors={
314 knownFacets.environmentId === environmentId ? knownFacets.authors : facets.authors
315 }
316 labels={
317 knownFacets.environmentId === environmentId ? knownFacets.labels : facets.labels
318 }
319 projects={projects}
320 />
321 {result.data?.errors.length ? (
322 <PullRequestListErrors
323 key={JSON.stringify(targets)}
324 messages={result.data.errors.map(
325 (error) =>
326 `${error.projectTitle || environments.find((environment) => environment.environmentId === error.environmentId)?.environmentLabel || "Environment"}: ${error.message}`,
327 )}
328 />
329 ) : null}
330 </>
331 }
332 ListFooterComponent={
333 result.loadingMore ? (
334 <View className="items-center py-5">
335 <AppActivityIndicator
336 colorClassName="accent-icon"
337 accessibilityLabel="Loading more pull requests"
338 />
339 </View>
340 ) : result.loadMoreError ? (
341 <View className="items-center gap-2 px-8 py-4">
342 <Text className="text-xs text-foreground-muted">{result.loadMoreError}</Text>
343 <Button
344 label="Try again"
345 accessibilityLabel="Retry loading more pull requests"
346 onPress={() => void result.loadMore(true)}
347 />
348 </View>
349 ) : undefined
350 }
351 ListEmptyComponent={
352 result.isPending && connectedTargets.length > 0 ? (
353 <View className="items-center py-12">
354 <AppActivityIndicator colorClassName="accent-icon" />
355 </View>
356 ) : (
357 <View className="px-8 py-12">
358 <EmptyState
359 title={
360 result.error
361 ? "Couldn't load pull requests"
362 : targets.length && connectedTargets.length === 0
363 ? "Environment offline"
364 : targets.length
365 ? query
366 ? "No results"
367 : "No matching pull requests"
368 : "Connect an environment"
369 }
370 detail={
371 result.error ??
372 (targets.length && connectedTargets.length === 0
373 ? "Reconnect to load pull requests that aren't saved on this device."
374 : targets.length
375 ? "Pull requests from the selected environments' projects appear here."
376 : "Add an environment in Settings to browse its pull requests.")
377 }
378 variant="plain"
379 />
380 </View>
381 )
382 }
383 />
384 </View>
385 );