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

PullRequestsScreen.tsx

441 lines18.1 KB

1import { usePaneRole } from "../../components/ui/Pane";
2import { Button } from "../../components/ui/Button";
3import {
4 applyPullRequestFilterChange,
5 parsePullRequestQuery,
6 pullRequestMenuFilters,
7} from "@t3tools/client-runtime/pull-request-query";
8import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
9import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
10import { useNavigation } from "@react-navigation/native";
11import { useGT } from "gt-react-native";
12import { use, useMemo, useRef, useState, type ReactNode } from "react";
13import { useAtomValue } from "@effect/atom-react";
14import { Keyboard, Platform, Pressable, View } from "react-native";
15import { RefreshControl } from "../../components/ui/RefreshControl";
16import { NativeScrollView } from "../../native/NativeScrollViewMarker";
17import { useSafeAreaInsets } from "react-native-safe-area-context";
18​
19import { AppText as Text } from "../../components/ui/AppText";
20import { useContentTopInset } from "../../components/ui/useBarInset";
21import { SymbolView } from "../../components/ui/AppSymbol";
22import { EmptyState } from "../../components/ui/EmptyState";
23import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
24import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
25import { useWorkspaceState } from "../../state/workspace";
26import { useProjects } from "../../state/entities";
27import { environmentPresentations } from "../../state/presentation";
28import { PullRequestListRow } from "./PullRequestListRow";
29import {
30 PullRequestListFilters,
31 usePullRequestListFilters,
32 type PullRequestFilterMenu,
33} from "./PullRequestListFilters";
34import { SavedViewsMenu } from "../layout/workspace/SavedViewsMenu";
35import { pullRequestViewMatches } from "./pullRequestSavedViews";
36import { usePullRequestList } from "./usePullRequestList";
37import { usePullRequestListControls } from "./usePullRequestListControls";
38import { usePullRequestListActions } from "./usePullRequestListActions";
39import {
40 distinctIgnoringCase,
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 {
52 useWorkspaceTabControls,
53 useWorkspaceTabsSelector,
54} from "../layout/workspace/WorkspaceTabsContext";
55import { useSearchScrollRestoration } from "../layout/workspace/useSearchScrollRestoration";
56import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
57​
58function PullRequestListError(props: { readonly message: string }) {
59 const [expanded, setExpanded] = useState(false);
60 return (
61 <Pressable
62 accessibilityRole="button"
63 accessibilityLabel={props.message}
64 accessibilityState={{ expanded }}
65 onPress={() => setExpanded((value) => !value)}
66 // A long press selects the text; collapsing under that selection crashes Android's
67 // smart-select animation, so it must not also count as a press.
68 onLongPress={() => undefined}
69 className="min-h-11 flex-row items-center gap-3 px-4 py-2.5 active:opacity-70"
70 >
71 <SymbolView
72 name="exclamationmark.triangle"
73 size={18}
74 tintColorClassName="accent-icon-muted"
75 />
76 <Text
77 selectable={expanded}
78 numberOfLines={expanded ? undefined : 1}
79 ellipsizeMode="tail"
80 className="min-w-0 flex-1 text-sm text-foreground-muted"
81 >
82 {props.message}
83 </Text>
84 <SymbolView
85 name={expanded ? "chevron.up" : "chevron.down"}
86 size={11}
87 tintColorClassName="accent-icon-muted"
88 />
89 </Pressable>
90 );
92​
93export function PullRequestsScreen(
94 props: {
95 readonly sidebar?: boolean;
96 readonly selectedPullRequestKey?: string | null;
97 /**
98 * Places the list under a header that opens the full filter menu (the Android toolbar). The
99 * filters live here, so the header gets them in the same render as the list.
100 */
101 readonly renderFrame?: (filters: PullRequestFilterMenu | null, list: ReactNode) => ReactNode;
102 } = {},
103) {
104 const navigation = useNavigation();
105 const gt = useGT();
106 const primaryColumn = use(NativePrimaryColumnContext);
107 const workspace = useWorkspaceTabControls()!;
108 const tab = useWorkspaceTabsSelector((state) => state.tabs.pullRequests)!;
109 const { environments } = useWorkspaceState();
110 // Without providers, so a provider status check does not re-render the list.
111 const configs = useAtomValue(environmentPresentations.serverConfigsAtom);
112 const insets = useSafeAreaInsets();
113 const contentTopInset = useContentTopInset();
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 [initialScrollOffset] = useState(() => workspace.getScrollOffset("pullRequests"));
120 useSearchScrollRestoration(tab.searchMode, () => {
121 void listRef.current?.scrollToOffset({
122 offset: tab.scrollOffset - contentTopInset,
123 animated: false,
124 });
125 });
126 const maintainVisiblePosition = {
127 data: tab.searchMode === "resting",
128 shouldRestorePosition: () => workspace.getScrollOffset("pullRequests") > 0,
129 };
130 const debouncedQuery = useDebouncedValue(tab.query.trim(), 180);
131 const query = tab.searchMode === "resting" ? "" : debouncedQuery;
132 const typedQuery = tab.searchMode === "resting" ? "" : tab.query;
133 const listControls = usePullRequestListControls();
134 const selectedEnvironmentId = listControls.environmentId;
135 const environmentId = environments.some((item) => item.environmentId === selectedEnvironmentId)
136 ? selectedEnvironmentId
137 : null;
138 const selectDetail = useSelectWorkspaceDetail();
139 const selectPullRequest = (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 const allProjects = useProjects();
152 const savedControls = listControls.controlsFor(environmentId);
153 const controls = useMemo(
154 () => withoutScratchProjectScope(savedControls, allProjects),
155 [allProjects, savedControls],
156 );
157 const targets = useMemo(
158 () =>
159 environments
160 .filter(
161 (environment) =>
162 configs.get(environment.environmentId) !== undefined &&
163 (environmentId === null || environment.environmentId === environmentId) &&
164 (!controls.projectEnvironmentId ||
165 environment.environmentId === controls.projectEnvironmentId),
166 )
167 .sort((left, right) => left.environmentId.localeCompare(right.environmentId))
168 .map((environment) => ({
169 environmentId: environment.environmentId,
170 input: pullRequestListInput(controls, query),
171 })),
172 [environments, environmentId, configs, controls, query],
173 );
174 const result = usePullRequestList(targets);
175 const connectedTargets = targets.filter((target) =>
176 environments.some(
177 (environment) =>
178 environment.environmentId === target.environmentId &&
179 environment.connectionState === "connected",
180 ),
181 );
182 const { actions, select, busyKey } = usePullRequestListActions(
183 connectedTargets.map((target) => target.environmentId),
184 result.updateEntry,
185 );
186 const paneRole = usePaneRole();
187 const sidebar = props.sidebar === true || (primaryColumn !== null && paneRole === "sidebar");
188 const selectedKey = props.selectedPullRequestKey ?? primaryColumn?.selectedPullRequestKey;
189 const connectedKey = connectedTargets.map((target) => target.environmentId).join("\n");
190 const entries = useMemo(
191 () =>
192 filterPullRequestList(
193 result.entries,
194 controls,
195 result.data?.viewers ?? {},
196 query,
197 result.data.localSearchHosts,
198 new Set(connectedKey.split("\n")),
199 ),
200 [result.entries, controls, query, result.data, connectedKey],
201 );
202 const facets = pullRequestListFacets(result.entries);
203 const [knownFacets, setKnownFacets] = useState({ environmentId, source: facets, ...facets });
204 if (knownFacets.environmentId !== environmentId || knownFacets.source !== facets) {
205 setKnownFacets((previous) => ({
206 source: facets,
207 environmentId,
208 authors: distinctIgnoringCase([
209 ...(previous.environmentId === environmentId ? previous.authors : []),
210 ...facets.authors,
211 ]).sort(),
212 labels: distinctIgnoringCase([
213 ...(previous.environmentId === environmentId ? previous.labels : []),
214 ...facets.labels,
215 ]).sort(),
216 labelColors: {
217 ...facets.labelColors,
218 ...(previous.environmentId === environmentId ? previous.labelColors : {}),
219 },
220 }));
221 }
222 const labelColors =
223 knownFacets.environmentId === environmentId ? knownFacets.labelColors : facets.labelColors;
224 const projects = pullRequestProjectChoices(allProjects, {
225 environmentId,
226 controls,
227 environmentLabels: new Map(
228 environments.map((item) => [item.environmentId, item.environmentLabel]),
229 ),
230 servesPullRequests: (id) => configs.get(id)?.environment.capabilities.pullRequests === true,
231 });
232 const filters = usePullRequestListFilters({
233 environments: environments.map((item) => ({
234 id: String(item.environmentId),
235 label: item.environmentLabel,
236 })),
237 environmentId,
238 onEnvironmentChange: listControls.setEnvironmentId,
239 value: {
240 ...controls,
241 filters: pullRequestMenuFilters(parsePullRequestQuery(typedQuery).filters, controls.filters),
242 },
243 onChange: (next) => {
244 const update = applyPullRequestFilterChange(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: -contentTopInset,
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" ? NativeScrollView : undefined}
305 contentInsetAdjustmentBehavior="never"
306 contentInset={Platform.OS === "ios" ? { top: contentTopInset } : undefined}
307 // A plain offset: LegendList adds the list header to an index-based restore, which
308 // landed every return one header lower.
309 initialScrollOffset={
310 initialScrollOffset > 0 ? initialScrollOffset - contentTopInset : undefined
311 }
312 contentContainerStyle={{
313 paddingBottom: Math.max(bottomSafeArea, workspace.bottomClearance),
314 }}
315 onScroll={(event) => {
316 workspace.recordScrollOffset(
317 "pullRequests",
318 Math.max(0, event.nativeEvent.contentOffset.y + contentTopInset),
319 );
320 }}
321 keyboardDismissMode="on-drag"
322 keyboardShouldPersistTaps="handled"
323 renderItem={renderPullRequest}
324 // Lifted above the rows so an iOS filter menu's dismissal morph is not covered.
325 ListHeaderComponentStyle={{ zIndex: 1 }}
326 ListHeaderComponent={
327 <>
328 <PullRequestListFilters
329 sidebar={sidebar}
330 savedViewsMenu={
331 <SavedViewsMenu
332 read={(preferences) => preferences.pullRequestSavedViews}
333 write={(pullRequestSavedViews) => ({ pullRequestSavedViews })}
334 list="pullRequest"
335 suggestedName={
336 controls.involvement === "reviewing" ? gt`PRs Requesting My Review` : ""
337 }
338 matches={pullRequestViewMatches}
339 scope={{
340 environmentId,
341 controls,
342 query: tab.searchMode === "resting" ? "" : tab.query,
343 }}
344 onApply={async (view) => {
345 await listControls.applyView(view);
346 workspace.dispatch(
347 view.query.trim()
348 ? { type: "search", tab: "pullRequests" }
349 : { type: "cancel", tab: "pullRequests", scrollToTop: true },
350 );
351 workspace.dispatch({
352 type: "query",
353 tab: "pullRequests",
354 query: view.query.trim(),
355 });
356 void listRef.current?.scrollToOffset({
357 offset: Platform.OS === "ios" ? -insets.top : 0,
358 animated: false,
359 });
360 }}
361 />
362 }
363 filters={filters}
364 />
365 {result.data?.errors.length ? (
366 <View key={JSON.stringify(targets)}>
367 {result.data.errors.map((error) => (
368 <PullRequestListError
369 key={`${error.environmentId} ${error.projectTitle} ${error.message}`}
370 message={`${error.projectTitle || environments.find((environment) => environment.environmentId === error.environmentId)?.environmentLabel || gt({ context: "fallback name for a server" })`Environment`}: ${error.message}`}
371 />
372 ))}
373 </View>
374 ) : null}
375 </>
376 }
377 ListFooterComponent={
378 result.loadingMore ? (
379 <View className="items-center py-5">
380 <AppActivityIndicator
381 colorClassName="accent-icon"
382 accessibilityLabel={gt`Loading more pull requests`}
383 />
384 </View>
385 ) : result.loadMoreError ? (
386 <View className="items-center gap-2 px-8 py-4">
387 <Text className="text-xs text-foreground-muted">{result.loadMoreError}</Text>
388 <Button
389 label={gt`Try again`}
390 accessibilityLabel={gt`Retry loading more pull requests`}
391 onPress={() => void result.loadMore(true)}
392 />
393 </View>
394 ) : result.hasMore ? (
395 // A filtered page can be too short to scroll, which leaves nothing to reach the end of.
396 <View className="items-center py-4">
397 <Button
398 label={gt`Load more`}
399 accessibilityLabel={gt`Load more pull requests`}
400 onPress={() => void result.loadMore()}
401 />
402 </View>
403 ) : undefined
404 }
405 ListEmptyComponent={
406 result.isPending && connectedTargets.length > 0 ? (
407 <View className="items-center py-12">
408 <AppActivityIndicator colorClassName="accent-icon" />
409 </View>
410 ) : (
411 <View className="px-8 py-12">
412 <EmptyState
413 title={
414 result.error
415 ? gt`Couldn't load pull requests`
416 : targets.length && connectedTargets.length === 0
417 ? gt`Environment offline`
418 : targets.length
419 ? query
420 ? gt`No results`
421 : gt`No matching pull requests`
422 : gt`Connect an environment`
423 }
424 detail={
425 result.error ??
426 (targets.length && connectedTargets.length === 0
427 ? gt`Reconnect to load pull requests that aren't saved on this device.`
428 : targets.length
429 ? gt`Pull requests from the selected environments' projects appear here.`
430 : gt`Add an environment in Settings to browse its pull requests.`)
431 }
432 variant="plain"
433 />
434 </View>
435 )
436 }
437 />
438 </View>
439 );
440 return props.renderFrame ? props.renderFrame(filters.headerMenu, list) : list;