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