The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { PullRequestRef, PullRequestStack, ThreadPullRequestLink } from "@t3tools/contracts"; |
| 2 | import { msg } from "gt-react"; |
| 3 | |
| 4 | import { m, type MessageResolver } from "~/i18n/messages"; |
| 5 | |
| 6 | /** Saved membership supports navigation, never action head SHAs. */ |
| 7 | export function savedPullRequestStack( |
| 8 | links: ReadonlyArray<ThreadPullRequestLink>, |
| 9 | reference: PullRequestRef, |
| 10 | ): PullRequestStack | null { |
| 11 | const host = reference.host?.toLowerCase(); |
| 12 | if (!host) return null; |
| 13 | const matching = links.filter( |
| 14 | (link) => |
| 15 | link.host.toLowerCase() === host && |
| 16 | link.repository.toLowerCase() === reference.repository.toLowerCase(), |
| 17 | ); |
| 18 | const exact = matching.filter((link) => link.number === reference.number); |
| 19 | const candidates = |
| 20 | exact.length > 0 |
| 21 | ? exact |
| 22 | : matching.filter((link) => |
| 23 | link.stack?.layers.some((layer) => layer.number === reference.number), |
| 24 | ); |
| 25 | const newest = candidates.toSorted( |
| 26 | (a, b) => |
| 27 | Date.parse(b.snapshot?.syncedAt ?? b.linkedAt) - |
| 28 | Date.parse(a.snapshot?.syncedAt ?? a.linkedAt), |
| 29 | )[0]; |
| 30 | const stack = newest?.stack; |
| 31 | if (!stack || !stack.layers.some((layer) => layer.number === reference.number)) return null; |
| 32 | return { |
| 33 | id: stack.id, |
| 34 | number: stack.number, |
| 35 | url: stack.url, |
| 36 | base: stack.base, |
| 37 | layers: stack.layers.map((layer) => { |
| 38 | const snapshot = matching |
| 39 | .filter((link) => link.number === layer.number) |
| 40 | .toSorted( |
| 41 | (a, b) => |
| 42 | Date.parse(b.snapshot?.syncedAt ?? b.linkedAt) - |
| 43 | Date.parse(a.snapshot?.syncedAt ?? a.linkedAt), |
| 44 | )[0]?.snapshot; |
| 45 | return { |
| 46 | ...layer, |
| 47 | ...(snapshot ? { title: snapshot.title, isDraft: snapshot.isDraft } : {}), |
| 48 | }; |
| 49 | }), |
| 50 | }; |
| 51 | } |
| 52 | |
| 53 | export function pullRequestStackView( |
| 54 | query: { |
| 55 | data: PullRequestStack | null; |
| 56 | isSuccess: boolean; |
| 57 | isPending: boolean; |
| 58 | error: string | null; |
| 59 | }, |
| 60 | saved: PullRequestStack | null, |
| 61 | resolve: MessageResolver = m, |
| 62 | ) { |
| 63 | const data = query.isSuccess ? query.data : (query.data ?? saved); |
| 64 | return { |
| 65 | data, |
| 66 | // A settled read: one still out may be showing an answer restored from the device. |
| 67 | isFresh: query.isSuccess && !query.isPending, |
| 68 | notice: |
| 69 | data === null |
| 70 | ? null |
| 71 | : query.error |
| 72 | ? resolve(msg("Stack data may be stale. We couldn’t refresh it.")) |
| 73 | : !query.isSuccess || query.isPending |
| 74 | ? resolve(msg("Refreshing stack… Showing saved data.")) |
| 75 | : null, |
| 76 | }; |
| 77 | } |