diff --git a/packages/app/src/git/pull-request-panel/checks-section.tsx b/packages/app/src/git/pull-request-panel/checks-section.tsx index ad542c869..a8b08a028 100644 --- a/packages/app/src/git/pull-request-panel/checks-section.tsx +++ b/packages/app/src/git/pull-request-panel/checks-section.tsx @@ -1,5 +1,5 @@ import { useCallback, useMemo } from "react"; -import { Pressable, ScrollView, Text, View, type GestureResponderEvent } from "react-native"; +import { Pressable, Text, View, type GestureResponderEvent } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { useTranslation } from "react-i18next"; import { ChevronDown, ChevronRight, MessageSquarePlus } from "lucide-react-native"; @@ -18,12 +18,6 @@ import { useCheckGroupState } from "./check-group-state"; const ThemedChevronDown = withUnistyles(ChevronDown); const ThemedChevronRight = withUnistyles(ChevronRight); -/** - * Roughly eight rows. A repo with thirty checks would otherwise push the activity - * timeline off the pane entirely, so past this height the list scrolls in place. - */ -const LIST_MAX_HEIGHT = 268; - /** * The three statuses the pane has always labelled for tests. Skipped has no id because * nothing asserts on it. @@ -112,11 +106,7 @@ export function ChecksSection({ {open && summary.groups.length > 0 ? ( - + {summary.groups.map((group) => ( ))} - + ) : null} ); @@ -263,9 +253,6 @@ const styles = StyleSheet.create((theme) => ({ color: theme.colors.foregroundMuted, }, list: { - maxHeight: LIST_MAX_HEIGHT, - }, - listContent: { paddingBottom: theme.spacing[2], }, groupHeader: { diff --git a/packages/app/src/git/pull-request-panel/pane.browser.test.tsx b/packages/app/src/git/pull-request-panel/pane.browser.test.tsx new file mode 100644 index 000000000..a25b5c72a --- /dev/null +++ b/packages/app/src/git/pull-request-panel/pane.browser.test.tsx @@ -0,0 +1,231 @@ +import React, { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { within } from "@testing-library/dom"; +import { SafeAreaInsetsContext } from "react-native-safe-area-context"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { i18n } from "@/i18n/i18next"; +import { ToastApiProvider } from "@/contexts/toast-context"; +import type { ToastApi } from "@/components/toast-host"; +import type { PrPaneCheck, PrPaneData } from "./data"; +import { PullRequestPane } from "./pane"; + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + +// App sources compile against the classic JSX runtime, which expects React on the global. +beforeEach(() => vi.stubGlobal("React", React)); + +const PANE_HEIGHT = 600; + +const silentToasts: ToastApi = { + show: () => () => {}, + copied: () => {}, + error: () => {}, +}; + +let root: Root | null = null; +let container: HTMLDivElement | null = null; + +afterEach(() => { + act(() => root?.unmount()); + container?.remove(); + root = null; + container = null; +}); + +function successfulChecks(count: number): PrPaneCheck[] { + return Array.from({ length: count }, (_, index) => ({ + provider: "github", + name: `check-${index + 1}`, + status: "success", + url: `https://example.test/checks/${index + 1}`, + })); +} + +function pullRequest(checks: PrPaneCheck[]): PrPaneData { + return { + provider: { id: "github", label: "GitHub" }, + forge: "github", + number: 42, + repoOwner: "acme", + repoName: "widgets", + title: "Ship the widget", + state: "open", + url: "https://example.test/pull/42", + reviewDecision: "pending", + awaitingReviewers: [], + checks, + activity: [], + }; +} + +/** A phone's home indicator: the pane clears it with bottom padding. */ +const HOME_INDICATOR_INSETS = { top: 0, right: 0, bottom: 34, left: 0 }; + +const NO_INSETS = { top: 0, right: 0, bottom: 0, left: 0 }; + +function renderPane(data: PrPaneData, insets = NO_INSETS) { + act(() => + root?.render( + + + + + , + ), + ); +} + +function mountPane(data: PrPaneData, insets = NO_INSETS) { + container = document.createElement("div"); + container.style.height = `${PANE_HEIGHT}px`; + container.style.width = "600px"; + container.style.display = "flex"; + container.style.flexDirection = "column"; + document.body.appendChild(container); + root = createRoot(container); + renderPane(data, insets); + const pane = container.querySelector('[data-testid="pr-pane"]'); + if (!pane) throw new Error("The pull request pane did not render"); + return pane; +} + +/** The pressable row holding the Activity title. */ +function activityHeader(pane: HTMLElement): HTMLElement { + const title = within(pane).getByText(i18n.t("workspace.git.pr.sections.activity")); + const header = title.closest("[tabindex]"); + if (!header) throw new Error("The Activity title is not inside a pressable header"); + return header; +} + +function checksRegionBottom(pane: HTMLElement): number { + return within(pane).getByRole("separator").getBoundingClientRect().top; +} + +/** Whether a user sees the element: no scroll container clips it out of view. */ +function isOnScreen(element: HTMLElement): boolean { + const rect = element.getBoundingClientRect(); + const hit = document.elementFromPoint(rect.left + 8, rect.top + rect.height / 2); + return hit !== null && element.contains(hit); +} + +/** React Native Web reports layout from a ResizeObserver, a frame or two after mounting. */ +async function settleLayout() { + for (let frame = 0; frame < 2; frame++) { + await act(() => new Promise((resolve) => requestAnimationFrame(() => resolve()))); + } +} + +/** Drags the separator through each offset from where it starts, releasing at the last one. */ +function dragSeparator(pane: HTMLElement, ...deltasY: number[]) { + const separator = within(pane).getByRole("separator"); + const rect = separator.getBoundingClientRect(); + const x = rect.left + rect.width / 2; + const startY = rect.top + rect.height / 2; + const pointer = { pointerId: 1, bubbles: true, cancelable: true, clientX: x, button: 0 }; + act(() => { + separator.dispatchEvent(new PointerEvent("pointerdown", { ...pointer, clientY: startY })); + }); + for (const deltaY of deltasY) { + act(() => { + window.dispatchEvent( + new PointerEvent("pointermove", { ...pointer, clientY: startY + deltaY }), + ); + }); + } + const endY = startY + (deltasY.at(-1) ?? 0); + act(() => { + window.dispatchEvent(new PointerEvent("pointerup", { ...pointer, clientY: endY })); + }); +} + +describe("pull request pane layout", () => { + it("docks a collapsed Activity section to the bottom and gives the checks the pane", async () => { + const pane = mountPane(pullRequest(successfulChecks(10))); + + act(() => activityHeader(pane).click()); + + await expect + .poll(() => Math.round(activityHeader(pane).getBoundingClientRect().bottom)) + .toBe(Math.round(pane.getBoundingClientRect().bottom)); + const rows = within(pane).getAllByTestId("pr-pane-check-row"); + expect(rows).toHaveLength(10); + expect(rows.every(isOnScreen)).toBe(true); + }); + + it("keeps keyboard focus on the Activity header while it collapses and expands", () => { + const pane = mountPane(pullRequest(successfulChecks(3))); + const header = activityHeader(pane); + act(() => header.focus()); + + act(() => header.click()); + expect(document.activeElement).toBe(header); + act(() => header.click()); + expect(document.activeElement).toBe(header); + }); + + it("exposes whether Activity is expanded to assistive technology", () => { + const pane = mountPane(pullRequest(successfulChecks(3))); + expect(activityHeader(pane).getAttribute("aria-expanded")).toBe("true"); + + act(() => activityHeader(pane).click()); + + expect(activityHeader(pane).getAttribute("aria-expanded")).toBe("false"); + }); + + it("keeps the Activity header inside the pane when a dragged pane gets short", async () => { + const pane = mountPane(pullRequest(successfulChecks(30))); + await settleLayout(); + dragSeparator(pane, PANE_HEIGHT); + await settleLayout(); + + act(() => { + if (container) container.style.height = "160px"; + }); + await settleLayout(); + + await expect + .poll(() => activityHeader(pane).getBoundingClientRect().bottom) + .toBeLessThanOrEqual(pane.getBoundingClientRect().bottom); + expect(isOnScreen(activityHeader(pane))).toBe(true); + }); + + it.each([ + ["5px down", [5]], + ["400px down", [400]], + ["up past their end and back down", [-20, 100]], + ])("gives the checks their earlier share when they grow after a drag %s", async (_name, path) => { + const pane = mountPane(pullRequest(successfulChecks(2))); + await settleLayout(); + const drawn = checksRegionBottom(pane); + + dragSeparator(pane, ...path); + await settleLayout(); + expect(checksRegionBottom(pane)).toBeCloseTo(drawn, 0); + + renderPane(pullRequest(successfulChecks(30))); + await settleLayout(); + const overview = within(pane).getByTestId("pr-pane-overview"); + expect(overview.getBoundingClientRect().height).toBeCloseTo(PANE_HEIGHT / 2, 0); + }); + + it("resizes the checks against Activity by dragging the separator between them", async () => { + const pane = mountPane(pullRequest(successfulChecks(30))); + await settleLayout(); + const before = checksRegionBottom(pane); + + dragSeparator(pane, 120); + + await expect.poll(() => Math.round(checksRegionBottom(pane) - before)).toBe(120); + expect(activityHeader(pane).getBoundingClientRect().top).toBeGreaterThan(before + 100); + }); + + it("keeps the separator under the pointer when the pane clears a bottom inset", async () => { + const pane = mountPane(pullRequest(successfulChecks(30)), HOME_INDICATOR_INSETS); + await settleLayout(); + const before = checksRegionBottom(pane); + + dragSeparator(pane, 120); + + await expect.poll(() => Math.round(checksRegionBottom(pane) - before)).toBe(120); + }); +}); diff --git a/packages/app/src/git/pull-request-panel/pane.tsx b/packages/app/src/git/pull-request-panel/pane.tsx index 1f36a8749..ff2b9c868 100644 --- a/packages/app/src/git/pull-request-panel/pane.tsx +++ b/packages/app/src/git/pull-request-panel/pane.tsx @@ -1,5 +1,5 @@ import { useCallback, useMemo, useState } from "react"; -import { Image, Pressable, ScrollView, Text, View, type ViewStyle } from "react-native"; +import { Image, Pressable, Text, View, type ViewStyle } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import { CircleCheck, @@ -74,13 +74,14 @@ import { type PrTimelineEntry, } from "./timeline"; import { - Section, + SectionHeader, SummaryPill, dangerColorMapping, foregroundMutedColorMapping, sectionKitStyles, successColorMapping, } from "./section-kit"; +import { PullRequestPaneSplit } from "./split"; const ThemedCircleCheck = withUnistyles(CircleCheck); const ThemedCircleX = withUnistyles(CircleX); @@ -478,8 +479,8 @@ export function PullRequestPane({ : null; return ( - - + + <> + + ) : null} + {activityLoading ? : null} + {!activityLoading && visibleEntries.length === 0 ? ( + {t("workspace.git.pr.empty.noActivity")} + ) : null} + {!activityLoading + ? visibleEntries.map(({ entry, collapsed }) => ( + - - - } - > - {timelineEntries.length > 0 && attachEnabled && visibleEntries.length > 0 ? ( - - - - ) : null} - {activityLoading ? : null} - {!activityLoading && visibleEntries.length === 0 ? ( - {t("workspace.git.pr.empty.noActivity")} - ) : null} - {!activityLoading - ? visibleEntries.map(({ entry, collapsed }) => ( - - )) - : null} - - - + )) + : null} + + ); } @@ -1192,15 +1193,6 @@ function ThreadComment({ } const styles = StyleSheet.create((theme) => ({ - root: { - flex: 1, - minHeight: 0, - backgroundColor: theme.colors.surfaceSidebar, - }, - scroll: { - flex: 1, - minHeight: 0, - }, invisible: { opacity: 0, }, @@ -1261,10 +1253,6 @@ const styles = StyleSheet.create((theme) => ({ marginLeft: theme.spacing[1], opacity: 0, }, - divider: { - height: 1, - backgroundColor: theme.colors.border, - }, toolbar: { flexDirection: "row", alignItems: "center", diff --git a/packages/app/src/git/pull-request-panel/section-kit.tsx b/packages/app/src/git/pull-request-panel/section-kit.tsx index b4a9d00a3..e28f0ac05 100644 --- a/packages/app/src/git/pull-request-panel/section-kit.tsx +++ b/packages/app/src/git/pull-request-panel/section-kit.tsx @@ -1,8 +1,9 @@ -import React, { type ReactNode } from "react"; +import React, { useMemo, type ReactNode } from "react"; import { Pressable, Text, View } from "react-native"; import { StyleSheet, withUnistyles } from "react-native-unistyles"; import type { CountedCheckPresentation } from "@/git/check-presentation"; import { CONTROL_HEIGHTS, mapLayout } from "@/components/ui/control-geometry"; +import { isWeb } from "@/constants/platform"; import { CheckPresentationIcon, getCheckPresentationTone, @@ -21,39 +22,57 @@ export const successColorMapping = (theme: Theme) => ({ color: theme.colors.stat export const dangerColorMapping = (theme: Theme) => ({ color: theme.colors.statusDanger }); export const warningColorMapping = (theme: Theme) => ({ color: theme.colors.statusWarning }); -interface SectionProps { +interface SectionHeaderProps { title: string; open: boolean; onToggle: () => void; summary: ReactNode; - children: ReactNode; accessibilityLabel?: string; } -export function Section({ +interface SectionProps extends SectionHeaderProps { + children: ReactNode; +} + +/** The disclosure row of a section, for layouts that place the section's body themselves. */ +export function SectionHeader({ title, open, onToggle, summary, - children, accessibilityLabel, -}: SectionProps) { +}: SectionHeaderProps) { + const accessibilityState = useMemo(() => ({ expanded: open }), [open]); + // React Native Web does not map `accessibilityState.expanded` to `aria-expanded`. + const webExpandedProps = useMemo( + () => (isWeb ? ({ "aria-expanded": open } as const) : null), + [open], + ); + return ( + + {open ? ( + + ) : ( + + )} + {title} + {summary} + + ); +} + +export function Section({ children, ...header }: SectionProps) { return ( - - {open ? ( - - ) : ( - - )} - {title} - {summary} - - {open ? {children} : null} + + {header.open ? {children} : null} ); } diff --git a/packages/app/src/git/pull-request-panel/split.tsx b/packages/app/src/git/pull-request-panel/split.tsx new file mode 100644 index 000000000..1491e6d40 --- /dev/null +++ b/packages/app/src/git/pull-request-panel/split.tsx @@ -0,0 +1,162 @@ +import { Children, useCallback, useMemo, useState, type ReactNode } from "react"; +import { ScrollView, View, type LayoutChangeEvent } from "react-native"; +import { StyleSheet } from "react-native-unistyles"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; +import { ResizeHandle } from "@/components/resize-handle"; + +/** Most of the pane the overview may take before it scrolls, until the user drags the separator. */ +const DEFAULT_OVERVIEW_SHARE = 0.5; +const SPLIT_GROUP_ID = "pr-pane"; + +interface PullRequestPaneSplitProps { + /** + * Exactly three children, in order: + * 1. the overview (the PR's header and checks), which scrolls in its own region; + * 2. the Activity disclosure row, docked to the bottom of the pane while collapsed; + * 3. the Activity timeline, filling the space below the separator while open. + * + * Slots are children because `react-perf/jsx-no-jsx-as-prop` rejects JSX in a prop. Pass all + * three unconditionally, the way `TreeRail` takes its slots. + */ + children: ReactNode; + activityOpen: boolean; +} + +/** + * Lays the pane out the way stacked sidebar sections behave: the overview and Activity share the + * height, a separator between them resizes the share, and a collapsed Activity gives its space + * back by docking its header to the bottom. + */ +export function PullRequestPaneSplit({ children, activityOpen }: PullRequestPaneSplitProps) { + const [overview, activityHeader, activityTimeline] = Children.toArray(children); + const insets = useSafeAreaInsets(); + const [overviewShare, setOverviewShare] = useState(DEFAULT_OVERVIEW_SHARE); + // The pointer's share while a drag is in progress. The saved share is decided once, when the + // drag ends, so moves along the way cannot overwrite the share the overview had before it. + const [dragShare, setDragShare] = useState(null); + const [splitHeight, setSplitHeight] = useState(0); + const [overviewHeight, setOverviewHeight] = useState(0); + const [overviewContentHeight, setOverviewContentHeight] = useState(0); + + const handleSplitLayout = useCallback((event: LayoutChangeEvent) => { + setSplitHeight(event.nativeEvent.layout.height); + }, []); + const handleOverviewLayout = useCallback((event: LayoutChangeEvent) => { + setOverviewHeight(event.nativeEvent.layout.height); + }, []); + const handleOverviewContentSizeChange = useCallback((_width: number, height: number) => { + setOverviewContentHeight(height); + }, []); + const handlePreviewResize = useCallback((_groupId: string, sizes: number[]) => { + const [share] = sizes; + if (share !== undefined) setDragShare(share); + }, []); + const handleResize = useCallback( + (_groupId: string, sizes: number[]) => { + setDragShare(null); + const [share] = sizes; + if (share === undefined || splitHeight <= 0) return; + const contentShare = overviewContentHeight / splitHeight; + setOverviewShare((current) => resolveDraggedShare(share, current, contentShare)); + }, + [overviewContentHeight, splitHeight], + ); + + // The overview stops at its content height, so a drag starts from where the separator is + // drawn rather than from the share the overview may grow to. + const separatorSizes = useMemo(() => { + const share = splitHeight > 0 ? overviewHeight / splitHeight : DEFAULT_OVERVIEW_SHARE; + return [share, 1 - share]; + }, [overviewHeight, splitHeight]); + // The Activity header docks to the bottom edge, so it clears the home indicator the way the + // Changes pane's docked Commits section does. The split is measured inside that padding: the + // overview's percentage height resolves against this box, so the drag must use the same one. + const rootStyle = useMemo(() => [styles.root, { paddingBottom: insets.bottom }], [insets.bottom]); + const drawnShare = dragShare ?? overviewShare; + const overviewStyle = useMemo( + () => + activityOpen + ? [styles.overviewShared, { maxHeight: `${drawnShare * 100}%` as const }] + : styles.overviewFill, + [activityOpen, drawnShare], + ); + + return ( + + + + {overview} + + {activityOpen ? ( + + ) : ( + + )} + {/* The header keeps one slot in both states, so toggling it does not remount the row + and drop keyboard focus. Only the timeline mounts and unmounts. */} + {activityHeader} + {activityOpen ? ( + + {activityTimeline} + + ) : null} + + + ); +} + +/** + * The share a drag leaves the overview. Short content stops the separator at the content's + * bottom, so a drag that ends there or below saves what was drawn and keeps any larger share + * the overview already had. The separator then neither jumps to the pointer nor stays pinned + * at the old content height when the content grows. + */ +function resolveDraggedShare(pointerShare: number, currentShare: number, contentShare: number) { + if (pointerShare < contentShare) return pointerShare; + return Math.max(currentShare, contentShare); +} + +const styles = StyleSheet.create((theme) => ({ + root: { + flex: 1, + minHeight: 0, + backgroundColor: theme.colors.surfaceSidebar, + }, + split: { + flex: 1, + minHeight: 0, + }, + overviewShared: { + flexGrow: 0, + flexShrink: 1, + minHeight: 0, + }, + overviewFill: { + flex: 1, + minHeight: 0, + }, + // Same 1px line the separator draws, so collapsing Activity does not move the boundary's look. + divider: { + height: 1, + backgroundColor: theme.colors.border, + }, + activityScroll: { + flex: 1, + minHeight: 0, + }, +})); diff --git a/packages/app/test-stubs/react-native-unistyles.ts b/packages/app/test-stubs/react-native-unistyles.ts index 04f61bc77..e33f3347c 100644 --- a/packages/app/test-stubs/react-native-unistyles.ts +++ b/packages/app/test-stubs/react-native-unistyles.ts @@ -1,7 +1,8 @@ +import { createElement, type ElementType } from "react"; import { lightHighlightColors } from "@getpaseo/highlight"; import { lightTheme } from "../src/styles/theme"; -const testTheme = { +const pinnedTheme = { colorScheme: "light", colors: { syntax: lightHighlightColors, @@ -86,6 +87,14 @@ const testTheme = { }, }; +// Tokens a test does not pin come from the real light theme, so a style or `uniProps` mapping +// that reads one (the markdown renderer reads `colors.terminal`) gets a value instead of crashing. +const testTheme = { + ...lightTheme, + ...pinnedTheme, + colors: { ...lightTheme.colors, ...pinnedTheme.colors }, +}; + type StyleFactory = (theme: typeof testTheme) => T; function isStyleFactory(styles: T | StyleFactory): styles is StyleFactory { @@ -142,7 +151,19 @@ export const StyleSheet = { resolveStyles(isStyleFactory(styles) ? styles(testTheme) : styles), }; -export const withUnistyles = (Component: T): T => Component; +type UniPropsMapping = (theme: typeof testTheme, runtime: object) => Record; + +/** Applies `uniProps` with the test theme, the way Unistyles maps theme values onto props. */ +export const withUnistyles = (Component: T): T => { + function ThemedComponent({ uniProps, ...props }: { uniProps?: UniPropsMapping }) { + // Explicit props win over mapped ones, as in Unistyles' `deepMergeObjects(mappings, uniProps, props)`. + return createElement(Component as ElementType, { + ...(uniProps ? uniProps(testTheme, {}) : {}), + ...props, + }); + } + return ThemedComponent as T; +}; export const useUnistyles = () => ({ theme: testTheme,