Skip to content
Merged
37 changes: 24 additions & 13 deletions apps/mobile/src/features/issues/IssuesScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useAtom, useAtomValue } from "@effect/atom-react";
import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
import {
continueIssuePage,
applyIssueContinuations,
groupIssues,
holdIssuePages,
issueFilterScopes,
Expand All @@ -20,9 +20,9 @@ import type {
IssueListSort,
IssueListState,
} from "@t3tools/contracts";
import { AsyncResult } from "effect/reactivity";
import { AsyncResult, Atom } from "effect/reactivity";
import { msg, useGT, useMessages } from "gt-react-native";
import { use, useEffect, useRef, useState, type ReactNode } from "react";
import { use, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { Keyboard, Platform, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

Expand Down Expand Up @@ -163,8 +163,20 @@ export function IssuesScreen(
.sort((left, right) => left.environmentId.localeCompare(right.environmentId));
const list = useIssueList(targets);

const [pages, setPages] = useState<ReadonlyMap<EnvironmentId, HeldIssuePage>>(new Map());
const held = holdIssuePages(list.answers, pages, JSON.stringify(targets));
const [pagesAtom] = useState(() =>
Atom.make<ReadonlyMap<EnvironmentId, HeldIssuePage>>(new Map()),
);
const [pages, setPages] = useAtom(pagesAtom);
const listKey = JSON.stringify(targets);
const held = holdIssuePages(list.answers, pages, listKey);
const activeListKey = useRef<string | null>(null);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Tracks which listing is mounted when a continuation settles.
useLayoutEffect(() => {
activeListKey.current = listKey;
return () => {
activeListKey.current = null;
};
}, [listKey]);
const loadPage = useAtomCommand(issueEnvironment.listPage, { reportFailure: false });
const readPage = async (environmentId: EnvironmentId, cursors: IssueListCursors) => {
const result = await loadPage({ environmentId, input: { ...listInput, cursors } });
Expand Down Expand Up @@ -194,17 +206,16 @@ export function IssuesScreen(
loading.current = true;
setLoadingMore(true);
const loaded = await Promise.all(
continuable.map(
async ([environmentId, page]) =>
[
environmentId,
continueIssuePage(page, await readPage(environmentId, page.nextCursors)),
] as const,
),
continuable.map(async ([environmentId, page]) => ({
environmentId,
page,
result: await readPage(environmentId, page.nextCursors),
})),
);
loading.current = false;
setLoadingMore(false);
setPages(new Map([...held, ...loaded]));
if (activeListKey.current !== listKey) return;
setPages((current) => applyIssueContinuations(current, list.readAnswers(), listKey, loaded));
};

const groups = groupIssues(held, query, projects, sort);
Expand Down
4 changes: 3 additions & 1 deletion apps/mobile/src/state/issues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ const mergedIssueLists = createMergedIssueListAtoms(issueEnvironment, formatEnvi

/** One listing read across every environment asked. */
export function useIssueList(targets: ReadonlyArray<IssueListTarget>) {
const view = useAtomValue(mergedIssueLists.atom(targets));
const list = mergedIssueLists.atom(targets);
const view = useAtomValue(list);
return {
...view,
readAnswers: () => appAtomRegistry.get(list).answers,
refresh: () => mergedIssueLists.refresh(appAtomRegistry, targets, "manual"),
};
}
Expand Down
142 changes: 137 additions & 5 deletions apps/web/src/components/issue/IssuesPage.browser.test.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
import { RegistryContext, useAtomValue } from "@effect/atom-react";
import {
EnvironmentId,
IssueTrackerKind,
ProjectId,
type IssueListInput,
type IssueListResult,
} from "@t3tools/contracts";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
import { describe, expect, it, vi } from "vite-plus/test";

Expand All @@ -12,7 +21,16 @@ const selectedIssue = {
scope: "owner/repo",
key: "7",
} as const;
const state = vi.hoisted(() => ({ navigate: vi.fn() }));
const state = vi.hoisted(() => ({
navigate: vi.fn(),
loadPage:
vi.fn<
(request: { input: IssueListInput }) => Promise<AsyncResult.AsyncResult<IssueListResult>>
>(),
registry: null as unknown as AtomRegistry.AtomRegistry,
}));
const environmentId = EnvironmentId.make("env-1");
const answers = Atom.make<ReadonlyArray<readonly [EnvironmentId, IssueListResult]>>([]);

vi.mock(import("@tanstack/react-router"), async (original) => ({
...(await original()),
Expand Down Expand Up @@ -45,15 +63,26 @@ vi.mock(import("~/state/entities"), async (original) => ({
}));
vi.mock(import("~/state/issues"), async (original) => ({
...(await original()),
useIssueList: (() => ({
answers: [],
useIssueList: () => ({
answers: useAtomValue(answers),
readAnswers: () => state.registry.get(answers),
isPending: false,
error: null,
refresh: () => {},
reload: () => {},
retry: () => {},
})) as never,
}),
}));
vi.mock(import("~/state/use-atom-command"), async (original) => {
const { useAtomCommand } = await original();
const { issueEnvironment } = await import("~/state/issues");
return {
useAtomCommand: (command, options) =>
Object.is(command, issueEnvironment.listPage)
? (state.loadPage as never)
: useAtomCommand(command, options),
};
});

import {
ISSUES_PANEL_REF,
Expand All @@ -64,15 +93,19 @@ import { IssuesPage } from "./IssuesPage";

function setup() {
state.navigate.mockReset();
state.loadPage.mockReset();
const registry = AtomRegistry.make();
state.registry = registry;
useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });
return { registry, [Symbol.dispose]: () => registry.dispose() };
}

const panelSurfaces = () =>
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ISSUES_PANEL_REF).surfaces;

describe("IssuesPage shortcuts", () => {
it("closes the active issue tab on the right panel close shortcut", async () => {
setup();
using _setup = setup();
using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
await using _screen = await render(<IssuesPage />);
expect(panelSurfaces()).toHaveLength(1);
Expand All @@ -88,3 +121,102 @@ describe("IssuesPage shortcuts", () => {
expect(state.navigate).toHaveBeenCalledWith({ search: { who: "all", status: "open" } });
});
});

const cursorKey = "github.com owner/repo";

function issuePage(key: string, title: string, next: string): IssueListResult {
const tracker = IssueTrackerKind.make("github");
return {
viewers: {},
trackers: [
{
tracker,
host: "github.com",
projectCount: 1,
configured: true,
capabilities: null,
detail: null,
},
],
errors: [],
entries: [
{
tracker,
host: "github.com",
scope: "owner/repo",
key,
displayKey: `#${key}`,
title,
url: `https://github.com/owner/repo/issues/${key}`,
projectId: ProjectId.make("project-1"),
projectTitle: "repo",
state: { category: "open", name: "Open" },
createdAt: "2026-10-01T00:00:00.000Z",
updatedAt: "2026-10-01T00:00:00.000Z",
closedAt: null,
author: null,
assignees: [],
labels: [],
commentCount: 0,
},
],
nextCursors: { [cursorKey]: next },
};
}

it("ignores a continuation that settles before React renders the published refresh", async () => {
using setupState = setup();
const { registry } = setupState;
registry.set(answers, [[environmentId, issuePage("1", "Old first page", "old-2")]]);
const late = Promise.withResolvers<AsyncResult.AsyncResult<IssueListResult>>();
state.loadPage
.mockResolvedValueOnce(AsyncResult.success(issuePage("2", "Old second page", "old-3")))
.mockReturnValueOnce(late.promise)
.mockResolvedValueOnce(AsyncResult.success(issuePage("5", "Refreshed second page", "new-3")))
.mockResolvedValue(AsyncResult.success(issuePage("6", "Unexpected third page", "new-4")));
// Hold the first-page notification until the pending command has completed. The
// registry value is still available synchronously to code applying the response.
const subscribe = registry.subscribe.bind(registry);
let deliverRefresh: (() => void) | undefined;
using _subscription = vi
.spyOn(registry, "subscribe")
.mockImplementation((atom, notify, options) =>
subscribe(
atom,
(value) => {
if (atom === answers) deliverRefresh = () => notify(value);
else notify(value);
},
options,
),
);
await using screen = await render(
<RegistryContext value={registry}>
<IssuesPage />
</RegistryContext>,
);
const loadMore = screen.getByRole("button", { name: "Load more", exact: true });
await act(() => (loadMore.element() as HTMLButtonElement).click());
await expect.element(screen.getByText("Old second page")).toBeVisible();
await act(() => (loadMore.element() as HTMLButtonElement).click());
await expect.element(screen.getByRole("button", { name: "Loading…" })).toBeVisible();
await act(() => {
registry.set(answers, [[environmentId, issuePage("4", "Refreshed first page", "new-2")]]);
late.resolve(AsyncResult.success(issuePage("3", "Delayed third page", "old-4")));
});
await expect
.element(screen.getByRole("button", { name: "Loading…", exact: true }))
.not.toBeInTheDocument();
expect(deliverRefresh).toBeTypeOf("function");
await act(() => deliverRefresh?.());

await expect.element(screen.getByText("Refreshed first page")).toBeVisible();
expect(screen.getByText("Refreshed second page").element()).toBeVisible();
expect(screen.getByText("Old first page").query()).toBeNull();
expect(screen.getByText("Delayed third page").query()).toBeNull();
expect(state.loadPage.mock.calls.map(([request]) => request.input.cursors?.[cursorKey])).toEqual([
"old-2",
"old-3",
"new-2",
]);
});
36 changes: 30 additions & 6 deletions apps/web/src/components/issue/IssuesPage.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import { useAtom, useAtomValue } from "@effect/atom-react";
import {
continueIssuePage,
applyIssueContinuations,
groupIssues,
holdIssuePages,
issueCursorsForHost,
Expand Down Expand Up @@ -36,8 +36,17 @@ import {
UserCheckIcon,
UsersIcon,
} from "lucide-react";
import { Atom } from "effect/reactivity";
import { msg, T, useGT, useMessages, Var } from "gt-react";
import { Fragment, useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react";
import {
Fragment,
useEffect,
useEffectEvent,
useLayoutEffect,
useRef,
useState,
type ReactNode,
} from "react";

import { RefreshIcon } from "~/components/ui/refresh-icon";
import { IssueDetailPanel } from "~/components/issue/IssueDetailPanel";
Expand Down Expand Up @@ -246,8 +255,20 @@ export function IssuesPage() {
{ key: JSON.stringify(targets) },
);

const [pages, setPages] = useState<ReadonlyMap<EnvironmentId, HeldIssuePage>>(new Map());
const held = holdIssuePages(list.answers, pages, JSON.stringify(targets));
const [pagesAtom] = useState(() =>
Atom.make<ReadonlyMap<EnvironmentId, HeldIssuePage>>(new Map()),
);
const [pages, setPages] = useAtom(pagesAtom);
const listKey = JSON.stringify(targets);
const held = holdIssuePages(list.answers, pages, listKey);
const activeListKey = useRef<string | null>(null);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Tracks which listing is mounted when a continuation settles.
useLayoutEffect(() => {
activeListKey.current = listKey;
return () => {
activeListKey.current = null;
};
}, [listKey]);
const loadPage = useAtomCommand(issueEnvironment.listPage, { reportFailure: false });
const readPage = async (environmentId: EnvironmentId, cursors: IssueListCursors) => {
const input = targets.find((target) => target.environmentId === environmentId)?.input;
Expand Down Expand Up @@ -276,8 +297,11 @@ export function IssuesPage() {
setLoadingMore(`${environmentId} ${host}`);
const result = await readPage(environmentId, cursors);
setLoadingMore(null);
if (activeListKey.current !== listKey) return;
setPages((current) =>
new Map(current).set(environmentId, continueIssuePage(page, result, cursors)),
applyIssueContinuations(current, list.readAnswers(), listKey, [
{ environmentId, page, result, cursors },
]),
);
};

Expand Down
5 changes: 4 additions & 1 deletion apps/web/src/state/issues.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,16 @@ const mergedIssueLists = createMergedIssueListAtoms(issueEnvironment, formatEnvi

/** The same listing read across every connected environment, as the pull-request page does. */
export function useIssueList(targets: ReadonlyArray<IssueListTarget>): MergedIssueList & {
readonly readAnswers: () => MergedIssueList["answers"];
readonly refresh: () => void;
readonly reload: () => void;
readonly retry: () => void;
} {
const view = useAtomValue(mergedIssueLists.atom(targets));
const list = mergedIssueLists.atom(targets);
const view = useAtomValue(list);
return {
...view,
readAnswers: () => appAtomRegistry.get(list).answers,
refresh: () => mergedIssueLists.refresh(appAtomRegistry, targets, "manual"),
reload: () => mergedIssueLists.refresh(appAtomRegistry, targets, "background"),
retry: () => mergedIssueLists.retry(appAtomRegistry, targets),
Expand Down
29 changes: 29 additions & 0 deletions packages/client-runtime/src/issueList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,35 @@ export function holdIssuePages(
return next;
}

/** Applies settled continuations against the first pages available at the time of the write. */
export function applyIssueContinuations(
pages: ReadonlyMap<EnvironmentId, HeldIssuePage>,
answers: ReadonlyArray<readonly [EnvironmentId, IssueListResult]>,
list: string,
continuations: ReadonlyArray<{
readonly environmentId: EnvironmentId;
readonly page: HeldIssuePage;
readonly result: IssueListResult | { readonly failure: string };
readonly cursors?: IssueListCursors;
}>,
): ReadonlyMap<EnvironmentId, HeldIssuePage> {
const held = holdIssuePages(answers, pages, list);
let updated: Map<EnvironmentId, HeldIssuePage> | undefined;
for (const { environmentId, page, result, cursors } of continuations) {
const current = held.get(environmentId);
if (
current?.list === page.list &&
current.answer === page.answer &&
current.rereading === null &&
current.nextCursors === page.nextCursors
) {
updated ??= new Map(pages);
updated.set(environmentId, continueIssuePage(current, result, cursors));
}
}
return updated ?? pages;
}

/** Reads the pages "Load more" had reached again under the newer first page, so they show what changed. */
export async function rereadIssuePage(
page: HeldIssuePage & { readonly rereading: IssueListResult },
Expand Down
Loading
Loading