Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 36 additions & 13 deletions apps/mobile/src/features/pull-requests/usePullRequestList.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import {
editHeldPullRequestListEntries,
pullRequestHostAnswer,
pullRequestPendingEditsFor,
} from "@t3tools/client-runtime/state/pull-requests";
import { RegistryContext, useAtomMount, useAtomSubscribe, useAtomValue } from "@effect/atom-react";
import { executeAtomQuery, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId, PullRequestDiffStat, PullRequestListInput } from "@t3tools/contracts";
Expand Down Expand Up @@ -31,7 +36,10 @@ type Read = <A>(atom: Atom.Atom<A>) => A;

/** The head the list query holds now, cached or answered. */
function currentHead(read: Read, target: ListTarget) {
return AsyncResult.getOrElse(read(composerPullRequests.list(target)), () => null);
return AsyncResult.getOrElse(
read(pullRequestHostAnswer(composerPullRequests.list(target))),
() => null,
);
}

function currentPages(read: Read, target: ListTarget): PullRequestListPages | null {
Expand All @@ -44,12 +52,23 @@ function currentPages(read: Read, target: ListTarget): PullRequestListPages | nu
const sourcesFamily = Atom.family((key: string) => {
const targets: readonly ListTarget[] = JSON.parse(key);
return Atom.make((get) =>
targets.map((target) => ({
target,
result: get(composerPullRequests.list(target)),
pages: currentPages(get, target),
stats: get(pullRequestListStatsFamily(target.environmentId)),
})),
targets.map((target) => {
const pages = currentPages(get, target);
return {
target,
result: get(composerPullRequests.list(target)),
pages:
pages === null
? null
: {
...pages,
entries: editHeldPullRequestListEntries(target.input, pages.entries, (entry) =>
get(pullRequestPendingEditsFor(target.environmentId, entry)),
),
},
stats: get(pullRequestListStatsFamily(target.environmentId)),
};
}),
);
});

Expand All @@ -71,7 +90,7 @@ async function loadNextPages(
continuations(registry, targets).map(async ({ target, pages, input }) => {
const response = await executeAtomQuery(
registry,
composerPullRequests.list({ ...target, input }),
pullRequestHostAnswer(composerPullRequests.list({ ...target, input })),
{
signal,
refresh: retry,
Expand Down Expand Up @@ -113,11 +132,15 @@ async function refreshHeads(
input: {},
});
if (signal.aborted) return;
const response = await executeAtomQuery(registry, composerPullRequests.list(target), {
refresh: true,
signal,
reportFailure: false,
});
const response = await executeAtomQuery(
registry,
pullRequestHostAnswer(composerPullRequests.list(target)),
{
refresh: true,
signal,
reportFailure: false,
},
);
if (signal.aborted) return;
if (response._tag === "Failure") throw squashAtomCommandFailure(response);
registry.set(
Expand Down
21 changes: 21 additions & 0 deletions apps/mobile/src/state/pull-requests.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import {
createPullRequestEnvironmentAtoms,
editHeldPullRequestListEntries,
createPullRequestStackAtomFamily,
patchPullRequestListEntries,
pullRequestPendingEditsAtom,
} from "@t3tools/client-runtime/state/pull-requests";
import type { EnvironmentId, PullRequestListInput, PullRequestRef } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
Expand Down Expand Up @@ -66,11 +68,30 @@ export const composerPullRequests = createPullRequestEnvironmentAtoms(connection
pages.entries,
target.input,
reply,
registry.get(pullRequestPendingEditsAtom(target.environmentId)),
);
return entries === "refresh" || entries === pages.entries ? pages : { ...pages, entries };
});
}
}),
acceptedEdit: (target, edit, registry) =>
Effect.sync(() => {
for (const atom of registry.getNodes().keys()) {
const listing =
typeof atom === "string" ? undefined : pullRequestListPagesTargets.get(atom);
if (listing === undefined || listing[0] !== target.environmentId) continue;
registry.update(atom as Atom.Writable<PullRequestListPages | null>, (pages) => {
if (pages === null) return pages;
const entries = editHeldPullRequestListEntries(
listing[1],
pages.entries,
() => [edit],
registry.get(pullRequestPendingEditsAtom(target.environmentId)),
);
return entries === pages.entries ? pages : { ...pages, entries };
});
}
}),
// 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) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1650,7 +1650,6 @@ export function PullRequestDetailPanel({
pullRequestKey={pullRequestKey}
detail={detail}
canWriteSourceControl={canWriteSourceControl}
onSaved={refreshDetail}
/>
}
author={
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ export function PullRequestLabelPicker({
}) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const [pending, setPending] = useState<string | null>(null);

const candidatesQuery = useEnvironmentQuery(
open ? pullRequestEnvironment.labelCandidates({ environmentId, input: reference }) : null,
Expand All @@ -45,14 +44,12 @@ export function PullRequestLabelPicker({
matches(entry, query),
);

// Each change shows at once and queues behind the one before it on the host.
const toggle = async (candidate: PullRequestLabelCandidate) => {
if (pending !== null) return;
setPending(candidate.name);
const result = await setLabels({
environmentId,
input: { ...reference, labels: [candidate.name], applied: !candidate.isApplied },
});
setPending(null);
if (result._tag === "Failure") {
toastManager.add({
type: "error",
Expand Down Expand Up @@ -88,7 +85,7 @@ export function PullRequestLabelPicker({
truncated={candidatesQuery.data?.truncated === true}
truncatedLabel="This repository has more labels than are listed here. Apply the rest on the host."
candidateKey={(candidate) => candidate.name}
disabled={pending !== null}
disabled={false}
onSelect={(candidate) => void toggle(candidate)}
>
{(candidate) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,12 @@ export function PullRequestTitleEditor({
pullRequestKey,
detail,
canWriteSourceControl,
onSaved,
}: {
environmentId: EnvironmentId;
reference: PullRequestRef;
pullRequestKey: string;
detail: PullRequestDetail;
canWriteSourceControl: boolean;
onSaved: () => void;
}) {
const update = useAtomCommand(pullRequestEnvironment.update, { reportFailure: false });
const [titleScope, setTitleScope] = useState<{
Expand All @@ -49,9 +47,12 @@ export function PullRequestTitleEditor({
return;
}
setTitleSaving(true);
// The new title shows while the host takes it, so the editor closes at once.
setTitleScope(null);
const result = await update({ environmentId, input: { ...reference, title } });
setTitleSaving(false);
if (result._tag === "Failure") {
setTitleScope({ pullRequestKey, text: title });
toastManager.add({
type: "error",
title: "The title could not be saved",
Expand All @@ -60,10 +61,7 @@ export function PullRequestTitleEditor({
"The host refused the new title.",
),
});
return;
}
setTitleScope(null);
onSaved();
};

if (titleDraft === null) {
Expand Down
80 changes: 67 additions & 13 deletions apps/web/src/components/pullRequest/PullRequestsPage.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { heldPullRequestListEntriesAtom } from "@t3tools/client-runtime/state/pull-requests";
import { AsyncResult, Atom } from "effect/reactivity";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import { applyPullRequestDraftFilterChange } from "@t3tools/client-runtime/pull-request-query";
import { Spinner } from "~/components/ui/spinner";
Expand Down Expand Up @@ -104,7 +106,7 @@ import {
import { useSidebarProjectGroups } from "~/hooks/useSidebarProjectGroups";
import {
pullRequestEnvironment,
usePullRequestList,
usePullRequestHostList,
usePullRequestListStats,
restoredPullRequestList,
usePullRequestTurnRefreshes,
Expand Down Expand Up @@ -147,6 +149,35 @@ const EMPTY_PREVIEW_SESSIONS = {};
const EMPTY_PREVIEW_DESKTOP_STATE = {};
const EMPTY_TERMINAL_LABELS = new Map<string, string>();
const EMPTY_PENDING_SURFACES = new Set<string>();
const heldRowReaders = new WeakMap<
EnvironmentPullRequestEntry,
Map<string, ReturnType<typeof heldPullRequestListEntriesAtom<EnvironmentPullRequestEntry>>>
>();

function usePendingListEntries(
input: PullRequestListInput,
entries: ReadonlyArray<EnvironmentPullRequestEntry> | undefined,
) {
const key = JSON.stringify(input);
return useAtomValue(
Atom.make((get) =>
(entries ?? []).flatMap((entry) => {
let readers = heldRowReaders.get(entry);
if (readers === undefined) {
readers = new Map();
heldRowReaders.set(entry, readers);
}
let reader = readers.get(key);
if (reader === undefined) {
reader = heldPullRequestListEntriesAtom(entry.environmentId, input, [entry]);
readers.set(key, reader);
}
return AsyncResult.getOrElse(get(reader), () => []);
}),
),
);
}

export function PullRequestsPage() {
const search = useSearch({ from: "/_chat/pull-requests" });
const sort = search.sort ?? "ready";
Expand Down Expand Up @@ -341,7 +372,7 @@ export function PullRequestsPage() {
];
});
const listTargets = listTargetsFor(environmentQueries);
const listQuery = usePullRequestList(listTargets);
const listQuery = usePullRequestHostList(listTargets);

/**
* Kept as its own read rather than remembered from an earlier answer because an answer cannot
Expand All @@ -362,7 +393,7 @@ export function PullRequestsPage() {
} satisfies PullRequestListInput,
}));
const baselineTargets = baselineTargetsFor(environmentQueries);
const baselineQuery = usePullRequestList(baselineTargets);
const baselineQuery = usePullRequestHostList(baselineTargets);
const observedHosts = rememberPullRequestHosts(
rememberPullRequestHosts(hostReads, baselineQuery.observations),
listQuery.observations,
Expand All @@ -387,7 +418,7 @@ export function PullRequestsPage() {
} satisfies PullRequestListInput,
}));
})();
const facetQuery = usePullRequestList(facetTargets);
const facetQuery = usePullRequestHostList(facetTargets);
const filterOptionScope = environmentQueries.map(({ environmentId, projectIds }) => ({
environmentId,
input: {
Expand Down Expand Up @@ -423,8 +454,8 @@ export function PullRequestsPage() {
}));
return { authored: targetsFor("authored"), reviewing: targetsFor("reviewing") };
})();
const authoredQuery = usePullRequestList(partitionTargets.authored);
const reviewingQuery = usePullRequestList(partitionTargets.reviewing);
const authoredQuery = usePullRequestHostList(partitionTargets.authored);
const reviewingQuery = usePullRequestHostList(partitionTargets.reviewing);
const invalidate = useAtomCommand(pullRequestEnvironment.invalidate, { reportFailure: false });
const [detailRefreshToken, setDetailRefreshToken] = useState(0);
const [invalidating, setInvalidating] = useState(false);
Expand Down Expand Up @@ -703,6 +734,23 @@ export function PullRequestsPage() {
search.state,
);

const heldEntries = ordered?.key === filterKey ? ordered.entries : (listData?.entries ?? []);
const overlayInput = { state: search.state, filters };
const shownEntries = usePendingListEntries(overlayInput, heldEntries);
const shownBaseline = usePendingListEntries(
overlayInput,
typedParsed.filters.checks === undefined ? baselineQuery.data?.entries : undefined,
);
const shownAuthored = usePendingListEntries(
overlayInput,
partitionsWanted ? authoredQuery.data?.entries : undefined,
);
const shownReviewing = usePendingListEntries(
overlayInput,
partitionsWanted ? reviewingQuery.data?.entries : undefined,
);
const shownHeldAuthored = usePendingListEntries(overlayInput, heldPartitions?.authored);
const shownHeldReviewing = usePendingListEntries(overlayInput, heldPartitions?.reviewing);
const scrollRef = useRef<HTMLDivElement>(null);
const {
entries,
Expand All @@ -711,9 +759,12 @@ export function PullRequestsPage() {
entriesByStatsKey,
heldPullRequestsBySurface,
} = pullRequestGroups({
known: ordered?.key === filterKey ? ordered.entries : (listData?.entries ?? []),
known: shownEntries,
// The baseline was read without typed qualifiers, and rows cannot be checked for `checks:`.
baseline: typedParsed.filters.checks === undefined ? baselineQuery.data?.entries : undefined,
baseline:
typedParsed.filters.checks === undefined && baselineQuery.data !== null
? shownBaseline
: undefined,
providers: baselineQuery.data?.providers ?? listData?.providers ?? [],
viewers,
involvement: search.involvement,
Expand All @@ -723,11 +774,14 @@ export function PullRequestsPage() {
answeredLocally: querySettled && !showingCarried,
baselineEmpty,
held:
loaded !== null && loaded.environmentKey === environmentKey && loaded.scope === scopeKey
? loaded.partitions
: undefined,
authored: partitionsWanted ? authoredQuery.data?.entries : undefined,
reviewing: partitionsWanted ? reviewingQuery.data?.entries : undefined,
heldPartitions === undefined
? undefined
: {
authored: shownHeldAuthored,
reviewing: shownHeldReviewing,
},
authored: partitionsWanted && authoredQuery.data !== null ? shownAuthored : undefined,
reviewing: partitionsWanted && reviewingQuery.data !== null ? shownReviewing : undefined,
partitionsWanted,
});

Expand Down
11 changes: 9 additions & 2 deletions apps/web/src/components/pullRequest/usePullRequestDetail.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import { resolvePullRequestDetailChecks } from "@t3tools/client-runtime/pull-request-checks";
import { pullRequestPendingEditsFor } from "@t3tools/client-runtime/state/pull-requests";
import {
AuthSourceControlWriteScope,
type EnvironmentId,
Expand All @@ -13,6 +15,7 @@ import { useServerConfigs } from "~/state/entities";
import { useEnvironmentQuery } from "~/state/query";
import { useEnvironmentScope } from "~/state/session";
import {
newestDisplayedPullRequestSummary,
newestPullRequestSummary,
pullRequestEnvironment,
pullRequestListEntryToSummary,
Expand Down Expand Up @@ -105,6 +108,7 @@ export function usePullRequestDetail(
setCachedDetail(detailQuery.data);
}
const observedSummary = useSharedPullRequestSummary(environmentId, reference);
const pendingEdits = useAtomValue(pullRequestPendingEditsFor(environmentId, reference));
const activity = activityQuery.data;
const resolvedCoreDetail = resolveDisplayedPullRequestDetail({
live: liveDetail,
Expand All @@ -115,9 +119,12 @@ export function usePullRequestDetail(
// `detail` would cost it its cache scope.
const listSummary = listEntry === null ? null : pullRequestListEntryToSummary(listEntry);
// The row can come from the page's stored snapshot, which no answer has published yet.
const sharedSummary = newestPullRequestSummary(
const sharedSummary = newestDisplayedPullRequestSummary(
resolvedCoreDetail,
newestPullRequestSummary(observedSummary, listSummary),
liveDetail === null,
newestPullRequestSummary(listSummary, observedSummary),
reference,
pendingEdits,
);
const coreDetail =
resolvedCoreDetail === null || sharedSummary === null || sharedSummary === resolvedCoreDetail
Expand Down
Loading
Loading