Skip to content
TypeScript

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

Julius Marminge68339a084644
diff --git a/apps/mobile/src/features/pull-requests/PullRequestFilterMenuContext.tsx b/apps/mobile/src/features/pull-requests/PullRequestFilterMenuContext.tsx
deleted file mode 100644
index 68a423f80aa..00000000000
--- a/apps/mobile/src/features/pull-requests/PullRequestFilterMenuContext.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import type { MenuAction } from "@react-native-menu/menu";
-import {
- createContext,
- use,
- useLayoutEffect,
- useState,
- type Dispatch,
- type ReactNode,
- type SetStateAction,
-} from "react";
-
-export interface PullRequestFilterMenu {
- readonly actions: readonly MenuAction[];
- readonly onSelect: (id: string) => void;
- /** Whether any filter, the environment, or a non-default sort is active. */
- readonly customized: boolean;
-}
-
-const MenuContext = createContext<PullRequestFilterMenu | null>(null);
-const PublishContext = createContext<Dispatch<SetStateAction<PullRequestFilterMenu | null>> | null>(
- null,
-);
-
-/**
- * The Android PR header opens the full filter menu, but the facets (authors, labels) and the
- * controls live in the list below it. The list publishes its menu here; only the header reads
- * it, so the list's own renders don't fan out.
- */
-export function PullRequestFilterMenuProvider(props: { readonly children: ReactNode }) {
- const [menu, setMenu] = useState<PullRequestFilterMenu | null>(null);
- return (
- <PublishContext value={setMenu}>
- <MenuContext value={menu}>{props.children}</MenuContext>
- </PublishContext>
- );
-}
-
-export function usePullRequestFilterMenu() {
- return use(MenuContext);
-}
-
-export function usePublishPullRequestFilterMenu(menu: PullRequestFilterMenu | null) {
- const publish = use(PublishContext);
- // A layout effect, so the header's filter button lands in the same frame as the list. There is
- // no cleanup: the list lives exactly as long as this provider, and a hidden tab runs its
- // cleanups, which would drop the button for a few frames every time the tab came back.
- useLayoutEffect(() => {
- if (publish && menu) publish(menu);
- }, [publish, menu]);
-}
diff --git a/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx b/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx
index d7359680d3f..a9a5abaaea8 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx
@@ -1,10 +1,13 @@
+import { useAtomValue } from "@effect/atom-react";
import { sortProjectsByGroupOrder } from "@t3tools/client-runtime/state/project-grouping";
+import type { ScopedProjectRef, SidebarProjectGroupingMode } from "@t3tools/contracts";
+import { Atom } from "effect/reactivity";
import { useMemo } from "react";
import { Platform, ScrollView } from "react-native";
import type { MenuProps } from "../../components/ui/Menu.types";
import { ListFilterMenu } from "../workspace/ListFilterMenu";
-import { usePublishPullRequestFilterMenu } from "./PullRequestFilterMenuContext";
-import { useProjects, useThreadShells } from "../../state/entities";
+import { environmentProjects } from "../../state/projects";
+import { environmentThreadShells } from "../../state/threads";
import { useMobileProjectGroupingSettings } from "../../state/project-grouping";
import { buildHomeProjectScopes, sortHomeProjectScopes } from "../home/homeThreadList";
import { DEFAULT_PR_LIST_CONTROLS, type PullRequestListControls } from "./pullRequestList";
@@ -39,32 +42,58 @@ function choices(field: string, options: Readonly<Record<string, string>>, selec
}));
}
+type ProjectOrder = readonly { readonly memberProjectRefs: readonly ScopedProjectRef[] }[];
+const sameProjectOrder = (previous: ProjectOrder, next: ProjectOrder) =>
+ previous.length === next.length &&
+ previous.every((group, index) => {
+ const members = next[index]!.memberProjectRefs;
+ return (
+ group.memberProjectRefs.length === members.length &&
+ group.memberProjectRefs.every(
+ (ref, member) =>
+ ref.environmentId === members[member]!.environmentId &&
+ ref.projectId === members[member]!.projectId,
+ )
+ );
+ });
+
+// Thread shells change on every agent tick, but the sidebar order they decide rarely does. The
+// equality check keeps the list screen, which builds these filters, from re-rendering on each tick.
+const sidebarProjectOrderFamily = Atom.family((mode: SidebarProjectGroupingMode) =>
+ Atom.make((get) =>
+ sortHomeProjectScopes({
+ scopes: buildHomeProjectScopes({
+ projects: get(environmentProjects.projectsAtom),
+ environmentId: null,
+ projectGroupingMode: mode,
+ }),
+ threads: get(environmentThreadShells.threadShellsAtom),
+ pendingTasks: [],
+ projectSortOrder: "updated_at",
+ }).map((scope) => ({ memberProjectRefs: scope.projectRefs })),
+ ).pipe(Atom.withEquality(sameProjectOrder)),
+);
+
function useProjectsInSidebarOrder<Project extends { id: string; environmentId: string }>(
projects: readonly Project[],
) {
- const allProjects = useProjects();
- const threads = useThreadShells();
const { sidebarProjectGroupingMode } = useMobileProjectGroupingSettings();
- const scopes = useMemo(
- () =>
- sortHomeProjectScopes({
- scopes: buildHomeProjectScopes({
- projects: allProjects,
- environmentId: null,
- projectGroupingMode: sidebarProjectGroupingMode,
- }),
- threads,
- pendingTasks: [],
- projectSortOrder: "updated_at",
- }).map((scope) => ({ memberProjectRefs: scope.projectRefs })),
- [allProjects, sidebarProjectGroupingMode, threads],
- );
+ const scopes = useAtomValue(sidebarProjectOrderFamily(sidebarProjectGroupingMode));
return useMemo(() => sortProjectsByGroupOrder(projects, scopes), [projects, scopes]);
}
-export function PullRequestListFilters(props: {
- /** Android sidebar rows sit further in than full-width rows; the pills follow them. */
- readonly sidebar?: boolean;
+export interface PullRequestFilterMenu {
+ readonly actions: MenuProps["actions"];
+ readonly onSelect: (id: string) => void;
+ /** Whether any filter, the environment, or a non-default sort is active. */
+ readonly customized: boolean;
+}
+
+/**
+ * Builds the filter pills and, on Android, the header's full filter menu. The list screen owns
+ * the call so both the pills and the header it frames read the same menu.
+ */
+export function usePullRequestListFilters(props: {
readonly environments: readonly { id: string; label: string }[];
readonly environmentId: string | null;
readonly onEnvironmentChange: (id: string | null) => void;
@@ -280,7 +309,7 @@ export function PullRequestListFilters(props: {
];
const customized = count > 0 || value.sort !== "updated" || props.environmentId !== null;
// The Android header's filter button opens every filter.
- const headerMenu =
+ const headerMenu: PullRequestFilterMenu | null =
Platform.OS === "android"
? {
actions: [
@@ -296,7 +325,35 @@ export function PullRequestListFilters(props: {
customized,
}
: null;
- usePublishPullRequestFilterMenu(headerMenu);
+ return {
+ headerMenu,
+ select,
+ count,
+ more,
+ reset,
+ environmentLabel:
+ props.environments.length > 1
+ ? (props.environments.find((environment) => environment.id === props.environmentId)
+ ?.label ?? "All environments")
+ : null,
+ environmentActions,
+ state: value.state,
+ stateActions,
+ involvement: value.involvement,
+ involvementActions,
+ selectedLabelCount: selectedLabels.length,
+ labelActions,
+ author,
+ authorActions,
+ };
+}
+
+export function PullRequestListFilters(props: {
+ /** Android sidebar rows sit further in than full-width rows; the pills follow them. */
+ readonly sidebar?: boolean;
+ readonly filters: ReturnType<typeof usePullRequestListFilters>;
+}) {
+ const { count, more, reset, select, author, selectedLabelCount } = props.filters;
return (
<ScrollView
horizontal
@@ -319,43 +376,40 @@ export function PullRequestListFilters(props: {
onSelect={select}
/>
)}
- {props.environments.length > 1 ? (
+ {props.filters.environmentLabel !== null ? (
<ListFilterMenu
- label={
- props.environments.find((environment) => environment.id === props.environmentId)
- ?.label ?? "All environments"
- }
+ label={props.filters.environmentLabel}
accessibilityLabel="Choose pull request environment"
- actions={environmentActions}
+ actions={props.filters.environmentActions}
onSelect={select}
/>
) : null}
<ListFilterMenu
- label={STATES[value.state]}
- active={value.state !== "open"}
+ label={STATES[props.filters.state]}
+ active={props.filters.state !== "open"}
accessibilityLabel="Filter by state"
- actions={stateActions}
+ actions={props.filters.stateActions}
onSelect={select}
/>
<ListFilterMenu
- label={INVOLVEMENT[value.involvement]}
- active={value.involvement !== "all"}
+ label={INVOLVEMENT[props.filters.involvement]}
+ active={props.filters.involvement !== "all"}
accessibilityLabel="Filter by involvement"
- actions={involvementActions}
+ actions={props.filters.involvementActions}
onSelect={select}
/>
<ListFilterMenu
- label={selectedLabels.length ? `Labels ${selectedLabels.length}` : "Labels"}
- active={selectedLabels.length > 0}
+ label={selectedLabelCount ? `Labels ${selectedLabelCount}` : "Labels"}
+ active={selectedLabelCount > 0}
accessibilityLabel="Filter by label"
- actions={labelActions}
+ actions={props.filters.labelActions}
onSelect={select}
/>
<ListFilterMenu
label={author === "me" ? "By you" : (author ?? "Author")}
active={Boolean(author)}
accessibilityLabel="Filter by author"
- actions={authorActions}
+ actions={props.filters.authorActions}
onSelect={select}
/>
</ScrollView>
diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx
index 1fa5cd83b87..829a62d4b4b 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx
@@ -7,7 +7,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native"
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import type { PullRequestReviewerCandidate } from "@t3tools/contracts";
-import { useEffect, useRef, useState } from "react";
+import { useRef, useState } from "react";
import {
FlatList,
Platform,
@@ -86,13 +86,14 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
(a, b) => Number(b.isRequested) - Number(a.isRequested) || a.login.localeCompare(b.login),
);
})();
- useEffect(() => {
- if (candidates.length === 0) return;
+ // A new search shows its best matches from the top.
+ const search = (next: string) => {
+ setQuery(next);
listRef.current?.scrollToOffset({
offset: Platform.OS === "ios" ? -insets.top : 0,
animated: false,
});
- }, [candidates, insets.top]);
+ };
const update = async (
candidate: Pick<PullRequestReviewerCandidate, "id" | "kind" | "isRequested">,
) => {
@@ -118,7 +119,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
return;
}
if (!pr?.capabilities.reviewers.listCandidates) {
- setQuery("");
+ search("");
detail.refresh();
}
};
@@ -126,8 +127,8 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
const searchOptions = {
placeholder: "Search reviewers",
autoCapitalize: "none" as const,
- onChangeText: (event: { nativeEvent: { text: string } }) => setQuery(event.nativeEvent.text),
- onCancelButtonPress: () => setQuery(""),
+ onChangeText: (event: { nativeEvent: { text: string } }) => search(event.nativeEvent.text),
+ onCancelButtonPress: () => search(""),
hideNavigationBar: false,
hideWhenScrolling: false,
obscureBackground: false,
@@ -150,7 +151,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
? [
createNativeMailSearchToolbarItem({
placeholder: "Search reviewers",
- onSearchTextChange: setQuery,
+ onSearchTextChange: search,
showsSearchDismissButton: true,
searchTextChangeId: "pr-reviewer-search",
}),
@@ -182,7 +183,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
placeholder="Search reviewers"
placeholderTextColorClassName="accent-foreground-muted"
value={query}
- onChangeText={setQuery}
+ onChangeText={search}
autoCapitalize="none"
className="min-h-11 rounded-xl bg-grouped-card px-3 text-sm"
/>
@@ -287,7 +288,7 @@ export function PullRequestReviewersScreen({ route }: StaticScreenProps<PullRequ
placeholder="Reviewer login or ID"
placeholderTextColorClassName="accent-foreground-muted"
value={query}
- onChangeText={setQuery}
+ onChangeText={search}
autoCapitalize="none"
autoCorrect={false}
className="min-h-12 rounded-xl bg-grouped-card px-3 text-base"
diff --git a/apps/mobile/src/features/pull-requests/PullRequestToolbar.android.tsx b/apps/mobile/src/features/pull-requests/PullRequestToolbar.android.tsx
index f2c3f205ad5..c6cb7e2bea7 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestToolbar.android.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestToolbar.android.tsx
@@ -1,4 +1,4 @@
-import { useNavigation, useNavigationState } from "@react-navigation/native";
+import { useNavigation } from "@react-navigation/native";
import { useCallback, useEffect, useRef } from "react";
import { BackHandler, Keyboard, View, type TextInputInstance } from "react-native";
import { AndroidHeaderIconButton } from "../../components/ui/AndroidScreenHeader";
@@ -8,17 +8,18 @@ import { useToolbarLayout } from "../../components/ui/useToolbarLayout";
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
import { WorkspaceListToolbarRow } from "../workspace/WorkspaceListToolbarRow";
import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
-import { usePullRequestFilterMenu } from "./PullRequestFilterMenuContext";
+import type { PullRequestFilterMenu } from "./PullRequestListFilters";
import { openSettings } from "../settings/settings-navigation";
/** PR search shares the thread list's Android header row. */
-export function PullRequestToolbar(props: { readonly onRequestVisibility?: () => void }) {
+export function PullRequestToolbar(props: {
+ readonly filters: PullRequestFilterMenu | null;
+ readonly onRequestVisibility?: () => void;
+}) {
const navigation = useNavigation();
- const filters = usePullRequestFilterMenu();
+ const { filters } = props;
const workspace = useWorkspaceTabs()!;
const { dispatch, getScrollOffset, recordScrollOffset, isTabActive } = workspace;
- const homeFocused = useNavigationState((state) => state.routes[state.index]?.name === "Home");
- const listFocused = homeFocused && workspace.state.selectedTab === "pullRequests";
const { onRequestVisibility } = props;
const tab = workspace.state.tabs.pullRequests;
const input = useRef<TextInputInstance>(null);
@@ -41,9 +42,10 @@ export function PullRequestToolbar(props: { readonly onRequestVisibility?: () =>
dispatch({ type: "cancel", tab: "pullRequests" });
}, [dispatch, recordScrollOffset, tab.searchEntryOffset]);
useEffect(() => {
- if (!searching || !listFocused) return;
+ if (!searching) return;
const subscription = BackHandler.addEventListener("hardwareBackPress", () => {
- // Frozen Home screens can keep effects alive after a detail route opens.
+ // Frozen Home screens stay mounted under a detail route or another tab,
+ // so back only applies while the PR list is in front.
const state = navigation.getState();
if (!state || state.routes[state.index]?.name !== "Home" || !isTabActive("pullRequests"))
return false;
@@ -52,7 +54,7 @@ export function PullRequestToolbar(props: { readonly onRequestVisibility?: () =>
return true;
});
return () => subscription.remove();
- }, [searching, closeSearch, listFocused, navigation, isTabActive]);
+ }, [searching, closeSearch, navigation, isTabActive]);
const { paddingTop, paddingBottom } = useToolbarLayout();
return (
<View className="bg-header px-2" style={{ paddingTop, paddingBottom }}>
diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx
index 1554c184d39..096f12c4204 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx
@@ -6,7 +6,7 @@ import {
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
import { useNavigation } from "@react-navigation/native";
-import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { use, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useAtomValue } from "@effect/atom-react";
import {
Keyboard,
@@ -26,7 +26,11 @@ import { useWorkspaceState } from "../../state/workspace";
import { useProjects } from "../../state/entities";
import { environmentServerConfigsAtom } from "../../state/server";
import { PullRequestListRow } from "./PullRequestListRow";
-import { PullRequestListFilters } from "./PullRequestListFilters";
+import {
+ PullRequestListFilters,
+ usePullRequestListFilters,
+ type PullRequestFilterMenu,
+} from "./PullRequestListFilters";
import { PullRequestCardRow } from "./PullRequestControls";
import { usePullRequestList } from "./usePullRequestList";
import { usePullRequestListControls } from "./usePullRequestListControls";
@@ -79,6 +83,11 @@ export function PullRequestsScreen(
props: {
readonly sidebar?: boolean;
readonly selectedPullRequestKey?: string | null;
+ /**
+ * Places the list under a header that opens the full filter menu (the Android toolbar). The
+ * filters live here, so the header gets them in the same render as the list.
+ */
+ readonly renderFrame?: (filters: PullRequestFilterMenu | null, list: ReactNode) => ReactNode;
} = {},
) {
const navigation = useNavigation();
@@ -87,9 +96,23 @@ export function PullRequestsScreen(
const { environments } = useWorkspaceState();
const configs = useAtomValue(environmentServerConfigsAtom);
const insets = useSafeAreaInsets();
- const [initialOffset] = useState(() => workspace.getScrollOffset("pullRequests"));
const listRef = useRef<LegendListRef>(null);
const tab = workspace.state.tabs.pullRequests;
+ const [initialScrollOffset] = useState(() => workspace.getScrollOffset("pullRequests"));
+ // Cancelling search restores the offset recorded when search opened. The
+ // toolbar that cancels has no handle on this list, so the list scrolls itself
+ // once it sees the tab come back to resting.
+ const previousSearchMode = useRef(tab.searchMode);
+ useEffect(() => {
+ const restoringSearch =
+ previousSearchMode.current !== "resting" && tab.searchMode === "resting";
+ previousSearchMode.current = tab.searchMode;
+ if (restoringSearch)
+ void listRef.current?.scrollToOffset({
+ offset: tab.scrollOffset - (Platform.OS === "ios" ? insets.top : 0),
+ animated: false,
+ });
+ }, [tab.searchMode, tab.scrollOffset, insets.top]);
const maintainVisiblePosition = useMemo(
() => ({
data: tab.searchMode === "resting",
@@ -203,6 +226,39 @@ export function PullRequestsScreen(
(project) =>
!project.isScratch && (environmentId === null || project.environmentId === environmentId),
);
+ const filters = usePullRequestListFilters({
+ environments: environments.map((item) => ({
+ id: String(item.environmentId),
+ label: item.environmentLabel,
+ })),
+ environmentId,
+ onEnvironmentChange: listControls.setEnvironmentId,
+ value: typedDraft
+ ? { ...controls, filters: { ...controls.filters, draft: typedDraft } }
+ : controls,
+ onChange: (next) => {
+ const update = applyPullRequestDraftFilterChange(typedQuery, controls.filters, next.filters);
+ listControls.setControls(environmentId, { ...next, filters: update.filters });
+ if (update.query !== typedQuery)
+ workspace.dispatch({ type: "query", tab: "pullRequests", query: update.query });
+ void listRef.current?.scrollToOffset({
+ offset: Platform.OS === "ios" ? -insets.top : 0,
+ animated: false,
+ });
+ },
+ authors: knownFacets.environmentId === environmentId ? knownFacets.authors : facets.authors,
+ labels: knownFacets.environmentId === environmentId ? knownFacets.labels : facets.labels,
+ labelColors,
+ projects,
+ onSearch: (kind) =>
+ navigation.navigate("PullRequestFilterSearch", {
+ kind,
+ environmentId,
+ environmentIds: targets.map((target) => String(target.environmentId)),
+ suggestions: knownFacets.environmentId === environmentId ? knownFacets[kind] : facets[kind],
+ labelColors,
+ }),
+ });
const renderPullRequest = useCallback(
({ item }: { readonly item: EnvironmentPullRequestListEntry }) => (
<PullRequestListRow
@@ -217,19 +273,7 @@ export function PullRequestsScreen(
),
[selectPullRequest, selectedKey, actions, select, busyKey, sidebar],
);
- const previousSearchMode = useRef(tab.searchMode);
- useEffect(() => {
- const restoringSearch =
- previousSearchMode.current !== "resting" && tab.searchMode === "resting";
- previousSearchMode.current = tab.searchMode;
- if (restoringSearch)
- void listRef.current?.scrollToOffset({
- offset: tab.scrollOffset - (Platform.OS === "ios" ? insets.top : 0),
- animated: false,
- });
- }, [tab.searchMode, tab.scrollOffset, insets.top]);
-
- return (
+ const list = (
<View className={sidebar ? "flex-1 bg-drawer" : "flex-1 bg-screen"}>
<LegendList
ref={listRef}
@@ -263,7 +307,9 @@ export function PullRequestsScreen(
// A plain offset: LegendList adds the list header to an index-based restore, which
// landed every return one header lower.
initialScrollOffset={
- initialOffset > 0 ? initialOffset - (Platform.OS === "ios" ? insets.top : 0) : undefined
+ initialScrollOffset > 0
+ ? initialScrollOffset - (Platform.OS === "ios" ? insets.top : 0)
+ : undefined
}
contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0}
contentContainerStyle={{
@@ -285,52 +331,7 @@ export function PullRequestsScreen(
renderItem={renderPullRequest}
ListHeaderComponent={
<>
- <PullRequestListFilters
- sidebar={sidebar}
- environments={environments.map((item) => ({
- id: String(item.environmentId),
- label: item.environmentLabel,
- }))}
- environmentId={environmentId}
- onEnvironmentChange={listControls.setEnvironmentId}
- value={
- typedDraft
- ? { ...controls, filters: { ...controls.filters, draft: typedDraft } }
- : controls
- }
- onChange={(next) => {
- const update = applyPullRequestDraftFilterChange(
- typedQuery,
- controls.filters,
- next.filters,
- );
- listControls.setControls(environmentId, { ...next, filters: update.filters });
- if (update.query !== typedQuery)
- workspace.dispatch({ type: "query", tab: "pullRequests", query: update.query });
- void listRef.current?.scrollToOffset({
- offset: Platform.OS === "ios" ? -insets.top : 0,
- animated: false,
- });
- }}
- authors={
- knownFacets.environmentId === environmentId ? knownFacets.authors : facets.authors
- }
- labels={
- knownFacets.environmentId === environmentId ? knownFacets.labels : facets.labels
- }
- labelColors={labelColors}
- projects={projects}
- onSearch={(kind) =>
- navigation.navigate("PullRequestFilterSearch", {
- kind,
- environmentId,
- environmentIds: targets.map((target) => String(target.environmentId)),
- suggestions:
- knownFacets.environmentId === environmentId ? knownFacets[kind] : facets[kind],
- labelColors,
- })
- }
- />
+ <PullRequestListFilters sidebar={sidebar} filters={filters} />
{result.data?.errors.length ? (
<PullRequestListErrors
key={JSON.stringify(targets)}
@@ -405,4 +406,5 @@ export function PullRequestsScreen(
/>
</View>
);
+ return props.renderFrame ? props.renderFrame(filters.headerMenu, list) : list;
}
diff --git a/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts
new file mode 100644
index 00000000000..ee438e61872
--- /dev/null
+++ b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.test.ts
@@ -0,0 +1,24 @@
+import type { PullRequestFilesViewedResult } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+import { viewedOverlay } from "./pullRequestFilesViewed";
+
+// The overlay compares reads by identity, so each call is a distinct read.
+const read = (): PullRequestFilesViewedResult => ({ files: [], truncated: false });
+
+describe("viewedOverlay", () => {
+ it("keeps a press while its write is in flight", () => {
+ const before = read();
+ expect(
+ viewedOverlay({ "a.ts": { viewed: true, version: 1, awaitingReadAfter: undefined } }, before),
+ ).toEqual({ "a.ts": true });
+ });
+
+ it("keeps a landed press until a read newer than the one current at the write", () => {
+ const before = read();
+ const presses = {
+ "a.ts": { viewed: true, version: 1, awaitingReadAfter: { read: before } },
+ };
+ expect(viewedOverlay(presses, before)).toEqual({ "a.ts": true });
+ expect(viewedOverlay(presses, read())).toEqual({});
+ });
+});
diff --git a/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts
new file mode 100644
index 00000000000..b76d3193c9c
--- /dev/null
+++ b/apps/mobile/src/features/pull-requests/pullRequestFilesViewed.ts
@@ -0,0 +1,28 @@
+import type { PullRequestFilesViewedResult } from "@t3tools/contracts";
+
+export type FilesViewedRead = PullRequestFilesViewedResult | null;
+
+export interface ViewedPress {
+ readonly viewed: boolean;
+ readonly version: number;
+ /** Set once the write lands: the press yields to the server once a read newer than this lands. */
+ readonly awaitingReadAfter: { readonly read: FilesViewedRead } | undefined;
+}
+
+export interface ViewedState {
+ readonly key: string;
+ readonly presses: Readonly<Record<string, ViewedPress>>;
+ readonly error: string | null;
+}
+
+/** The pressed states the server's read has not caught up with yet. */
+export function viewedOverlay(
+ presses: Readonly<Record<string, ViewedPress>>,
+ read: FilesViewedRead,
+): Record<string, boolean> {
+ const overlay: Record<string, boolean> = {};
+ for (const [path, press] of Object.entries(presses))
+ if (press.awaitingReadAfter === undefined || press.awaitingReadAfter.read === read)
+ overlay[path] = press.viewed;
+ return overlay;
+}
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts b/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts
index cf882ac0dae..46f6f941806 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestFilesViewed.ts
@@ -1,15 +1,19 @@
import { usePullRequestConnected } from "./usePullRequestConnected";
-import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
+import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { PullRequestDetail } from "@t3tools/contracts";
-import { useCallback, useEffect, useRef, useState } from "react";
+import * as Option from "effect/Option";
+import { AsyncResult } from "effect/reactivity";
+import { use, useState } from "react";
import { composerPullRequests } from "../../state/pull-requests";
import { useEnvironmentQuery } from "../../state/query";
import { useAtomCommand } from "../../state/use-atom-command";
import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff";
import { pullRequestReviewKey } from "./pullRequestReviewDrafts";
+import { viewedOverlay, type ViewedState } from "./pullRequestFilesViewed";
export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullRequestDetail | null) {
+ const registry = use(RegistryContext);
const target = pullRequestTarget(params);
const scopeKey = pullRequestReviewKey(params);
const supported = Boolean(pr?.capabilities.viewedFiles);
@@ -21,90 +25,53 @@ export function usePullRequestFilesViewed(params: PullRequestParams, pr: PullReq
const query = useEnvironmentQuery(supported ? composerPullRequests.filesViewed(target) : null);
const refresh = useAtomRefresh(composerPullRequests.filesViewed(target));
const write = useAtomCommand(composerPullRequests.setFilesViewed, { reportFailure: false });
- const [state, setState] = useState<{
- key: string;
- overlay: Record<string, boolean>;
- error: string | null;
- }>({ key: scopeKey, overlay: {}, error: null });
- const overlay = state.key === scopeKey ? state.overlay : {};
+ const [state, setState] = useState<ViewedState>({ key: scopeKey, presses: {}, error: null });
+ const presses = state.key === scopeKey ? state.presses : {};
const error = state.key === scopeKey ? state.error : null;
- const setOverlay = useCallback(
- (overlay: Record<string, boolean>) =>
- setState((current) => ({
- key: scopeKey,
- overlay,
- error: current.key === scopeKey ? current.error : null,
- })),
- [scopeKey],
- );
- const setError = (error: string | null) =>
- setState((current) => ({
- key: scopeKey,
- error,
- overlay: current.key === scopeKey ? current.overlay : {},
- }));
- const versions = useRef(new Map<string, number>());
- const pressed = useRef<Record<string, boolean>>({});
- const reads = useRef(query.data);
- useEffect(() => {
- reads.current = query.data;
- }, [query.data]);
- const awaitingRead = useRef(new Map<string, typeof query.data>());
- const scope = useRef(scopeKey);
- useEffect(() => {
- scope.current = scopeKey;
- versions.current.clear();
- awaitingRead.current.clear();
- pressed.current = {};
- }, [scopeKey]);
- useEffect(() => {
- if (supported && pr?.headSha) refresh();
- }, [supported, pr?.headSha, refresh]);
- useEffect(() => {
- let changed = false;
- const next = { ...pressed.current };
- for (const [path, from] of awaitingRead.current) {
- if (from === query.data) continue;
- delete next[path];
- awaitingRead.current.delete(path);
- changed = true;
- }
- if (changed) {
- pressed.current = next;
- setOverlay(next);
- }
- }, [query.data, setOverlay]);
- const isViewed = (path: string) =>
- overlay[path] ??
- query.data?.files.some((file) => file.path === path && file.state === "viewed") ??
- false;
+ const overlay = viewedOverlay(presses, query.data);
+ const update = (change: (current: ViewedState) => ViewedState) =>
+ setState((current) =>
+ change(current.key === scopeKey ? current : { key: scopeKey, presses: {}, error: null }),
+ );
+ const serverViewed = (path: string) =>
+ query.data?.files.some((file) => file.path === path && file.state === "viewed") ?? false;
+ const isViewed = (path: string) => overlay[path] ?? serverViewed(path);
const toggle = async (path: string) => {
if (!supported || !allowed || !query.data) return;
- const viewed = !(
- pressed.current[path] ??
- query.data.files.some((file) => file.path === path && file.state === "viewed")
- );
- const version = (versions.current.get(path) ?? 0) + 1;
- versions.current.set(path, version);
- awaitingRead.current.delete(path);
- pressed.current = { ...pressed.current, [path]: viewed };
- setOverlay(pressed.current);
- setError(null);
+ const viewed = !isViewed(path);
+ const version = (presses[path]?.version ?? 0) + 1;
+ update((current) => ({
+ ...current,
+ error: null,
+ presses: { ...current.presses, [path]: { viewed, version, awaitingReadAfter: undefined } },
+ }));
const response = await write({
...target,
input: { ...target.input, files: [{ path, viewed }] },
});
- if (scope.current !== scopeKey) return;
- if (response._tag === "Failure" && versions.current.get(path) === version) {
- const next = { ...pressed.current };
- delete next[path];
- pressed.current = next;
- setOverlay(next);
+ // The read that is current once the write lands still predates it; a newer one carries it.
+ const readAtWrite = Option.getOrNull(
+ AsyncResult.value(registry.get(composerPullRequests.filesViewed(target))),
+ );
+ setState((current) => {
+ if (current.key !== scopeKey || current.presses[path]?.version !== version) return current;
+ if (response._tag === "Success")
+ return {
+ ...current,
+ presses: {
+ ...current.presses,
+ [path]: { viewed, version, awaitingReadAfter: { read: readAtWrite } },
+ },
+ };
+ const rest = { ...current.presses };
+ delete rest[path];
const cause = squashAtomCommandFailure(response);
- setError(cause instanceof Error ? cause.message : "Could not update viewed files.");
- }
- if (response._tag === "Success" && versions.current.get(path) === version)
- awaitingRead.current.set(path, reads.current);
+ return {
+ ...current,
+ presses: rest,
+ error: cause instanceof Error ? cause.message : "Could not update viewed files.",
+ };
+ });
refresh();
};
return {
diff --git a/apps/mobile/src/features/pull-requests/usePullRequestList.ts b/apps/mobile/src/features/pull-requests/usePullRequestList.ts
index 73dad15cafd..477caa0559b 100644
--- a/apps/mobile/src/features/pull-requests/usePullRequestList.ts
+++ b/apps/mobile/src/features/pull-requests/usePullRequestList.ts
@@ -1,6 +1,6 @@
import { RegistryContext, useAtomValue } from "@effect/atom-react";
import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
-import type { EnvironmentId, PullRequestListInput } from "@t3tools/contracts";
+import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
@@ -156,15 +156,20 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
// Starting one kind of load clears the other, so at most one holds an error.
const loadError = settledError(refresh) ?? settledError(page);
+ // Read from the registry, not the render: a second onEndReached before React re-renders must
+ // see the load the first one started.
const loadMore = (retry = false) => {
- if (page.waiting || refresh.waiting || (!retry && loadError)) return;
+ const pageResult = registry.get(pageAtom);
+ const refreshResult = registry.get(refreshAtom);
+ if (pageResult.waiting || refreshResult.waiting) return;
+ if (!retry && (settledError(refreshResult) ?? settledError(pageResult))) return;
if (!continuations(registry, targets).length) return;
registry.set(refreshAtom, Atom.Reset);
registry.set(pageAtom, retry);
};
const onRefresh = () => {
- if (!targets.length || refresh.waiting) return;
+ if (!targets.length || registry.get(refreshAtom).waiting) return;
registry.set(pageAtom, Atom.Reset);
registry.set(refreshAtom, undefined);
};
@@ -249,16 +254,13 @@ export function usePullRequestList(targets: readonly ListTarget[]) {
}, [statsKey]);
const counts = useAtomValue(statsAtom);
// Server answers land in pullRequestListStatsFamily; these cover a cached answer, which is
- // all an offline environment has.
+ // all an offline environment has. Scrolling makes a new stats query, which has no answer until
+ // its cached rows load, so each environment keeps the answer it showed until the new one lands.
+ const [shown, setShown] = useState({ counts, answers: answeredStats(counts, []) });
+ if (shown.counts !== counts) setShown({ counts, answers: answeredStats(counts, shown.answers) });
const entries = useMemo(
- () =>
- withShownPullRequestStats(
- data.entries,
- counts.flatMap(({ environmentId, result }) =>
- AsyncResult.isSuccess(result) ? [{ environmentId, stats: result.value.stats }] : [],
- ),
- ),
- [data.entries, counts],
+ () => withShownPullRequestStats(data.entries, shown.answers),
+ [data.entries, shown.answers],
);
const updateEntry = useCallback(
@@ -332,3 +334,32 @@ function requestErrors(results: readonly PromiseSettledResult<unknown>[]) {
.join("\n") || null
);
}
+
+type StatsAnswer = {
+ readonly environmentId: EnvironmentId;
+ readonly stats: readonly PullRequestDiffStat[];
+};
+
+/** Each environment's newest stats answer, or the one it had while its query has none. */
+function answeredStats(
+ counts: readonly {
+ readonly environmentId: EnvironmentId;
+ readonly result: AsyncResult.AsyncResult<
+ { readonly stats: readonly PullRequestDiffStat[] },
+ unknown
+ >;
+ }[],
+ previous: readonly StatsAnswer[],
+): readonly StatsAnswer[] {
+ const next = counts.flatMap(({ environmentId, result }) => {
+ const kept = previous.find((answer) => answer.environmentId === environmentId);
+ if (!AsyncResult.isSuccess(result)) return kept ? [kept] : [];
+ return kept?.stats === result.value.stats
+ ? [kept]
+ : [{ environmentId, stats: result.value.stats }];
+ });
+ return next.length === previous.length &&
+ next.every((answer, index) => answer === previous[index])
+ ? previous
+ : next;
+}
diff --git a/apps/mobile/src/features/workspace/AndroidWorkspaceSidebar.android.tsx b/apps/mobile/src/features/workspace/AndroidWorkspaceSidebar.android.tsx
index 65fa9d1d37e..d0d0796c9b6 100644
--- a/apps/mobile/src/features/workspace/AndroidWorkspaceSidebar.android.tsx
+++ b/apps/mobile/src/features/workspace/AndroidWorkspaceSidebar.android.tsx
@@ -4,7 +4,6 @@ import { NAVIGATION_TAB_ORDER } from "./navigation-tab-order";
import { useMemo, type ReactNode } from "react";
import { View } from "react-native";
import { ScreenContent } from "../../components/ui/ScreenContent";
-import { PullRequestFilterMenuProvider } from "../pull-requests/PullRequestFilterMenuContext";
import { PullRequestsScreen } from "../pull-requests/PullRequestsScreen";
import { PullRequestToolbar } from "../pull-requests/PullRequestToolbar.android";
import { WorkspaceTabsContext, useWorkspaceTabs } from "./WorkspaceTabsContext";
@@ -30,17 +29,19 @@ export function AndroidWorkspaceSidebar(props: {
<View className="flex-1 bg-screen" />
) : (
<WorkspaceTabsContext value={context}>
- <PullRequestFilterMenuProvider>
- <View className="flex-1 bg-header">
- <PullRequestToolbar onRequestVisibility={props.onRequestVisibility} />
- <ScreenContent insetHorizontal>
- <PullRequestsScreen
- sidebar
- selectedPullRequestKey={props.selectedPullRequestKey}
+ <PullRequestsScreen
+ sidebar
+ selectedPullRequestKey={props.selectedPullRequestKey}
+ renderFrame={(filters, list) => (
+ <View className="flex-1 bg-header">
+ <PullRequestToolbar
+ filters={filters}
+ onRequestVisibility={props.onRequestVisibility}
/>
- </ScreenContent>
- </View>
- </PullRequestFilterMenuProvider>
+ <ScreenContent insetHorizontal>{list}</ScreenContent>
+ </View>
+ )}
+ />
</WorkspaceTabsContext>
)
}
diff --git a/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx b/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx
index 1173a08e867..3f346f69bd4 100644
--- a/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx
+++ b/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx
@@ -11,7 +11,6 @@ import { EmptyState } from "../../components/ui/EmptyState";
import { ScreenContent } from "../../components/ui/ScreenContent";
import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
import { HomeRouteScreen } from "../home/HomeRouteScreen";
-import { PullRequestFilterMenuProvider } from "../pull-requests/PullRequestFilterMenuContext";
import { PullRequestsScreen } from "../pull-requests/PullRequestsScreen";
import { PullRequestToolbar } from "../pull-requests/PullRequestToolbar.android";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
@@ -83,12 +82,14 @@ export function WorkspaceRootScreen() {
) : tab !== "pullRequests" ? (
<WorkspaceExtraTab tab={tab} />
) : (
- <PullRequestFilterMenuProvider>
- <PullRequestToolbar />
- <ScreenContent>
- <PullRequestsScreen />
- </ScreenContent>
- </PullRequestFilterMenuProvider>
+ <PullRequestsScreen
+ renderFrame={(filters, list) => (
+ <>
+ <PullRequestToolbar filters={filters} />
+ <ScreenContent>{list}</ScreenContent>
+ </>
+ )}
+ />
)
}
/>
diff --git a/apps/mobile/src/state/pull-requests.ts b/apps/mobile/src/state/pull-requests.ts
index 5d6b5980fa9..e803bd0de1f 100644
--- a/apps/mobile/src/state/pull-requests.ts
+++ b/apps/mobile/src/state/pull-requests.ts
@@ -4,7 +4,8 @@ import {
} from "@t3tools/client-runtime/state/pull-requests";
import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
-import { Atom } from "effect/reactivity";
+import * as Option from "effect/Option";
+import { AsyncResult, Atom } from "effect/reactivity";
import { connectionAtomRuntime } from "../connection/runtime";
import {
pullRequestListHead,
@@ -28,6 +29,14 @@ export const pullRequestListStatsFamily = Atom.family((_environmentId: string) =
);
export const composerPullRequests = createPullRequestEnvironmentAtoms(connectionAtomRuntime, {
+ // A new head can change which files GitHub still counts as viewed, so the viewed-files read is
+ // refreshed where the new head lands. The detail atom still holds the previous answer here.
+ detail: (target, value, registry) =>
+ Effect.sync(() => {
+ const previous = AsyncResult.value(registry.get(composerPullRequests.detail(target)));
+ if (Option.isSome(previous) && previous.value.headSha !== value.headSha)
+ registry.refresh(composerPullRequests.filesViewed(target));
+ }),
list: (target, value, registry) =>
target.input.cursors === undefined
? Effect.sync(() =>