diff --git a/apps/mobile/src/features/pull-requests/PullRequestStackHeaderRow.tsx b/apps/mobile/src/features/pull-requests/PullRequestStackHeaderRow.tsx new file mode 100644 index 0000000000000..cbf5d460d18cf --- /dev/null +++ b/apps/mobile/src/features/pull-requests/PullRequestStackHeaderRow.tsx @@ -0,0 +1,69 @@ +import type { PullRequestStackMembership } from "@t3tools/contracts"; +import { useGT } from "gt-react-native"; +import { Pressable, View } from "react-native"; + +import { AppText as Text } from "../../components/ui/AppText"; +import { SymbolView } from "../../components/ui/AppSymbol"; +import { cn } from "../../lib/cn"; +import { PullRequestGlyph } from "./pullRequestGlyphs"; + +/** Heads two or more PRs from one stack; tapping folds them. */ +export function PullRequestStackHeaderRow(props: { + readonly membership: PullRequestStackMembership; + readonly shown: number; + readonly open: boolean; + readonly sidebar: boolean; + readonly onToggle: () => void; + /** Opens a PR in the stack, whose page lists every layer. */ + readonly onShowAll: () => void; +}) { + const gt = useGT(); + const muted = props.sidebar ? "text-drawer-foreground-muted" : "text-foreground-muted"; + const tint = props.sidebar ? "accent-drawer-foreground-muted" : "accent-foreground-muted"; + const hidden = props.membership.size - props.shown; + return ( + + + + + + {gt("Stack into {base}", { base: props.membership.base })} + + + {gt("{shown} of {size} here", { shown: props.shown, size: props.membership.size })} + + + {hidden > 0 ? ( + + ) : null} + + ); +} diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index 515234ca036d8..13f80f93c7366 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -9,7 +9,8 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react-native"; import { useNavigation } from "@react-navigation/native"; import { useGT } from "gt-react-native"; import { use, useMemo, useRef, useState, type ReactNode } from "react"; -import { useAtomValue } from "@effect/atom-react"; +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { AsyncResult } from "effect/reactivity"; import { Keyboard, Platform, Pressable, View } from "react-native"; import { RefreshControl } from "../../components/ui/RefreshControl"; import { NativeScrollView } from "../../native/NativeScrollViewMarker"; @@ -25,6 +26,15 @@ import { useWorkspaceState } from "../../state/workspace"; import { useProjects } from "../../state/entities"; import { environmentServerConfigsAtom } from "../../state/server"; import { PullRequestListRow } from "./PullRequestListRow"; +import { PullRequestStackHeaderRow } from "./PullRequestStackHeaderRow"; +import { + pullRequestListItemEntries, + pullRequestListItemKey, + pullRequestListItems, + pullRequestListItemsAreEqual, + type PullRequestListItem, +} from "./pullRequestStackItems"; +import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; import { liveReviewKey, useLiveReviews } from "./review/useLiveReviews"; import { PullRequestListFilters, @@ -40,7 +50,6 @@ import { filterPullRequestList, pullRequestListFacets, pullRequestListInput, - pullRequestListRowsAreEqual, scopedPullRequestListKey as pullRequestKey, type EnvironmentPullRequestListEntry, withoutScratchProjectScope, @@ -103,6 +112,8 @@ export function PullRequestsScreen( const workspace = useWorkspaceTabs()!; const { environments } = useWorkspaceState(); const configs = useAtomValue(environmentServerConfigsAtom); + const preferencesResult = useAtomValue(mobilePreferencesAtom); + const savePreferences = useAtomSet(updateMobilePreferencesAtom); const insets = useSafeAreaInsets(); const contentTopInset = useContentTopInset(); // UIKit insets the list by its column's safe area, which this context can report as 0. @@ -269,32 +280,70 @@ export function PullRequestsScreen( labelColors, }), }); - const renderPullRequest = ({ item }: { readonly item: EnvironmentPullRequestListEntry }) => ( - - ); + const collapsedStackList = AsyncResult.isSuccess(preferencesResult) + ? (preferencesResult.value.pullRequestCollapsedStacks ?? []) + : []; + const listItems = pullRequestListItems(entries, new Set(collapsedStackList), selectedKey); + // Builds from the stored list, not this render's, like Home's folded projects. + const toggleStack = (stackKey: string) => + savePreferences({ + transform: (current) => { + const next = new Set(current.pullRequestCollapsedStacks ?? []); + if (!next.delete(stackKey)) next.add(stackKey); + return { pullRequestCollapsedStacks: [...next].slice(-200) }; + }, + }); + const renderPullRequest = ({ item: row }: { readonly item: PullRequestListItem }) => { + if (row.kind === "stack") { + return ( + toggleStack(row.key)} + onShowAll={() => selectPullRequest(row.entries[0]!)} + /> + ); + } + const item = row.entry; + const pullRequestRow = ( + + ); + return row.nested ? {pullRequestRow} : pullRequestRow; + }; const list = ( void result.loadMore()} onEndReachedThreshold={0.5} - onViewableItemsChanged={result.onViewableItemsChanged} + onViewableItemsChanged={({ viewableItems }) => + result.onViewableItemsChanged({ + viewableItems: viewableItems.flatMap((token) => + pullRequestListItemEntries(token.item).map((item) => ({ + item, + isViewable: token.isViewable, + })), + ), + }) + } refreshControl={ + ({ + environmentId: "env-1", + projectId: "project-1", + host: "github.com", + repository: "acme/app", + number, + ...(position === undefined ? {} : { stack: { number: 7, position, size: 4, base: "main" } }), + }) as unknown as EnvironmentPullRequestListEntry; + +const shape = (items: ReturnType) => + items.map((item) => + item.kind === "stack" + ? `stack:${item.open ? "open" : "folded"}` + : `${item.nested ? " " : ""}#${item.entry.number}`, + ); + +describe("pullRequestListItems", () => { + const entries = [entry(12, 2), entry(5), entry(11, 1)]; + const stackKey = "env-1|github.com|acme/app|7"; + + it("puts a stack's PRs under one open header at the first one's spot", () => { + expect(shape(pullRequestListItems(entries, new Set(), undefined))).toEqual([ + "stack:open", + " #11", + " #12", + "#5", + ]); + }); + + it("keeps only the header of a folded stack", () => { + expect(shape(pullRequestListItems(entries, new Set([stackKey]), undefined))).toEqual([ + "stack:folded", + "#5", + ]); + }); + + it("opens a folded stack that holds the selected PR", () => { + const selected = scopedPullRequestListKey(entries[0]!); + expect(shape(pullRequestListItems(entries, new Set([stackKey]), selected))).toEqual([ + "stack:open", + " #11", + " #12", + "#5", + ]); + }); +}); diff --git a/apps/mobile/src/features/pull-requests/pullRequestStackItems.ts b/apps/mobile/src/features/pull-requests/pullRequestStackItems.ts new file mode 100644 index 0000000000000..70b41510cf5cc --- /dev/null +++ b/apps/mobile/src/features/pull-requests/pullRequestStackItems.ts @@ -0,0 +1,74 @@ +import { nestPullRequestStacks } from "@t3tools/client-runtime/pull-request-stack-nesting"; +import type { PullRequestStackMembership } from "@t3tools/contracts"; + +import { + pullRequestListRowsAreEqual, + scopedPullRequestListKey, + type EnvironmentPullRequestListEntry, +} from "./pullRequestList"; + +/** One row of the PR list: a PR, or the header of two or more PRs from one stack. */ +export type PullRequestListItem = + | { + readonly kind: "entry"; + readonly entry: EnvironmentPullRequestListEntry; + /** Shown under a stack header. */ + readonly nested: boolean; + } + | { + readonly kind: "stack"; + readonly key: string; + readonly membership: PullRequestStackMembership; + /** Bottom layer first. */ + readonly entries: ReadonlyArray; + readonly open: boolean; + }; + +/** Flattens nested stacks for a flat list; a folded stack keeps only its header. */ +export function pullRequestListItems( + entries: ReadonlyArray, + collapsedStacks: ReadonlySet, + selectedKey: string | null | undefined, +): ReadonlyArray { + return nestPullRequestStacks(entries).flatMap((row): PullRequestListItem[] => { + if (row.kind === "entry") return [{ kind: "entry", entry: row.entry, nested: false }]; + // The selected PR never hides inside a folded stack. + const open = + !collapsedStacks.has(row.key) || + row.entries.some((entry) => scopedPullRequestListKey(entry) === selectedKey); + return [ + { kind: "stack", key: row.key, membership: row.membership, entries: row.entries, open }, + ...(open + ? row.entries.map((entry) => ({ kind: "entry" as const, entry, nested: true })) + : []), + ]; + }); +} + +export const pullRequestListItemKey = (item: PullRequestListItem) => + item.kind === "stack" ? `stack:${item.key}` : scopedPullRequestListKey(item.entry); + +export function pullRequestListItemsAreEqual( + previous: PullRequestListItem, + next: PullRequestListItem, +): boolean { + if (previous.kind === "entry" && next.kind === "entry") { + return ( + previous.nested === next.nested && pullRequestListRowsAreEqual(previous.entry, next.entry) + ); + } + if (previous.kind === "stack" && next.kind === "stack") { + return ( + previous.key === next.key && + previous.open === next.open && + previous.membership.size === next.membership.size && + previous.membership.base === next.membership.base && + previous.entries.length === next.entries.length + ); + } + return false; +} + +/** The PRs a list row shows, for visibility tracking. */ +export const pullRequestListItemEntries = (item: PullRequestListItem) => + item.kind === "entry" ? [item.entry] : []; diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 21f9893716155..9edeb723a841d 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -2912,6 +2912,11 @@ }, ". Öffne eine Ebene, um sie zu prüfen oder den Stack bis zu dieser Ebene zu mergen." ], + "7bbdd8496e6dbd8a": "Stack into {base}, {shown} of {size} here", + "f003c65939c9c8f0": "Stack into {base}", + "0034f65ef4b6491d": "{shown} of {size} here", + "e31342b1da7c0627": "Show the {count} other layers of this stack", + "98515f1201b25dcc": "+{count} more", "7d50c5c18ba726fa": "{term, select, mr {Status des Merge Requests, {status}} cr {Status der Änderungsanfrage, {status}} other {Status des Pull Requests, {status}}}", "25019c947d3082dc": "{term, select, mr {Status des Merge Requests} cr {Status der Änderungsanfrage} other {Status des Pull Requests}}", "cdfe7771384370e8": "{term, select, mr {Einen neuen Merge Request öffnen, der diese Änderungen rückgängig macht?} cr {Eine neue Änderungsanfrage öffnen, die diese Änderungen rückgängig macht?} other {Einen neuen Pull Request öffnen, der diese Änderungen rückgängig macht?}}", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index da3b03961ad58..42b43cafde5fa 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -2914,6 +2914,11 @@ }, ". Open a layer to review it or merge the stack through that layer." ], + "7bbdd8496e6dbd8a": "Stack into {base}, {shown} of {size} here", + "f003c65939c9c8f0": "Stack into {base}", + "0034f65ef4b6491d": "{shown} of {size} here", + "e31342b1da7c0627": "Show the {count} other layers of this stack", + "98515f1201b25dcc": "+{count} more", "7d50c5c18ba726fa": "{term, select, mr {Merge request} cr {Change request} other {Pull request}} status, {status}", "25019c947d3082dc": "{term, select, mr {Merge request} cr {Change request} other {Pull request}} status", "cdfe7771384370e8": "Open a new {term, select, mr {merge request} cr {change request} other {pull request}} that reverses these changes?", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 4f34183a7cd93..54e7d31edf8c3 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -2908,6 +2908,11 @@ }, ". Abre una capa para revisarla o fusionar la pila hasta esa capa." ], + "7bbdd8496e6dbd8a": "Stack into {base}, {shown} of {size} here", + "f003c65939c9c8f0": "Stack into {base}", + "0034f65ef4b6491d": "{shown} of {size} here", + "e31342b1da7c0627": "Show the {count} other layers of this stack", + "98515f1201b25dcc": "+{count} more", "7d50c5c18ba726fa": "Estado de la {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}}, {status}", "25019c947d3082dc": "Estado de la {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}}", "cdfe7771384370e8": "¿Abrir una {term, select, mr {merge request} cr {solicitud de cambios} other {pull request}} nueva que revierta estos cambios?", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index eae4cd38b9684..4bbadbd0350ae 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -2908,6 +2908,11 @@ }, ". Ouvrez une couche pour la relire ou fusionner la pile jusqu’à cette couche." ], + "7bbdd8496e6dbd8a": "Stack into {base}, {shown} of {size} here", + "f003c65939c9c8f0": "Stack into {base}", + "0034f65ef4b6491d": "{shown} of {size} here", + "e31342b1da7c0627": "Show the {count} other layers of this stack", + "98515f1201b25dcc": "+{count} more", "7d50c5c18ba726fa": "Statut de la {term, select, mr {merge request} cr {demande de modification} other {pull request}}, {status}", "25019c947d3082dc": "Statut de la {term, select, mr {merge request} cr {demande de modification} other {pull request}}", "cdfe7771384370e8": "Ouvrir une nouvelle {term, select, mr {merge request} cr {demande de modification} other {pull request}} qui annule ces modifications ?", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index c1dac6a12af9f..6bc4897fe3d75 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -2905,6 +2905,11 @@ }, "。レイヤーを開いてレビューするか、そのレイヤーまでスタックをマージしてください。" ], + "7bbdd8496e6dbd8a": "Stack into {base}, {shown} of {size} here", + "f003c65939c9c8f0": "Stack into {base}", + "0034f65ef4b6491d": "{shown} of {size} here", + "e31342b1da7c0627": "Show the {count} other layers of this stack", + "98515f1201b25dcc": "+{count} more", "7d50c5c18ba726fa": "{term, select, mr {マージリクエストのステータス、{status}} cr {変更リクエストのステータス、{status}} other {プルリクエストのステータス、{status}}}", "25019c947d3082dc": "{term, select, mr {マージリクエストのステータス} cr {変更リクエストのステータス} other {プルリクエストのステータス}}", "cdfe7771384370e8": "{term, select, mr {これらの変更を元に戻す新しいマージリクエストを開きますか?} cr {これらの変更を元に戻す新しい変更リクエストを開きますか?} other {これらの変更を元に戻す新しいプルリクエストを開きますか?}}", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 633c68e8fcb7d..223c9709a5367 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -2909,6 +2909,11 @@ }, ". 레이어를 열어 검토하거나 해당 레이어까지 스택을 병합하세요." ], + "7bbdd8496e6dbd8a": "Stack into {base}, {shown} of {size} here", + "f003c65939c9c8f0": "Stack into {base}", + "0034f65ef4b6491d": "{shown} of {size} here", + "e31342b1da7c0627": "Show the {count} other layers of this stack", + "98515f1201b25dcc": "+{count} more", "7d50c5c18ba726fa": "{term, select, mr {병합 요청} cr {변경 요청} other {풀 리퀘스트}} 상태, {status}", "25019c947d3082dc": "{term, select, mr {병합 요청} cr {변경 요청} other {풀 리퀘스트}} 상태", "cdfe7771384370e8": "이 변경 사항을 되돌리는 새 {term, select, mr {병합 요청을} cr {변경 요청을} other {풀 리퀘스트를}} 열까요?", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index db6ff3d8b6cbc..bffe424659b80 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -2908,6 +2908,11 @@ }, ". Abra uma camada para revisá-la ou mesclar a pilha até essa camada." ], + "7bbdd8496e6dbd8a": "Stack into {base}, {shown} of {size} here", + "f003c65939c9c8f0": "Stack into {base}", + "0034f65ef4b6491d": "{shown} of {size} here", + "e31342b1da7c0627": "Show the {count} other layers of this stack", + "98515f1201b25dcc": "+{count} more", "7d50c5c18ba726fa": "Status {term, select, mr {do merge request} cr {da solicitação de alteração} other {do pull request}}, {status}", "25019c947d3082dc": "Status {term, select, mr {do merge request} cr {da solicitação de alteração} other {do pull request}}", "cdfe7771384370e8": "Abrir {term, select, mr {um novo merge request} cr {uma nova solicitação de alteração} other {um novo pull request}} que reverte essas alterações?", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index fb21fca3ba695..1d248c32a920e 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -2962,6 +2962,11 @@ }, ". Откройте слой, чтобы провести ревью, или слейте стек до этого слоя." ], + "7bbdd8496e6dbd8a": "Stack into {base}, {shown} of {size} here", + "f003c65939c9c8f0": "Stack into {base}", + "0034f65ef4b6491d": "{shown} of {size} here", + "e31342b1da7c0627": "Show the {count} other layers of this stack", + "98515f1201b25dcc": "+{count} more", "7d50c5c18ba726fa": "{term, select, mr {Статус мерж-реквеста} cr {Статус запроса на изменение} other {Статус пул-реквеста}}: {status}", "25019c947d3082dc": "{term, select, mr {Статус мерж-реквеста} cr {Статус запроса на изменение} other {Статус пул-реквеста}}", "cdfe7771384370e8": "{term, select, mr {Открыть новый мерж-реквест, отменяющий эти изменения?} cr {Открыть новый запрос на изменение, отменяющий эти изменения?} other {Открыть новый пул-реквест, отменяющий эти изменения?}}", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 479dce8b2ff41..ae4ec57e23e83 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -2914,6 +2914,11 @@ }, ". Öppna ett lager för att granska det eller merga stacken till och med det lagret." ], + "7bbdd8496e6dbd8a": "Stack into {base}, {shown} of {size} here", + "f003c65939c9c8f0": "Stack into {base}", + "0034f65ef4b6491d": "{shown} of {size} here", + "e31342b1da7c0627": "Show the {count} other layers of this stack", + "98515f1201b25dcc": "+{count} more", "7d50c5c18ba726fa": "Status för {term, select, mr {merge request} cr {ändringsbegäran} other {pull request}}, {status}", "25019c947d3082dc": "Status för {term, select, mr {merge request} cr {ändringsbegäran} other {pull request}}", "cdfe7771384370e8": "Öppna en ny {term, select, mr {merge request} cr {ändringsbegäran} other {pull request}} som återställer de här ändringarna?", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 00e643e3e2016..a01973f4242d4 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -2909,6 +2909,11 @@ }, "。打开某一层以审查,或将堆叠合并到该层为止。" ], + "7bbdd8496e6dbd8a": "Stack into {base}, {shown} of {size} here", + "f003c65939c9c8f0": "Stack into {base}", + "0034f65ef4b6491d": "{shown} of {size} here", + "e31342b1da7c0627": "Show the {count} other layers of this stack", + "98515f1201b25dcc": "+{count} more", "7d50c5c18ba726fa": "{term, select, mr {MR} cr {change request} other {PR}} 状态,{status}", "25019c947d3082dc": "{term, select, mr {MR} cr {change request} other {PR}} 状态", "cdfe7771384370e8": "要新建一个撤销这些更改的 {term, select, mr {merge request} cr {change request} other {pull request}} 吗?", diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts index 57ffacc943fd0..6938167455eed 100644 --- a/apps/mobile/src/persistence/mobile-preferences.ts +++ b/apps/mobile/src/persistence/mobile-preferences.ts @@ -186,6 +186,8 @@ export interface Preferences { readonly threadListRowOrder?: ReadonlyArray; /** Project scope keys whose Home section is folded to its heading. */ readonly threadListCollapsedProjects?: ReadonlyArray; + /** Pull request stack keys whose rows are folded under their header. */ + readonly pullRequestCollapsedStacks?: ReadonlyArray; readonly useLastProjectForNewThreads?: boolean; readonly lastThreadProject?: typeof ThreadProject.Type; readonly modelFavorites?: ReadonlyArray<{ @@ -283,6 +285,7 @@ export function sanitizePreferences(parsed: Preferences): Preferences { threadListProjectOrder?: ReadonlyArray; threadListRowOrder?: ReadonlyArray; threadListCollapsedProjects?: ReadonlyArray; + pullRequestCollapsedStacks?: ReadonlyArray; useLastProjectForNewThreads?: boolean; lastThreadProject?: typeof ThreadProject.Type; modelFavorites?: Preferences["modelFavorites"]; @@ -434,6 +437,7 @@ export function sanitizePreferences(parsed: Preferences): Preferences { "threadListProjectOrder", "threadListRowOrder", "threadListCollapsedProjects", + "pullRequestCollapsedStacks", ] as const) { const value: unknown = parsed[key]; if (Array.isArray(value)) { diff --git a/apps/web/src/components/pullRequest/PullRequestListGroups.tsx b/apps/web/src/components/pullRequest/PullRequestListGroups.tsx index 0bc1bdf15981d..b461feddbaa02 100644 --- a/apps/web/src/components/pullRequest/PullRequestListGroups.tsx +++ b/apps/web/src/components/pullRequest/PullRequestListGroups.tsx @@ -8,8 +8,12 @@ import { type LucideIcon, } from "lucide-react"; import { useMessages } from "gt-react"; +import { nestPullRequestStacks } from "@t3tools/client-runtime/pull-request-stack-nesting"; +import * as Schema from "effect/Schema"; import { useDeferredValue, type RefCallback } from "react"; +import { useLocalStorage } from "~/hooks/useLocalStorage"; + import { cn } from "~/lib/utils"; import { Separator } from "../ui/separator"; import { @@ -19,6 +23,7 @@ import { type PullRequestDisplayGroup, } from "./pullRequestList.logic"; import { PullRequestRow, type PullRequestRowTarget } from "./PullRequestRow"; +import { PullRequestStackGroup } from "./PullRequestStackGroup"; import { PullRequestSpeedModeProvider, type PullRequestSpeedActionResult, @@ -31,6 +36,9 @@ const GROUP_ICONS: Record = { }; const MATCHED_ELSEWHERE_SCORE = 10; +const COLLAPSED_STACKS_KEY = "t3.pullRequests.collapsedStacks"; +const COLLAPSED_STACKS_LIMIT = 200; +const CollapsedStacks = Schema.Array(Schema.String); const FIRST_PAINT_ROWS = 24; function firstPaintGroups }>( @@ -104,6 +112,47 @@ export function PullRequestListGroups({ // opening the page from blocking on the whole list. const shownGroups = useDeferredValue(groups, firstPaintGroups(groups)); const counts = new Map(groups.map((group) => [group.key, group.entries.length])); + const [collapsedStacks, setCollapsedStacks] = useLocalStorage< + ReadonlyArray, + ReadonlyArray + >(COLLAPSED_STACKS_KEY, [], CollapsedStacks); + const toggleStack = (key: string) => + setCollapsedStacks((current) => + current.includes(key) + ? current.filter((collapsed) => collapsed !== key) + : [...current, key].slice(-COLLAPSED_STACKS_LIMIT), + ); + const isSelected = (entry: EnvironmentPullRequestEntry) => + selected?.environmentId === entry.environmentId && + selected.repository === entry.repository && + selected.host?.toLowerCase() === entry.host.toLowerCase() && + selected.number === entry.number; + const renderRow = (entry: EnvironmentPullRequestEntry) => { + const entryKey = pullRequestEntryKey(entry); + const environmentLabel = environmentLabels?.get(entry.environmentId); + return ( + 0 && scorePullRequestMatch(entry, query) <= MATCHED_ELSEWHERE_SCORE + } + selected={isSelected(entry)} + onSelect={onSelect} + onIntent={onIntent} + hostActions={hostActionsOf(entry)} + onActed={onActed} + closing={closingKeys.has(entryKey)} + sweeping={sweepingKeys.has(entryKey)} + onCloseSweepStart={onCloseSweepStart} + /> + ); + }; return (
0 && "**:pointer-events-none")}> @@ -115,38 +164,23 @@ export function PullRequestListGroups({ count={counts.get(group.key) ?? group.entries.length} /> ) : null} - {group.entries.map((entry) => { - const entryKey = pullRequestEntryKey(entry); - const environmentLabel = environmentLabels?.get(entry.environmentId); - return ( - 0 && - scorePullRequestMatch(entry, query) <= MATCHED_ELSEWHERE_SCORE - } - selected={ - selected?.environmentId === entry.environmentId && - selected.repository === entry.repository && - selected.host?.toLowerCase() === entry.host.toLowerCase() && - selected.number === entry.number - } + {nestPullRequestStacks(group.entries).map((row) => + row.kind === "entry" ? ( + renderRow(row.entry) + ) : ( + toggleStack(row.key)} onSelect={onSelect} - onIntent={onIntent} - hostActions={hostActionsOf(entry)} - onActed={onActed} - closing={closingKeys.has(entryKey)} - sweeping={sweepingKeys.has(entryKey)} - onCloseSweepStart={onCloseSweepStart} - /> - ); - })} + > + {row.entries.map(renderRow)} + + ), + )}
))} diff --git a/apps/web/src/components/pullRequest/PullRequestStackGroup.tsx b/apps/web/src/components/pullRequest/PullRequestStackGroup.tsx new file mode 100644 index 0000000000000..b98e54441489a --- /dev/null +++ b/apps/web/src/components/pullRequest/PullRequestStackGroup.tsx @@ -0,0 +1,87 @@ +import type { PullRequestStackMembership } from "@t3tools/contracts"; +import { T, useGT, Var } from "gt-react"; +import { ChevronRightIcon } from "lucide-react"; +import type { ReactNode } from "react"; + +import { cn } from "~/lib/utils"; +import type { EnvironmentPullRequestEntry } from "./pullRequestList.logic"; +import { PullRequestGlyph } from "./pullRequestIcons"; +import type { PullRequestRowTarget } from "./PullRequestRow"; +import { PullRequestStackPopover } from "./PullRequestStackPopover"; + +/** Two or more rows of one stack, under a header that folds them away. */ +export function PullRequestStackGroup({ + membership, + entries, + open, + onToggle, + onSelect, + children, +}: { + membership: PullRequestStackMembership; + /** Bottom layer first. */ + entries: ReadonlyArray; + open: boolean; + onToggle: () => void; + onSelect: (target: PullRequestRowTarget) => void; + /** The member rows, in `entries` order. */ + children: ReactNode; +}) { + const gt = useGT(); + const first = entries[0]!; + const hidden = membership.size - entries.length; + return ( +
+
+ + {hidden > 0 ? ( + + onSelect({ ...target, host: first.host, environmentId: first.environmentId }) + } + trigger={{ + content: ( + + + +{hidden} more + + + ), + ariaLabel: gt("Show the {count} other layers of this stack", { count: hidden }), + }} + /> + ) : null} +
+ {open ?
{children}
: null} +
+ ); +} diff --git a/apps/web/src/components/pullRequest/PullRequestStackPopover.tsx b/apps/web/src/components/pullRequest/PullRequestStackPopover.tsx index ca3c3c2869eff..f88dae1aeedc3 100644 --- a/apps/web/src/components/pullRequest/PullRequestStackPopover.tsx +++ b/apps/web/src/components/pullRequest/PullRequestStackPopover.tsx @@ -1,7 +1,7 @@ import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip"; import type { EnvironmentId, PullRequestRef, PullRequestStackMembership } from "@t3tools/contracts"; import { T, useGT, Var } from "gt-react"; -import { useState } from "react"; +import { useState, type ReactNode } from "react"; import { usePullRequestStack } from "~/state/usePullRequestStack"; import { Menu, MenuTrigger, MenuPopup, MenuGroup, MenuGroupLabel, MenuItem } from "../ui/menu"; import { PullRequestStackLayers } from "./PullRequestStackLayers"; @@ -57,11 +57,14 @@ export function PullRequestStackPopover({ reference, membership, onSelect, + trigger, }: { environmentId: EnvironmentId; reference: PullRequestRef; membership: PullRequestStackMembership; onSelect: (reference: PullRequestRef) => void; + /** Replaces the layer glyph, e.g. a nested stack's "+3 more". */ + trigger?: { readonly content: ReactNode; readonly ariaLabel: string } | undefined; }) { const gt = useGT(); const [open, setOpen] = useState(false); @@ -79,24 +82,39 @@ export function PullRequestStackPopover({ className="inline-flex shrink-0 cursor-pointer items-center gap-1 text-xs font-normal text-muted-foreground" /> } - aria-label={gt("Stack {number}, layer {position} of {size}", { - number: membership.number, - position: membership.position, - size: membership.size, - })} + aria-label={ + trigger?.ariaLabel ?? + gt("Stack {number}, layer {position} of {size}", { + number: membership.number, + position: membership.position, + size: membership.size, + }) + } onClick={(event) => event.stopPropagation()} onKeyDown={(event) => event.stopPropagation()} > - - {membership.position}/{membership.size} + {trigger ? ( + trigger.content + ) : ( + <> + + {membership.position}/{membership.size} + + )} } /> - - View stack #{membership.number}, layer {membership.position} of{" "} - {membership.size} - + {trigger ? ( + + View all {membership.size} layers of stack #{membership.number} + + ) : ( + + View stack #{membership.number}, layer {membership.position} of{" "} + {membership.size} + + )} ({ + environmentId: "env-1", + host: "github.com", + repository, + number, + ...(stack + ? { + stack: { + number: stack.number, + position: stack.position, + size: stack.size ?? 5, + base: "main", + }, + } + : {}), +}); + +const shape = (rows: ReturnType) => + rows.map((row) => + row.kind === "entry" ? row.entry.number : row.entries.map((member) => member.number), + ); + +describe("nestPullRequestStacks", () => { + it("leaves entries without a stack in order", () => { + expect(shape(nestPullRequestStacks([entry(1), entry(2), entry(3)]))).toEqual([1, 2, 3]); + }); + + it("collapses a stack's entries at the first one's spot, bottom layer first", () => { + const rows = nestPullRequestStacks([ + entry(10, { number: 7, position: 3 }), + entry(20), + entry(11, { number: 7, position: 1 }), + entry(30), + ]); + expect(shape(rows)).toEqual([[11, 10], 20, 30]); + expect(rows[0]).toMatchObject({ kind: "stack", membership: { number: 7, size: 5 } }); + }); + + it("keeps a stack with one entry here as a plain row", () => { + expect( + shape(nestPullRequestStacks([entry(10, { number: 7, position: 2 }), entry(20)])), + ).toEqual([10, 20]); + }); + + it("does not merge the same stack number from two repositories", () => { + const rows = nestPullRequestStacks([ + entry(10, { number: 7, position: 1 }, "acme/app"), + entry(11, { number: 7, position: 2 }, "acme/app"), + entry(12, { number: 7, position: 1 }, "acme/api"), + entry(13, { number: 7, position: 2 }, "acme/api"), + ]); + expect(shape(rows)).toEqual([ + [10, 11], + [12, 13], + ]); + }); +}); diff --git a/packages/client-runtime/src/pullRequestStackNesting.ts b/packages/client-runtime/src/pullRequestStackNesting.ts new file mode 100644 index 0000000000000..4e5c12d09505b --- /dev/null +++ b/packages/client-runtime/src/pullRequestStackNesting.ts @@ -0,0 +1,64 @@ +import type { PullRequestStackMembership } from "@t3tools/contracts"; + +export interface StackablePullRequestEntry { + readonly environmentId: string; + readonly host: string; + readonly repository: string; + readonly number: number; + readonly stack?: PullRequestStackMembership | undefined; +} + +export type NestedPullRequestRow = + | { readonly kind: "entry"; readonly entry: E } + | { + readonly kind: "stack"; + readonly key: string; + readonly membership: PullRequestStackMembership; + /** Ordered bottom layer first. */ + readonly entries: ReadonlyArray; + }; + +/** Stack numbers are per repository, so the key carries where the stack lives. */ +function pullRequestStackKey(entry: StackablePullRequestEntry): string | null { + return entry.stack === undefined + ? null + : `${entry.environmentId}|${entry.host.toLowerCase()}|${entry.repository}|${entry.stack.number}`; +} + +/** + * Nests entries that share a stack under one block, placed where the first of them was. + * A stack with a single entry here stays a plain row. + */ +export function nestPullRequestStacks( + entries: ReadonlyArray, +): ReadonlyArray> { + const members = new Map(); + for (const entry of entries) { + const key = pullRequestStackKey(entry); + if (key === null) continue; + const list = members.get(key); + if (list) list.push(entry); + else members.set(key, [entry]); + } + const rows: NestedPullRequestRow[] = []; + const placed = new Set(); + for (const entry of entries) { + const key = pullRequestStackKey(entry); + const stackEntries = key === null ? undefined : members.get(key); + if (key === null || entry.stack === undefined || !stackEntries || stackEntries.length < 2) { + rows.push({ kind: "entry", entry }); + continue; + } + if (placed.has(key)) continue; + placed.add(key); + rows.push({ + kind: "stack", + key, + membership: entry.stack, + entries: [...stackEntries].sort( + (left, right) => (left.stack?.position ?? 0) - (right.stack?.position ?? 0), + ), + }); + } + return rows; +}