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

IssuesScreen.tsx

549 lines22.3 KB

1import { useAtom, useAtomValue } from "@effect/atom-react";
2import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
3import {
4 applyIssueContinuations,
5 groupIssues,
6 holdIssuePages,
7 issueFilterScopes,
8 issueOrder,
9 createIssuePageRereader,
10 type EnvironmentIssueEntry,
11 type HeldIssuePage,
12} from "@t3tools/client-runtime/issue-list";
13import { issueTrackerDetailText } from "@t3tools/client-runtime/state/issue-trackers";
14import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
15import type {
16 EnvironmentId,
17 IssueInvolvement,
18 IssueListCursors,
19 IssueListInput,
20 IssueListSort,
21 IssueListState,
22} from "@t3tools/contracts";
23import { AsyncResult, Atom } from "effect/reactivity";
24import { msg, useGT, useMessages, type Msg } from "gt-react-native";
25import { use, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
26import { Keyboard, Platform, ScrollView, View } from "react-native";
27import { useSafeAreaInsets } from "react-native-safe-area-context";
28​
29import { useNavigation } from "@react-navigation/native";
30import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
31import { AppText as Text } from "../../components/ui/AppText";
32import { Button } from "../../components/ui/Button";
33import { Chip } from "../../components/ui/Chip";
34import { EmptyState } from "../../components/ui/EmptyState";
35import { usePaneRole } from "../../components/ui/Pane";
36import { RefreshControl } from "../../components/ui/RefreshControl";
37import { useContentTopInset } from "../../components/ui/useBarInset";
38import { m, type MessageResolver } from "../../i18n/messages";
39import { NativeScrollView } from "../../native/NativeScrollViewMarker";
40import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
41import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
42import { useProjects } from "../../state/entities";
43import { issueEnvironment, useIssueList } from "../../state/issues";
44import { useDebouncedValue } from "../../state/queries";
45import { environmentPresentations } from "../../state/presentation";
46import { useAtomCommand } from "../../state/use-atom-command";
47import { useWorkspaceState } from "../../state/workspace";
48import { ListFilterMenu } from "../layout/workspace/ListFilterMenu";
49import { useSearchScrollRestoration } from "../layout/workspace/useSearchScrollRestoration";
50import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
51import {
52 useWorkspaceTabControls,
53 useWorkspaceTabsSelector,
54} from "../layout/workspace/WorkspaceTabsContext";
55import { isSelectedIssueRow, issueParamsKey } from "./issueParams";
56import { IssueListRow } from "./IssueListRow";
57import type { PullRequestFilterMenu } from "../pull-requests/PullRequestListFilters";
58import { issueListFiltersAtom, issueSearchQuery } from "./issueListFilters";
59import { issueViewMatches } from "./issueSavedViews";
60import { SavedViewsMenu } from "../layout/workspace/SavedViewsMenu";
61import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
62​
63const DEFAULT_ISSUE_LIST_INPUT = { state: "open", involvement: "all", limit: 50 } as const;
64const STATES = {
65 open: msg({ context: "issue state" })`Open`,
66 closed: msg({ context: "issue state" })`Closed`,
67 all: msg("All states"),
68} as const satisfies Record<IssueListState, string | Msg>;
69const INVOLVEMENT = {
70 all: msg({ context: "issue filter" })`Everyone`,
71 assigned: msg("Assigned to you"),
72 authored: msg("Opened by you"),
73 mentioned: msg("Mentioning you"),
74} as const satisfies Record<IssueInvolvement, string | Msg>;
75const SORTS = {
76 updated: msg("Recently updated"),
77 created: msg({ context: "sort order" })`Newest`,
78} as const satisfies Record<IssueListSort, string | Msg>;
79// A 12dp inset keeps 16dp chips concentric with Android's 28dp ScreenContent corner.
80const FILTER_ROW_STYLE =
81 Platform.OS === "android"
82 ? { paddingHorizontal: 12, paddingTop: 12, paddingBottom: 8, gap: 8 }
83 : { paddingHorizontal: 16, paddingTop: 2, paddingBottom: 10, gap: 8 };
84​
85function choices<Value extends string>(
86 options: Readonly<Record<Value, string | Msg>>,
87 selected: Value,
88 resolve: MessageResolver,
89 /** Prefixes the ids, for a menu that holds more than one set of choices. */
90 field?: string,
91) {
92 return (Object.entries(options) as Array<[Value, string | Msg]>).map(([id, title]) => ({
93 id: field ? `${field}:${id}` : id,
94 title: resolve(title),
95 state: id === selected ? ("on" as const) : ("off" as const),
96 }));
98​
99const rowKey = (item: EnvironmentIssueEntry) =>
100 issueParamsKey({
101 environmentId: item.environmentId,
102 projectId: item.projectId,
103 host: item.host,
104 scope: item.scope,
105 issueKey: item.key,
106 });
107​
108export function IssuesScreen(
109 props: {
110 readonly sidebar?: boolean;
111 readonly selectedIssueKey?: string | null;
112 /** Places the list under a header of the caller's (the Android toolbar). */
113 readonly renderFrame?: (filters: PullRequestFilterMenu | null, list: ReactNode) => ReactNode;
114 } = {},
115) {
116 const gt = useGT();
117 const messages = useMessages();
118 const primaryColumn = use(NativePrimaryColumnContext);
119 const workspace = useWorkspaceTabControls()!;
120 const tab = useWorkspaceTabsSelector((state) => state.tabs.issues)!;
121 const { environments } = useWorkspaceState();
122 // Without providers, so a provider status check does not re-render the list.
123 const configs = useAtomValue(environmentPresentations.serverConfigsAtom);
124 const projects = useProjects();
125 const insets = useSafeAreaInsets();
126 const contentTopInset = useContentTopInset();
127 // UIKit insets the list by its column's safe area, which this context can report as 0.
128 const columnSafeBottom = useNativeColumnLayoutMetrics()?.safeArea.bottom;
129 const bottomSafeArea =
130 Platform.OS === "ios" ? (columnSafeBottom ?? insets.bottom) : insets.bottom;
131 const listRef = useRef<LegendListRef>(null);
132 const [initialScrollOffset] = useState(() => workspace.getScrollOffset("issues"));
133 useSearchScrollRestoration(tab.searchMode, () => {
134 void listRef.current?.scrollToOffset({
135 offset: tab.scrollOffset - contentTopInset,
136 animated: false,
137 });
138 });
139 const debouncedQuery = useDebouncedValue(issueSearchQuery(tab.query), 300);
140 const query = tab.searchMode === "resting" ? "" : debouncedQuery;
141 const [state, setState] = useState<IssueListState>("open");
142 const [involvement, setInvolvement] = useState<IssueInvolvement>("all");
143 const navigation = useNavigation();
144 const [{ labels, assignee }, setFilters] = useAtom(issueListFiltersAtom);
145 const { themeAppearance } = useAppearancePreferences();
146 const [sort, setSort] = useState<IssueListSort>("updated");
147 const listInput: IssueListInput = {
148 ...DEFAULT_ISSUE_LIST_INPUT,
149 state,
150 involvement,
151 ...(query ? { query } : {}),
152 ...(labels.length > 0 ? { labels } : {}),
153 ...(assignee === null ? {} : { assignee: assignee.login }),
154 ...(sort === "updated" ? {} : { sort }),
155 };
156 const capable = environments.filter(
157 (environment) =>
158 configs.get(environment.environmentId)?.environment.capabilities.issues === true,
159 );
160 const connected = capable.filter((environment) => environment.connectionState === "connected");
161 const targets = connected
162 .map((environment) => ({ environmentId: environment.environmentId, input: listInput }))
163 .sort((left, right) => left.environmentId.localeCompare(right.environmentId));
164 const list = useIssueList(targets);
165​
166 const [pagesAtom] = useState(() =>
167 Atom.make<ReadonlyMap<EnvironmentId, HeldIssuePage>>(new Map()),
168 );
169 const [pages, setPages] = useAtom(pagesAtom);
170 const listKey = JSON.stringify(targets);
171 const held = holdIssuePages(list.answers, pages, listKey);
172 const activeListKey = useRef<string | null>(null);
173 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Tracks which listing is mounted when a continuation settles.
174 useLayoutEffect(() => {
175 activeListKey.current = listKey;
176 return () => {
177 activeListKey.current = null;
178 };
179 }, [listKey]);
180 const loadPage = useAtomCommand(issueEnvironment.listPage, { reportFailure: false });
181 const readPage = async (environmentId: EnvironmentId, cursors: IssueListCursors) => {
182 const result = await loadPage({ environmentId, input: { ...listInput, cursors } });
183 if (!AsyncResult.isFailure(result)) return result.value;
184 const failure = squashAtomCommandFailure(result);
185 return {
186 failure: failure instanceof Error ? failure.message : m(msg("The next page failed.")),
187 };
188 };
189 const [rereadPages] = useState(createIssuePageRereader);
190 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- A refreshed first page reads the pages "Load more" had reached again from the server, so they show what changed.
191 useEffect(() => {
192 rereadPages(held, readPage, (environmentId, next) =>
193 setPages((current) => new Map(current).set(environmentId, next)),
194 );
195 });
196 const [loadingMore, setLoadingMore] = useState(false);
197 const loading = useRef(false);
198 const continuable = [...held].filter(
199 ([, page]) => page.rereading === null && Object.keys(page.nextCursors).length > 0,
200 );
201 const moreFailure = [...held.values()].find((page) => page.moreFailure)?.moreFailure ?? null;
202 const needsRetry = continuable.some(([, page]) => page.moreFailed);
203 const loadMore = async (retry = false) => {
204 // With nothing to continue, the spinner and new pages would only re-fire onEndReached forever.
205 if (loading.current || continuable.length === 0 || (needsRetry && !retry)) return;
206 loading.current = true;
207 setLoadingMore(true);
208 const loaded = await Promise.all(
209 continuable.map(async ([environmentId, page]) => ({
210 environmentId,
211 page,
212 result: await readPage(environmentId, page.nextCursors),
213 })),
214 );
215 loading.current = false;
216 setLoadingMore(false);
217 if (activeListKey.current !== listKey) return;
218 setPages((current) => applyIssueContinuations(current, list.readAnswers(), listKey, loaded));
219 };
220​
221 const groups = groupIssues(held, query, projects, sort);
222 const entries = groups.flatMap((group) => group.rows).sort(issueOrder(sort));
223 const filterScopes = issueFilterScopes(held, projects);
224 const notices = [
225 // An environment that failed while another answered: its issues are missing from the rows.
226 ...(entries.length > 0 && list.error ? [list.error] : []),
227 ...groups.flatMap((group) => [
228 ...(group.tracker.configured
229 ? []
230 : [
231 `${group.tracker.host}: ${group.tracker.detail === null ? gt`This tracker cannot be read.` : issueTrackerDetailText(group.tracker.detail, messages)}`,
232 ]),
233 ...group.errors.map((error) => `${error.projectTitle}: ${error.message}`),
234 ]),
235 ];
236​
237 const paneRole = usePaneRole();
238 const sidebar = props.sidebar === true || (primaryColumn !== null && paneRole === "sidebar");
239 const selectedKey = props.selectedIssueKey ?? primaryColumn?.selectedIssueKey;
240 const selectDetail = useSelectWorkspaceDetail();
241 const selectIssue = (item: EnvironmentIssueEntry) => {
242 Keyboard.dismiss();
243 selectDetail({
244 name: "Issue",
245 params: {
246 environmentId: String(item.environmentId),
247 projectId: String(item.projectId),
248 tracker: item.tracker,
249 host: item.host,
250 scope: item.scope,
251 issueKey: item.key,
252 initialSummary: item,
253 },
254 });
255 };
256 const scrollToTop = () =>
257 void listRef.current?.scrollToOffset({ offset: -contentTopInset, animated: false });
258​
259 const customized =
260 state !== "open" ||
261 involvement !== "all" ||
262 sort !== "updated" ||
263 labels.length > 0 ||
264 assignee !== null;
265 // The Android header's filter button opens every filter, as the pull request list's does.
266 const headerMenu: PullRequestFilterMenu | null =
267 Platform.OS === "android"
268 ? {
269 actions: [
270 {
271 id: "state",
272 title: gt({ context: "issue state filter" })`State`,
273 subactions: choices(STATES, state, messages, "state"),
274 },
275 {
276 id: "involvement",
277 title: gt`Involvement`,
278 subactions: choices(INVOLVEMENT, involvement, messages, "involvement"),
279 },
280 {
281 id: "labels",
282 title: labels.length === 0 ? gt`Labels…` : gt`Labels (${{ count: labels.length }})…`,
283 },
284 {
285 id: "assignee",
286 title:
287 assignee === null
288 ? gt`Assignee…`
289 : gt`Assignee: ${{ name: assignee.name ?? assignee.login }}…`,
290 },
291 {
292 id: "sort",
293 title: gt({ context: "noun, sort order menu" })`Sort`,
294 subactions: choices(SORTS, sort, messages, "sort"),
295 },
296 {
297 id: "reset",
298 title: gt`Reset filters`,
299 attributes: { disabled: !customized },
300 },
301 ],
302 onSelect: (id) => {
303 const [field, value] = id.split(":");
304 if (field === "state") setState(value as IssueListState);
305 if (field === "involvement") setInvolvement(value as IssueInvolvement);
306 if (field === "sort") setSort(value as IssueListSort);
307 if (field === "labels" || field === "assignee")
308 navigation.navigate("IssueFilterSearch", { kind: field, scopes: filterScopes });
309 if (field === "reset") {
310 setState("open");
311 setInvolvement("all");
312 setSort("updated");
313 setFilters({ labels: [], assignee: null });
314 }
315 },
316 customized,
317 }
318 : null;
319​
320 const content = (
321 <View className={sidebar ? "flex-1 bg-drawer" : "flex-1 bg-screen"}>
322 <LegendList
323 ref={listRef}
324 data={entries}
325 extraData={selectedKey}
326 keyExtractor={rowKey}
327 estimatedItemSize={84}
328 drawDistance={1_000}
329 onEndReached={() => void loadMore()}
330 onEndReachedThreshold={0.5}
331 refreshControl={
332 <RefreshControl
333 refreshing={list.isPending && list.answers.length > 0}
334 onRefresh={list.refresh}
335 // The list already accounts for the navigation header in its content inset.
336 progressViewOffset={Platform.OS === "ios" ? 60 : undefined}
337 />
338 }
339 alwaysBounceVertical
340 showsVerticalScrollIndicator={Platform.OS !== "android"}
341 recycleItems
342 renderScrollComponent={Platform.OS === "ios" ? NativeScrollView : undefined}
343 contentInsetAdjustmentBehavior="never"
344 contentInset={Platform.OS === "ios" ? { top: contentTopInset } : undefined}
345 initialScrollOffset={
346 initialScrollOffset > 0 ? initialScrollOffset - contentTopInset : undefined
347 }
348 contentContainerStyle={{
349 paddingBottom: Math.max(bottomSafeArea, workspace.bottomClearance),
350 }}
351 onScroll={(event) => {
352 workspace.recordScrollOffset(
353 "issues",
354 Math.max(0, event.nativeEvent.contentOffset.y + contentTopInset),
355 );
356 }}
357 keyboardDismissMode="on-drag"
358 keyboardShouldPersistTaps="handled"
359 renderItem={({ item }) => (
360 <IssueListRow
361 item={item}
362 onSelect={selectIssue}
363 selected={isSelectedIssueRow(selectedKey, item)}
364 sidebar={sidebar}
365 />
366 )}
367 // Lifted above the rows so an iOS filter menu's dismissal morph is not covered.
368 ListHeaderComponentStyle={{ zIndex: 1 }}
369 ListHeaderComponent={
370 <>
371 <ScrollView
372 horizontal
373 showsHorizontalScrollIndicator={false}
374 style={{ overflow: "visible" }}
375 contentContainerStyle={
376 sidebar && Platform.OS === "android"
377 ? { ...FILTER_ROW_STYLE, paddingHorizontal: 20 }
378 : FILTER_ROW_STYLE
379 }
380 >
381 <SavedViewsMenu
382 read={(preferences) => preferences.issueSavedViews}
383 write={(issueSavedViews) => ({ issueSavedViews })}
384 list="issue"
385 suggestedName={involvement === "assigned" ? gt`Issues Assigned to Me` : ""}
386 matches={issueViewMatches}
387 scope={{
388 query: tab.searchMode === "resting" ? "" : tab.query,
389 state,
390 involvement,
391 sort,
392 labels,
393 assignee,
394 }}
395 onApply={(view) => {
396 setState(view.state);
397 setInvolvement(view.involvement);
398 setSort(view.sort);
399 setFilters({ labels: view.labels, assignee: view.assignee });
400 const viewQuery = view.query.trim();
401 workspace.dispatch(
402 viewQuery
403 ? { type: "search", tab: "issues" }
404 : { type: "cancel", tab: "issues", scrollToTop: true },
405 );
406 workspace.dispatch({ type: "query", tab: "issues", query: viewQuery });
407 scrollToTop();
408 }}
409 />
410 <ListFilterMenu
411 label={messages(STATES[state])}
412 active={state !== "open"}
413 accessibilityLabel={gt`Filter by state`}
414 actions={choices(STATES, state, messages)}
415 onSelect={(id) => {
416 setState(id as IssueListState);
417 scrollToTop();
418 }}
419 />
420 <ListFilterMenu
421 label={messages(INVOLVEMENT[involvement])}
422 active={involvement !== "all"}
423 accessibilityLabel={gt`Filter by involvement`}
424 actions={choices(INVOLVEMENT, involvement, messages)}
425 onSelect={(id) => {
426 setInvolvement(id as IssueInvolvement);
427 scrollToTop();
428 }}
429 />
430 <Chip
431 label={
432 labels.length === 0
433 ? gt`Labels`
434 : labels.length === 1
435 ? labels[0]!
436 : gt`Labels ${{ count: labels.length }}`
437 }
438 selected={labels.length > 0}
439 trailingIcon="chevron.down"
440 glass
441 colorScheme={themeAppearance}
442 accessibilityLabel={gt`Filter by label`}
443 onPress={() =>
444 navigation.navigate("IssueFilterSearch", { kind: "labels", scopes: filterScopes })
445 }
446 />
447 <Chip
448 label={assignee === null ? gt`Assignee` : (assignee.name ?? assignee.login)}
449 selected={assignee !== null}
450 trailingIcon="chevron.down"
451 glass
452 colorScheme={themeAppearance}
453 accessibilityLabel={gt`Filter by assignee`}
454 onPress={() =>
455 navigation.navigate("IssueFilterSearch", {
456 kind: "assignee",
457 scopes: filterScopes,
458 })
459 }
460 />
461 <ListFilterMenu
462 label={messages(SORTS[sort])}
463 active={sort !== "updated"}
464 accessibilityLabel={gt`Sort issues`}
465 actions={choices(SORTS, sort, messages)}
466 onSelect={(id) => {
467 setSort(id as IssueListSort);
468 scrollToTop();
469 }}
470 />
471 </ScrollView>
472 {notices.map((notice) => (
473 <Text key={notice} selectable className="px-4 py-1.5 text-sm text-foreground-muted">
474 {notice}
475 </Text>
476 ))}
477 </>
478 }
479 ListFooterComponent={
480 loadingMore ? (
481 <View className="items-center py-5">
482 <AppActivityIndicator
483 colorClassName="accent-icon"
484 accessibilityLabel={gt`Loading more issues`}
485 />
486 </View>
487 ) : needsRetry ? (
488 <View className="items-center gap-2 px-8 py-4">
489 {moreFailure ? (
490 <Text className="text-xs text-foreground-muted">{moreFailure}</Text>
491 ) : null}
492 <Button
493 label={gt`Try again`}
494 accessibilityLabel={gt`Retry loading more issues`}
495 onPress={() => void loadMore(true)}
496 />
497 </View>
498 ) : continuable.length > 0 ? (
499 // A filtered page can be too short to scroll, which leaves nothing to reach the end of.
500 <View className="items-center py-4">
501 <Button
502 label={gt`Load more`}
503 accessibilityLabel={gt`Load more issues`}
504 onPress={() => void loadMore()}
505 />
506 </View>
507 ) : undefined
508 }
509 ListEmptyComponent={
510 list.isPending && list.answers.length === 0 ? (
511 <View className="items-center py-12">
512 <AppActivityIndicator colorClassName="accent-icon" />
513 </View>
514 ) : (
515 <View className="px-8 py-12">
516 <EmptyState
517 title={
518 list.error
519 ? gt`Couldn't load issues`
520 : connected.length > 0
521 ? query
522 ? gt`No results`
523 : gt`No matching issues`
524 : capable.length > 0
525 ? gt`Environment offline`
526 : environments.length > 0
527 ? gt`Issues unavailable`
528 : gt`Connect an environment`
529 }
530 detail={
531 list.error ??
532 (connected.length > 0
533 ? gt`Issues from your environments' projects appear here.`
534 : capable.length > 0
535 ? gt`Reconnect to load issues.`
536 : environments.length > 0
537 ? gt`Update the environment's T3 Code server to browse issues.`
538 : gt`Add an environment in Settings to browse its issues.`)
539 }
540 variant="plain"
541 />
542 </View>
543 )
544 }
545 />
546 </View>
547 );
548 return props.renderFrame ? props.renderFrame(headerMenu, content) : content;