@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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