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

PullRequestsScreen.tsx

400 lines16.2 KB

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