@devries-cameron20 / t3code Mirror · read-only / commits / 68339a0846
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 22, 15:45 UTC

refactor(mobile): pull request list, filters and viewed files without synchronizing effects (#25614)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 26, 2026 at 17:56 UTC 68339a084644540f176ce83d97dd4c768b65b52e
12 files changed +350 -280
apps/mobile/src/features/pull-requests/PullRequestFilterMenuContext.tsx deleted
-50
@@ -1,50 +0,0 @@
1 -import type { MenuAction } from "@react-native-menu/menu";
2 -import {
3 - createContext,
4 - use,
5 - useLayoutEffect,
6 - useState,
7 - type Dispatch,
8 - type ReactNode,
9 - type SetStateAction,
10 -} from "react";
11 -
12 -export interface PullRequestFilterMenu {
13 - readonly actions: readonly MenuAction[];
14 - readonly onSelect: (id: string) => void;
15 - /** Whether any filter, the environment, or a non-default sort is active. */
16 - readonly customized: boolean;
17 -}
18 -
19 -const MenuContext = createContext<PullRequestFilterMenu | null>(null);
20 -const PublishContext = createContext<Dispatch<SetStateAction<PullRequestFilterMenu | null>> | null>(
21 - null,
22 -);
23 -
24 -/**
25 - * The Android PR header opens the full filter menu, but the facets (authors, labels) and the
26 - * controls live in the list below it. The list publishes its menu here; only the header reads
27 - * it, so the list's own renders don't fan out.
28 - */
29 -export function PullRequestFilterMenuProvider(props: { readonly children: ReactNode }) {
30 - const [menu, setMenu] = useState<PullRequestFilterMenu | null>(null);
31 - return (
32 - <PublishContext value={setMenu}>
33 - <MenuContext value={menu}>{props.children}</MenuContext>
34 - </PublishContext>
35 - );
36 -}
37 -
38 -export function usePullRequestFilterMenu() {
39 - return use(MenuContext);
40 -}
41 -
42 -export function usePublishPullRequestFilterMenu(menu: PullRequestFilterMenu | null) {
43 - const publish = use(PublishContext);
44 - // A layout effect, so the header's filter button lands in the same frame as the list. There is
45 - // no cleanup: the list lives exactly as long as this provider, and a hidden tab runs its
46 - // cleanups, which would drop the button for a few frames every time the tab came back.
47 - useLayoutEffect(() => {
48 - if (publish && menu) publish(menu);
49 - }, [publish, menu]);
50 -}
apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx
+93 -39
@@ -1,10 +1,13 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 import { sortProjectsByGroupOrder } from "@t3tools/client-runtime/state/project-grouping";
3 +import type { ScopedProjectRef, SidebarProjectGroupingMode } from "@t3tools/contracts";
4 +import { Atom } from "effect/reactivity";
5 import { useMemo } from "react";
6 import { Platform, ScrollView } from "react-native";
7 import type { MenuProps } from "../../components/ui/Menu.types";
8 import { ListFilterMenu } from "../workspace/ListFilterMenu";
6 -import { usePublishPullRequestFilterMenu } from "./PullRequestFilterMenuContext";
7 -import { useProjects, useThreadShells } from "../../state/entities";
9 +import { environmentProjects } from "../../state/projects";
10 +import { environmentThreadShells } from "../../state/threads";
11 import { useMobileProjectGroupingSettings } from "../../state/project-grouping";
12 import { buildHomeProjectScopes, sortHomeProjectScopes } from "../home/homeThreadList";
13 import { DEFAULT_PR_LIST_CONTROLS, type PullRequestListControls } from "./pullRequestList";
@@ -39,32 +42,58 @@ function choices(field: string, options: Readonly<Record<string, string>>, selec
42 }));
43 }
44
45 +type ProjectOrder = readonly { readonly memberProjectRefs: readonly ScopedProjectRef[] }[];
46 +const sameProjectOrder = (previous: ProjectOrder, next: ProjectOrder) =>
47 + previous.length === next.length &&
48 + previous.every((group, index) => {
49 + const members = next[index]!.memberProjectRefs;
50 + return (
51 + group.memberProjectRefs.length === members.length &&
52 + group.memberProjectRefs.every(
53 + (ref, member) =>
54 + ref.environmentId === members[member]!.environmentId &&
55 + ref.projectId === members[member]!.projectId,
56 + )
57 + );
58 + });
59 +
60 +// Thread shells change on every agent tick, but the sidebar order they decide rarely does. The
61 +// equality check keeps the list screen, which builds these filters, from re-rendering on each tick.
62 +const sidebarProjectOrderFamily = Atom.family((mode: SidebarProjectGroupingMode) =>
63 + Atom.make((get) =>
64 + sortHomeProjectScopes({
65 + scopes: buildHomeProjectScopes({
66 + projects: get(environmentProjects.projectsAtom),
67 + environmentId: null,
68 + projectGroupingMode: mode,
69 + }),
70 + threads: get(environmentThreadShells.threadShellsAtom),
71 + pendingTasks: [],
72 + projectSortOrder: "updated_at",
73 + }).map((scope) => ({ memberProjectRefs: scope.projectRefs })),
74 + ).pipe(Atom.withEquality(sameProjectOrder)),
75 +);
76 +
77 function useProjectsInSidebarOrder<Project extends { id: string; environmentId: string }>(
78 projects: readonly Project[],
79 ) {
45 - const allProjects = useProjects();
46 - const threads = useThreadShells();
80 const { sidebarProjectGroupingMode } = useMobileProjectGroupingSettings();
48 - const scopes = useMemo(
49 - () =>
50 - sortHomeProjectScopes({
51 - scopes: buildHomeProjectScopes({
52 - projects: allProjects,
53 - environmentId: null,
54 - projectGroupingMode: sidebarProjectGroupingMode,
55 - }),
56 - threads,
57 - pendingTasks: [],
58 - projectSortOrder: "updated_at",
59 - }).map((scope) => ({ memberProjectRefs: scope.projectRefs })),
60 - [allProjects, sidebarProjectGroupingMode, threads],
61 - );
81 + const scopes = useAtomValue(sidebarProjectOrderFamily(sidebarProjectGroupingMode));
82 return useMemo(() => sortProjectsByGroupOrder(projects, scopes), [projects, scopes]);
83 }
84
65 -export function PullRequestListFilters(props: {
66 - /** Android sidebar rows sit further in than full-width rows; the pills follow them. */
67 - readonly sidebar?: boolean;
85 +export interface PullRequestFilterMenu {
86 + readonly actions: MenuProps["actions"];
87 + readonly onSelect: (id: string) => void;
88 + /** Whether any filter, the environment, or a non-default sort is active. */
89 + readonly customized: boolean;
90 +}
91 +
92 +/**
93 + * Builds the filter pills and, on Android, the header's full filter menu. The list screen owns
94 + * the call so both the pills and the header it frames read the same menu.
95 + */
96 +export function usePullRequestListFilters(props: {
97 readonly environments: readonly { id: string; label: string }[];
98 readonly environmentId: string | null;
99 readonly onEnvironmentChange: (id: string | null) => void;
@@ -280,7 +309,7 @@ export function PullRequestListFilters(props: {
309 ];
310 const customized = count > 0 || value.sort !== "updated" || props.environmentId !== null;
311 // The Android header's filter button opens every filter.
283 - const headerMenu =
312 + const headerMenu: PullRequestFilterMenu | null =
313 Platform.OS === "android"
314 ? {
315 actions: [
@@ -296,7 +325,35 @@ export function PullRequestListFilters(props: {
325 customized,
326 }
327 : null;
299 - usePublishPullRequestFilterMenu(headerMenu);
328 + return {
329 + headerMenu,
330 + select,
331 + count,
332 + more,
333 + reset,
334 + environmentLabel:
335 + props.environments.length > 1
336 + ? (props.environments.find((environment) => environment.id === props.environmentId)
337 + ?.label ?? "All environments")
338 + : null,
339 + environmentActions,
340 + state: value.state,
341 + stateActions,
342 + involvement: value.involvement,
343 + involvementActions,
344 + selectedLabelCount: selectedLabels.length,
345 + labelActions,
346 + author,
347 + authorActions,
348 + };
349 +}
350 +
351 +export function PullRequestListFilters(props: {
352 + /** Android sidebar rows sit further in than full-width rows; the pills follow them. */
353 + readonly sidebar?: boolean;
354 + readonly filters: ReturnType<typeof usePullRequestListFilters>;
355 +}) {
356 + const { count, more, reset, select, author, selectedLabelCount } = props.filters;
357 return (
358 <ScrollView
359 horizontal
@@ -319,43 +376,40 @@ export function PullRequestListFilters(props: {
376 onSelect={select}
377 />
378 )}
322 - {props.environments.length > 1 ? (
379 + {props.filters.environmentLabel !== null ? (
380 <ListFilterMenu
324 - label={
325 - props.environments.find((environment) => environment.id === props.environmentId)
326 - ?.label ?? "All environments"
327 - }
381 + label={props.filters.environmentLabel}
382 accessibilityLabel="Choose pull request environment"
329 - actions={environmentActions}
383 + actions={props.filters.environmentActions}
384 onSelect={select}
385 />
386 ) : null}
387 <ListFilterMenu
334 - label={STATES[value.state]}
335 - active={value.state !== "open"}
388 + label={STATES[props.filters.state]}
389 + active={props.filters.state !== "open"}
390 accessibilityLabel="Filter by state"
337 - actions={stateActions}
391 + actions={props.filters.stateActions}
392 onSelect={select}
393 />
394 <ListFilterMenu
341 - label={INVOLVEMENT[value.involvement]}
342 - active={value.involvement !== "all"}
395 + label={INVOLVEMENT[props.filters.involvement]}
396 + active={props.filters.involvement !== "all"}
397 accessibilityLabel="Filter by involvement"
344 - actions={involvementActions}
398 + actions={props.filters.involvementActions}
399 onSelect={select}
400 />
401 <ListFilterMenu
348 - label={selectedLabels.length ? `Labels ${selectedLabels.length}` : "Labels"}
349 - active={selectedLabels.length > 0}
402 + label={selectedLabelCount ? `Labels ${selectedLabelCount}` : "Labels"}
403 + active={selectedLabelCount > 0}
404 accessibilityLabel="Filter by label"
351 - actions={labelActions}
405 + actions={props.filters.labelActions}
406 onSelect={select}
407 />
408 <ListFilterMenu
409 label={author === "me" ? "By you" : (author ?? "Author")}
410 active={Boolean(author)}
411 accessibilityLabel="Filter by author"
358 - actions={authorActions}
412 + actions={props.filters.authorActions}
413 onSelect={select}
414 />
415 </ScrollView>
apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx
+11 -10
@@ -7,7 +7,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native"
7 import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
8 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
9 import type { PullRequestReviewerCandidate } from "@t3tools/contracts";
10 -import { useEffect, useRef, useState } from "react";
10 +import { useRef, useState } from "react";
11 import {
12 FlatList,
13 Platform,
@@ -86,13 +86,14 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
86 (a, b) => Number(b.isRequested) - Number(a.isRequested) || a.login.localeCompare(b.login),
87 );
88 })();
89 - useEffect(() => {
90 - if (candidates.length === 0) return;
89 + // A new search shows its best matches from the top.
90 + const search = (next: string) => {
91 + setQuery(next);
92 listRef.current?.scrollToOffset({
93 offset: Platform.OS === "ios" ? -insets.top : 0,
94 animated: false,
95 });
95 - }, [candidates, insets.top]);
96 + };
97 const update = async (
98 candidate: Pick<PullRequestReviewerCandidate, "id" | "kind" | "isRequested">,
99 ) => {
@@ -118,7 +119,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
119 return;
120 }
121 if (!pr?.capabilities.reviewers.listCandidates) {
121 - setQuery("");
122 + search("");
123 detail.refresh();
124 }
125 };
@@ -126,8 +127,8 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
127 const searchOptions = {
128 placeholder: "Search reviewers",
129 autoCapitalize: "none" as const,
129 - onChangeText: (event: { nativeEvent: { text: string } }) => setQuery(event.nativeEvent.text),
130 - onCancelButtonPress: () => setQuery(""),
130 + onChangeText: (event: { nativeEvent: { text: string } }) => search(event.nativeEvent.text),
131 + onCancelButtonPress: () => search(""),
132 hideNavigationBar: false,
133 hideWhenScrolling: false,
134 obscureBackground: false,
@@ -150,7 +151,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
151 ? [
152 createNativeMailSearchToolbarItem({
153 placeholder: "Search reviewers",
153 - onSearchTextChange: setQuery,
154 + onSearchTextChange: search,
155 showsSearchDismissButton: true,
156 searchTextChangeId: "pr-reviewer-search",
157 }),
@@ -182,7 +183,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
183 placeholder="Search reviewers"
184 placeholderTextColorClassName="accent-foreground-muted"
185 value={query}
185 - onChangeText={setQuery}
186 + onChangeText={search}
187 autoCapitalize="none"
188 className="min-h-11 rounded-xl bg-grouped-card px-3 text-sm"
189 />
@@ -287,7 +288,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
288 placeholder="Reviewer login or ID"
289 placeholderTextColorClassName="accent-foreground-muted"
290 value={query}
290 - onChangeText={setQuery}
291 + onChangeText={search}
292 autoCapitalize="none"
293 autoCorrect={false}
294 className="min-h-12 rounded-xl bg-grouped-card px-3 text-base"
apps/mobile/src/features/pull-requests/PullRequestToolbar.android.tsx
+11 -9
@@ -1,4 +1,4 @@
1 -import { useNavigation, useNavigationState } from "@react-navigation/native";
1 +import { useNavigation } from "@react-navigation/native";
2 import { useCallback, useEffect, useRef } from "react";
3 import { BackHandler, Keyboard, View, type TextInputInstance } from "react-native";
4 import { AndroidHeaderIconButton } from "../../components/ui/AndroidScreenHeader";
@@ -8,17 +8,18 @@ import { useToolbarLayout } from "../../components/ui/useToolbarLayout";
8 import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
9 import { WorkspaceListToolbarRow } from "../workspace/WorkspaceListToolbarRow";
10 import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
11 -import { usePullRequestFilterMenu } from "./PullRequestFilterMenuContext";
11 +import type { PullRequestFilterMenu } from "./PullRequestListFilters";
12 import { openSettings } from "../settings/settings-navigation";
13
14 /** PR search shares the thread list's Android header row. */
15 -export function PullRequestToolbar(props: { readonly onRequestVisibility?: () => void }) {
15 +export function PullRequestToolbar(props: {
16 + readonly filters: PullRequestFilterMenu | null;
17 + readonly onRequestVisibility?: () => void;
18 +}) {
19 const navigation = useNavigation();
17 - const filters = usePullRequestFilterMenu();
20 + const { filters } = props;
21 const workspace = useWorkspaceTabs()!;
22 const { dispatch, getScrollOffset, recordScrollOffset, isTabActive } = workspace;
20 - const homeFocused = useNavigationState((state) => state.routes[state.index]?.name === "Home");
21 - const listFocused = homeFocused && workspace.state.selectedTab === "pullRequests";
23 const { onRequestVisibility } = props;
24 const tab = workspace.state.tabs.pullRequests;
25 const input = useRef<TextInputInstance>(null);
@@ -41,9 +42,10 @@ export function PullRequestToolbar(props: { readonly onRequestVisibility?: () =>
42 dispatch({ type: "cancel", tab: "pullRequests" });
43 }, [dispatch, recordScrollOffset, tab.searchEntryOffset]);
44 useEffect(() => {
44 - if (!searching || !listFocused) return;
45 + if (!searching) return;
46 const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
46 - // Frozen Home screens can keep effects alive after a detail route opens.
47 + // Frozen Home screens stay mounted under a detail route or another tab,
48 + // so back only applies while the PR list is in front.
49 const state = navigation.getState();
50 if (!state || state.routes[state.index]?.name !== "Home" || !isTabActive("pullRequests"))
51 return false;
@@ -52,7 +54,7 @@ export function PullRequestToolbar(props: { readonly onRequestVisibility?: () =>
54 return true;
55 });
56 return () => subscription.remove();
55 - }, [searching, closeSearch, listFocused, navigation, isTabActive]);
57 + }, [searching, closeSearch, navigation, isTabActive]);
58 const { paddingTop, paddingBottom } = useToolbarLayout();
59 return (
60 <View className="bg-header px-2" style={{ paddingTop, paddingBottom }}>
apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx
+65 -63
@@ -6,7 +6,7 @@ import {
6 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
7 import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
8 import { useNavigation } from "@react-navigation/native";
9 -import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";
9 +import { use, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
10 import { useAtomValue } from "@effect/atom-react";
11 import {
12 Keyboard,
@@ -26,7 +26,11 @@ import { useWorkspaceState } from "../../state/workspace";
26 import { useProjects } from "../../state/entities";
27 import { environmentServerConfigsAtom } from "../../state/server";
28 import { PullRequestListRow } from "./PullRequestListRow";
29 -import { PullRequestListFilters } from "./PullRequestListFilters";
29 +import {
30 + PullRequestListFilters,
31 + usePullRequestListFilters,
32 + type PullRequestFilterMenu,
33 +} from "./PullRequestListFilters";
34 import { PullRequestCardRow } from "./PullRequestControls";
35 import { usePullRequestList } from "./usePullRequestList";
36 import { usePullRequestListControls } from "./usePullRequestListControls";
@@ -79,6 +83,11 @@ export function PullRequestsScreen(
83 props: {
84 readonly sidebar?: boolean;
85 readonly selectedPullRequestKey?: string | null;
86 + /**
87 + * Places the list under a header that opens the full filter menu (the Android toolbar). The
88 + * filters live here, so the header gets them in the same render as the list.
89 + */
90 + readonly renderFrame?: (filters: PullRequestFilterMenu | null, list: ReactNode) => ReactNode;
91 } = {},
92 ) {
93 const navigation = useNavigation();
@@ -87,9 +96,23 @@ export function PullRequestsScreen(
96 const { environments } = useWorkspaceState();
97 const configs = useAtomValue(environmentServerConfigsAtom);
98 const insets = useSafeAreaInsets();
90 - const [initialOffset] = useState(() => workspace.getScrollOffset("pullRequests"));
99 const listRef = useRef<LegendListRef>(null);
100 const tab = workspace.state.tabs.pullRequests;
101 + const [initialScrollOffset] = useState(() => workspace.getScrollOffset("pullRequests"));
102 + // Cancelling search restores the offset recorded when search opened. The
103 + // toolbar that cancels has no handle on this list, so the list scrolls itself
104 + // once it sees the tab come back to resting.
105 + const previousSearchMode = useRef(tab.searchMode);
106 + useEffect(() => {
107 + const restoringSearch =
108 + previousSearchMode.current !== "resting" && tab.searchMode === "resting";
109 + previousSearchMode.current = tab.searchMode;
110 + if (restoringSearch)
111 + void listRef.current?.scrollToOffset({
112 + offset: tab.scrollOffset - (Platform.OS === "ios" ? insets.top : 0),
113 + animated: false,
114 + });
115 + }, [tab.searchMode, tab.scrollOffset, insets.top]);
116 const maintainVisiblePosition = useMemo(
117 () => ({
118 data: tab.searchMode === "resting",
@@ -203,6 +226,39 @@ export function PullRequestsScreen(
226 (project) =>
227 !project.isScratch && (environmentId === null || project.environmentId === environmentId),
228 );
229 + const filters = usePullRequestListFilters({
230 + environments: environments.map((item) => ({
231 + id: String(item.environmentId),
232 + label: item.environmentLabel,
233 + })),
234 + environmentId,
235 + onEnvironmentChange: listControls.setEnvironmentId,
236 + value: typedDraft
237 + ? { ...controls, filters: { ...controls.filters, draft: typedDraft } }
238 + : controls,
239 + onChange: (next) => {
240 + const update = applyPullRequestDraftFilterChange(typedQuery, controls.filters, next.filters);
241 + listControls.setControls(environmentId, { ...next, filters: update.filters });
242 + if (update.query !== typedQuery)
243 + workspace.dispatch({ type: "query", tab: "pullRequests", query: update.query });
244 + void listRef.current?.scrollToOffset({
245 + offset: Platform.OS === "ios" ? -insets.top : 0,
246 + animated: false,
247 + });
248 + },
249 + authors: knownFacets.environmentId === environmentId ? knownFacets.authors : facets.authors,
250 + labels: knownFacets.environmentId === environmentId ? knownFacets.labels : facets.labels,
251 + labelColors,
252 + projects,
253 + onSearch: (kind) =>
254 + navigation.navigate("PullRequestFilterSearch", {
255 + kind,
256 + environmentId,
257 + environmentIds: targets.map((target) => String(target.environmentId)),
258 + suggestions: knownFacets.environmentId === environmentId ? knownFacets[kind] : facets[kind],
259 + labelColors,
260 + }),
261 + });
262 const renderPullRequest = useCallback(
263 ({ item }: { readonly item: EnvironmentPullRequestListEntry }) => (
264 <PullRequestListRow
@@ -217,19 +273,7 @@ export function PullRequestsScreen(
273 ),
274 [selectPullRequest, selectedKey, actions, select, busyKey, sidebar],
275 );
220 - const previousSearchMode = useRef(tab.searchMode);
221 - useEffect(() => {
222 - const restoringSearch =
223 - previousSearchMode.current !== "resting" && tab.searchMode === "resting";
224 - previousSearchMode.current = tab.searchMode;
225 - if (restoringSearch)
226 - void listRef.current?.scrollToOffset({
227 - offset: tab.scrollOffset - (Platform.OS === "ios" ? insets.top : 0),
228 - animated: false,
229 - });
230 - }, [tab.searchMode, tab.scrollOffset, insets.top]);
231 -
232 - return (
276 + const list = (
277 <View className={sidebar ? "flex-1 bg-drawer" : "flex-1 bg-screen"}>
278 <LegendList
279 ref={listRef}
@@ -263,7 +307,9 @@ export function PullRequestsScreen(
307 // A plain offset: LegendList adds the list header to an index-based restore, which
308 // landed every return one header lower.
309 initialScrollOffset={
266 - initialOffset > 0 ? initialOffset - (Platform.OS === "ios" ? insets.top : 0) : undefined
310 + initialScrollOffset > 0
311 + ? initialScrollOffset - (Platform.OS === "ios" ? insets.top : 0)
312 + : undefined
313 }
314 contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0}
315 contentContainerStyle={{
@@ -285,52 +331,7 @@ export function PullRequestsScreen(
331 renderItem={renderPullRequest}
332 ListHeaderComponent={
333 <>
288 - <PullRequestListFilters
289 - sidebar={sidebar}
290 - environments={environments.map((item) => ({
291 - id: String(item.environmentId),
292 - label: item.environmentLabel,
293 - }))}
294 - environmentId={environmentId}
295 - onEnvironmentChange={listControls.setEnvironmentId}
296 - value={
297 - typedDraft
298 - ? { ...controls, filters: { ...controls.filters, draft: typedDraft } }
299 - : controls
300 - }
301 - onChange={(next) => {
302 - const update = applyPullRequestDraftFilterChange(
303 - typedQuery,
304 - controls.filters,
305 - next.filters,
306 - );
307 - listControls.setControls(environmentId, { ...next, filters: update.filters });
308 - if (update.query !== typedQuery)
309 - workspace.dispatch({ type: "query", tab: "pullRequests", query: update.query });
310 - void listRef.current?.scrollToOffset({
311 - offset: Platform.OS === "ios" ? -insets.top : 0,
312 - animated: false,
313 - });
314 - }}
315 - authors={
316 - knownFacets.environmentId === environmentId ? knownFacets.authors : facets.authors
317 - }
318 - labels={
319 - knownFacets.environmentId === environmentId ? knownFacets.labels : facets.labels
320 - }
321 - labelColors={labelColors}
322 - projects={projects}
323 - onSearch={(kind) =>
324 - navigation.navigate("PullRequestFilterSearch", {
325 - kind,
326 - environmentId,
327 - environmentIds: targets.map((target) => String(target.environmentId)),
328 - suggestions:
329 - knownFacets.environmentId === environmentId ? knownFacets[kind] : facets[kind],
330 - labelColors,
331 - })
332 - }
333 - />
334 + <PullRequestListFilters sidebar={sidebar} filters={filters} />
335 {result.data?.errors.length ? (
336 <PullRequestListErrors
337 key={JSON.stringify(targets)}
@@ -405,4 +406,5 @@ export function PullRequestsScreen(
406 />
407 </View>
408 );
409 + return props.renderFrame ? props.renderFrame(filters.headerMenu, list) : list;
410 }
apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts new
+24
@@ -0,0 +1,24 @@
1 +import type { PullRequestFilesViewedResult } from "@t3tools/contracts";
2 +import { describe, expect, it } from "vite-plus/test";
3 +import { viewedOverlay } from "./pullRequestFilesViewed";
4 +
5 +// The overlay compares reads by identity, so each call is a distinct read.
6 +const read = (): PullRequestFilesViewedResult => ({ files: [], truncated: false });
7 +
8 +describe("viewedOverlay", () => {
9 + it("keeps a press while its write is in flight", () => {
10 + const before = read();
11 + expect(
12 + viewedOverlay({ "a.ts": { viewed: true, version: 1, awaitingReadAfter: undefined } }, before),
13 + ).toEqual({ "a.ts": true });
14 + });
15 +
16 + it("keeps a landed press until a read newer than the one current at the write", () => {
17 + const before = read();
18 + const presses = {
19 + "a.ts": { viewed: true, version: 1, awaitingReadAfter: { read: before } },
20 + };
21 + expect(viewedOverlay(presses, before)).toEqual({ "a.ts": true });
22 + expect(viewedOverlay(presses, read())).toEqual({});
23 + });
24 +});
apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts new
+28
@@ -0,0 +1,28 @@
1 +import type { PullRequestFilesViewedResult } from "@t3tools/contracts";
2 +
3 +export type FilesViewedRead = PullRequestFilesViewedResult | null;
4 +
5 +export interface ViewedPress {
6 + readonly viewed: boolean;
7 + readonly version: number;
8 + /** Set once the write lands: the press yields to the server once a read newer than this lands. */
9 + readonly awaitingReadAfter: { readonly read: FilesViewedRead } | undefined;
10 +}
11 +
12 +export interface ViewedState {
13 + readonly key: string;
14 + readonly presses: Readonly<Record<string, ViewedPress>>;
15 + readonly error: string | null;
16 +}
17 +
18 +/** The pressed states the server's read has not caught up with yet. */
19 +export function viewedOverlay(
20 + presses: Readonly<Record<string, ViewedPress>>,
21 + read: FilesViewedRead,
22 +): Record<string, boolean> {
23 + const overlay: Record<string, boolean> = {};
24 + for (const [path, press] of Object.entries(presses))
25 + if (press.awaitingReadAfter === undefined || press.awaitingReadAfter.read === read)
26 + overlay[path] = press.viewed;
27 + return overlay;
28 +}
apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts
+45 -78
@@ -1,15 +1,19 @@
1 import { usePullRequestConnected } from "./usePullRequestConnected";
2 -import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
2 +import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
3 import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4 import type { PullRequestDetail } from "@t3tools/contracts";
5 -import { useCallback, useEffect, useRef, useState } from "react";
5 +import * as Option from "effect/Option";
6 +import { AsyncResult } from "effect/reactivity";
7 +import { use, useState } from "react";
8 import { composerPullRequests } from "../../state/pull-requests";
9 import { useEnvironmentQuery } from "../../state/query";
10 import { useAtomCommand } from "../../state/use-atom-command";
11 import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
12 import { pullRequestReviewKey } from "./pullRequestReviewDrafts";
13 +import { viewedOverlay, type ViewedState } from "./pullRequestFilesViewed";
14
15 export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullRequestDetail | null) {
16 + const registry = use(RegistryContext);
17 const target = pullRequestTarget(params);
18 const scopeKey = pullRequestReviewKey(params);
19 const supported = Boolean(pr?.capabilities.viewedFiles);
@@ -21,90 +25,53 @@ export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullReq
25 const query = useEnvironmentQuery(supported ? composerPullRequests.filesViewed(target) : null);
26 const refresh = useAtomRefresh(composerPullRequests.filesViewed(target));
27 const write = useAtomCommand(composerPullRequests.setFilesViewed, { reportFailure: false });
24 - const [state, setState] = useState<{
25 - key: string;
26 - overlay: Record<string, boolean>;
27 - error: string | null;
28 - }>({ key: scopeKey, overlay: {}, error: null });
29 - const overlay = state.key === scopeKey ? state.overlay : {};
28 + const [state, setState] = useState<ViewedState>({ key: scopeKey, presses: {}, error: null });
29 + const presses = state.key === scopeKey ? state.presses : {};
30 const error = state.key === scopeKey ? state.error : null;
31 - const setOverlay = useCallback(
32 - (overlay: Record<string, boolean>) =>
33 - setState((current) => ({
34 - key: scopeKey,
35 - overlay,
36 - error: current.key === scopeKey ? current.error : null,
37 - })),
38 - [scopeKey],
39 - );
40 - const setError = (error: string | null) =>
41 - setState((current) => ({
42 - key: scopeKey,
43 - error,
44 - overlay: current.key === scopeKey ? current.overlay : {},
45 - }));
46 - const versions = useRef(new Map<string, number>());
47 - const pressed = useRef<Record<string, boolean>>({});
48 - const reads = useRef(query.data);
49 - useEffect(() => {
50 - reads.current = query.data;
51 - }, [query.data]);
52 - const awaitingRead = useRef(new Map<string, typeof query.data>());
53 - const scope = useRef(scopeKey);
54 - useEffect(() => {
55 - scope.current = scopeKey;
56 - versions.current.clear();
57 - awaitingRead.current.clear();
58 - pressed.current = {};
59 - }, [scopeKey]);
60 - useEffect(() => {
61 - if (supported && pr?.headSha) refresh();
62 - }, [supported, pr?.headSha, refresh]);
63 - useEffect(() => {
64 - let changed = false;
65 - const next = { ...pressed.current };
66 - for (const [path, from] of awaitingRead.current) {
67 - if (from === query.data) continue;
68 - delete next[path];
69 - awaitingRead.current.delete(path);
70 - changed = true;
71 - }
72 - if (changed) {
73 - pressed.current = next;
74 - setOverlay(next);
75 - }
76 - }, [query.data, setOverlay]);
77 - const isViewed = (path: string) =>
78 - overlay[path] ??
79 - query.data?.files.some((file) => file.path === path && file.state === "viewed") ??
80 - false;
31 + const overlay = viewedOverlay(presses, query.data);
32 + const update = (change: (current: ViewedState) => ViewedState) =>
33 + setState((current) =>
34 + change(current.key === scopeKey ? current : { key: scopeKey, presses: {}, error: null }),
35 + );
36 + const serverViewed = (path: string) =>
37 + query.data?.files.some((file) => file.path === path && file.state === "viewed") ?? false;
38 + const isViewed = (path: string) => overlay[path] ?? serverViewed(path);
39 const toggle = async (path: string) => {
40 if (!supported || !allowed || !query.data) return;
83 - const viewed = !(
84 - pressed.current[path] ??
85 - query.data.files.some((file) => file.path === path && file.state === "viewed")
86 - );
87 - const version = (versions.current.get(path) ?? 0) + 1;
88 - versions.current.set(path, version);
89 - awaitingRead.current.delete(path);
90 - pressed.current = { ...pressed.current, [path]: viewed };
91 - setOverlay(pressed.current);
92 - setError(null);
41 + const viewed = !isViewed(path);
42 + const version = (presses[path]?.version ?? 0) + 1;
43 + update((current) => ({
44 + ...current,
45 + error: null,
46 + presses: { ...current.presses, [path]: { viewed, version, awaitingReadAfter: undefined } },
47 + }));
48 const response = await write({
49 ...target,
50 input: { ...target.input, files: [{ path, viewed }] },
51 });
97 - if (scope.current !== scopeKey) return;
98 - if (response._tag === "Failure" && versions.current.get(path) === version) {
99 - const next = { ...pressed.current };
100 - delete next[path];
101 - pressed.current = next;
102 - setOverlay(next);
52 + // The read that is current once the write lands still predates it; a newer one carries it.
53 + const readAtWrite = Option.getOrNull(
54 + AsyncResult.value(registry.get(composerPullRequests.filesViewed(target))),
55 + );
56 + setState((current) => {
57 + if (current.key !== scopeKey || current.presses[path]?.version !== version) return current;
58 + if (response._tag === "Success")
59 + return {
60 + ...current,
61 + presses: {
62 + ...current.presses,
63 + [path]: { viewed, version, awaitingReadAfter: { read: readAtWrite } },
64 + },
65 + };
66 + const rest = { ...current.presses };
67 + delete rest[path];
68 const cause = squashAtomCommandFailure(response);
104 - setError(cause instanceof Error ? cause.message : "Could not update viewed files.");
105 - }
106 - if (response._tag === "Success" && versions.current.get(path) === version)
107 - awaitingRead.current.set(path, reads.current);
69 + return {
70 + ...current,
71 + presses: rest,
72 + error: cause instanceof Error ? cause.message : "Could not update viewed files.",
73 + };
74 + });
75 refresh();
76 };
77 return {
apps/mobile/src/features/pull-requests/usePullRequestList.ts
+43 -12
@@ -1,6 +1,6 @@
1 import { RegistryContext, useAtomValue } from "@effect/atom-react";
2 import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3 -import type { EnvironmentId, PullRequestListInput } from "@t3tools/contracts";
3 +import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
4 import * as Cause from "effect/Cause";
5 import * as Effect from "effect/Effect";
6 import * as Option from "effect/Option";
@@ -156,15 +156,20 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
156 // Starting one kind of load clears the other, so at most one holds an error.
157 const loadError = settledError(refresh) ?? settledError(page);
158
159 + // Read from the registry, not the render: a second onEndReached before React re-renders must
160 + // see the load the first one started.
161 const loadMore = (retry = false) => {
160 - if (page.waiting || refresh.waiting || (!retry && loadError)) return;
162 + const pageResult = registry.get(pageAtom);
163 + const refreshResult = registry.get(refreshAtom);
164 + if (pageResult.waiting || refreshResult.waiting) return;
165 + if (!retry && (settledError(refreshResult) ?? settledError(pageResult))) return;
166 if (!continuations(registry, targets).length) return;
167 registry.set(refreshAtom, Atom.Reset);
168 registry.set(pageAtom, retry);
169 };
170
171 const onRefresh = () => {
167 - if (!targets.length || refresh.waiting) return;
172 + if (!targets.length || registry.get(refreshAtom).waiting) return;
173 registry.set(pageAtom, Atom.Reset);
174 registry.set(refreshAtom, undefined);
175 };
@@ -249,16 +254,13 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
254 }, [statsKey]);
255 const counts = useAtomValue(statsAtom);
256 // Server answers land in pullRequestListStatsFamily; these cover a cached answer, which is
252 - // all an offline environment has.
257 + // all an offline environment has. Scrolling makes a new stats query, which has no answer until
258 + // its cached rows load, so each environment keeps the answer it showed until the new one lands.
259 + const [shown, setShown] = useState({ counts, answers: answeredStats(counts, []) });
260 + if (shown.counts !== counts) setShown({ counts, answers: answeredStats(counts, shown.answers) });
261 const entries = useMemo(
254 - () =>
255 - withShownPullRequestStats(
256 - data.entries,
257 - counts.flatMap(({ environmentId, result }) =>
258 - AsyncResult.isSuccess(result) ? [{ environmentId, stats: result.value.stats }] : [],
259 - ),
260 - ),
261 - [data.entries, counts],
262 + () => withShownPullRequestStats(data.entries, shown.answers),
263 + [data.entries, shown.answers],
264 );
265
266 const updateEntry = useCallback(
@@ -332,3 +334,32 @@ function requestErrors(results: readonly PromiseSettledResult<unknown>[]) {
334 .join("\n") || null
335 );
336 }
337 +
338 +type StatsAnswer = {
339 + readonly environmentId: EnvironmentId;
340 + readonly stats: readonly PullRequestDiffStat[];
341 +};
342 +
343 +/** Each environment's newest stats answer, or the one it had while its query has none. */
344 +function answeredStats(
345 + counts: readonly {
346 + readonly environmentId: EnvironmentId;
347 + readonly result: AsyncResult.AsyncResult<
348 + { readonly stats: readonly PullRequestDiffStat[] },
349 + unknown
350 + >;
351 + }[],
352 + previous: readonly StatsAnswer[],
353 +): readonly StatsAnswer[] {
354 + const next = counts.flatMap(({ environmentId, result }) => {
355 + const kept = previous.find((answer) => answer.environmentId === environmentId);
356 + if (!AsyncResult.isSuccess(result)) return kept ? [kept] : [];
357 + return kept?.stats === result.value.stats
358 + ? [kept]
359 + : [{ environmentId, stats: result.value.stats }];
360 + });
361 + return next.length === previous.length &&
362 + next.every((answer, index) => answer === previous[index])
363 + ? previous
364 + : next;
365 +}
apps/mobile/src/features/workspace/AndroidWorkspaceSidebar.android.tsx
+12 -11
@@ -4,7 +4,6 @@ import { NAVIGATION_TAB_ORDER } from "./navigation-tab-order";
4 import { useMemo, type ReactNode } from "react";
5 import { View } from "react-native";
6 import { ScreenContent } from "../../components/ui/ScreenContent";
7 -import { PullRequestFilterMenuProvider } from "../pull-requests/PullRequestFilterMenuContext";
7 import { PullRequestsScreen } from "../pull-requests/PullRequestsScreen";
8 import { PullRequestToolbar } from "../pull-requests/PullRequestToolbar.android";
9 import { WorkspaceTabsContext, useWorkspaceTabs } from "./WorkspaceTabsContext";
@@ -30,17 +29,19 @@ export function AndroidWorkspaceSidebar(props: {
29 <View className="flex-1 bg-screen" />
30 ) : (
31 <WorkspaceTabsContext value={context}>
33 - <PullRequestFilterMenuProvider>
34 - <View className="flex-1 bg-header">
35 - <PullRequestToolbar onRequestVisibility={props.onRequestVisibility} />
36 - <ScreenContent insetHorizontal>
37 - <PullRequestsScreen
38 - sidebar
39 - selectedPullRequestKey={props.selectedPullRequestKey}
32 + <PullRequestsScreen
33 + sidebar
34 + selectedPullRequestKey={props.selectedPullRequestKey}
35 + renderFrame={(filters, list) => (
36 + <View className="flex-1 bg-header">
37 + <PullRequestToolbar
38 + filters={filters}
39 + onRequestVisibility={props.onRequestVisibility}
40 />
41 - </ScreenContent>
42 - </View>
43 - </PullRequestFilterMenuProvider>
41 + <ScreenContent insetHorizontal>{list}</ScreenContent>
42 + </View>
43 + )}
44 + />
45 </WorkspaceTabsContext>
46 )
47 }
apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx
+8 -7
@@ -11,7 +11,6 @@ import { EmptyState } from "../../components/ui/EmptyState";
11 import { ScreenContent } from "../../components/ui/ScreenContent";
12 import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
13 import { HomeRouteScreen } from "../home/HomeRouteScreen";
14 -import { PullRequestFilterMenuProvider } from "../pull-requests/PullRequestFilterMenuContext";
14 import { PullRequestsScreen } from "../pull-requests/PullRequestsScreen";
15 import { PullRequestToolbar } from "../pull-requests/PullRequestToolbar.android";
16 import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
@@ -83,12 +82,14 @@ export function WorkspaceRootScreen() {
82 ) : tab !== "pullRequests" ? (
83 <WorkspaceExtraTab tab={tab} />
84 ) : (
86 - <PullRequestFilterMenuProvider>
87 - <PullRequestToolbar />
88 - <ScreenContent>
89 - <PullRequestsScreen />
90 - </ScreenContent>
91 - </PullRequestFilterMenuProvider>
85 + <PullRequestsScreen
86 + renderFrame={(filters, list) => (
87 + <>
88 + <PullRequestToolbar filters={filters} />
89 + <ScreenContent>{list}</ScreenContent>
90 + </>
91 + )}
92 + />
93 )
94 }
95 />
apps/mobile/src/state/pull-requests.ts
+10 -1
@@ -4,7 +4,8 @@ import {
4 } from "@t3tools/client-runtime/state/pull-requests";
5 import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
6 import * as Effect from "effect/Effect";
7 -import { Atom } from "effect/reactivity";
7 +import * as Option from "effect/Option";
8 +import { AsyncResult, Atom } from "effect/reactivity";
9 import { connectionAtomRuntime } from "../connection/runtime";
10 import {
11 pullRequestListHead,
@@ -28,6 +29,14 @@ export const pullRequestListStatsFamily = Atom.family((_environmentId: string) =
29 );
30
31 export const composerPullRequests = createPullRequestEnvironmentAtoms(connectionAtomRuntime, {
32 + // A new head can change which files GitHub still counts as viewed, so the viewed-files read is
33 + // refreshed where the new head lands. The detail atom still holds the previous answer here.
34 + detail: (target, value, registry) =>
35 + Effect.sync(() => {
36 + const previous = AsyncResult.value(registry.get(composerPullRequests.detail(target)));
37 + if (Option.isSome(previous) && previous.value.headSha !== value.headSha)
38 + registry.refresh(composerPullRequests.filesViewed(target));
39 + }),
40 list: (target, value, registry) =>
41 target.input.cursors === undefined
42 ? Effect.sync(() =>