diff --git a/packages/react/src/SelectPanel/SelectPanel.examples.stories.tsx b/packages/react/src/SelectPanel/SelectPanel.examples.stories.tsx index 5d9058bcefd..bcb6999da3c 100644 --- a/packages/react/src/SelectPanel/SelectPanel.examples.stories.tsx +++ b/packages/react/src/SelectPanel/SelectPanel.examples.stories.tsx @@ -356,7 +356,7 @@ export const RepositionAfterLoading = () => { const [loading, setLoading] = useState(true) React.useEffect(() => { - // eslint-disable-next-line react-hooks/set-state-in-effect + // eslint-disable-next-line react-hooks/set-state-in-effect -- Reset loading state when panel closes if (!open) setLoading(true) window.setTimeout(() => { if (open) { @@ -369,7 +369,6 @@ export const RepositionAfterLoading = () => { React.useEffect(() => { if (!loading) { - // eslint-disable-next-line react-hooks/set-state-in-effect setFilteredItems(items.filter(item => item.text.toLowerCase().startsWith(filter.toLowerCase()))) } // eslint-disable-next-line react-hooks/exhaustive-deps @@ -405,7 +404,7 @@ export const SelectPanelRepositionInsideDialog = () => { const [loading, setLoading] = useState(true) React.useEffect(() => { - // eslint-disable-next-line react-hooks/set-state-in-effect + // eslint-disable-next-line react-hooks/set-state-in-effect -- Reset loading state when panel closes if (!open) setLoading(true) window.setTimeout(() => { if (open) { @@ -418,7 +417,6 @@ export const SelectPanelRepositionInsideDialog = () => { React.useEffect(() => { if (!loading) { - // eslint-disable-next-line react-hooks/set-state-in-effect setFilteredItems(items.filter(item => item.text.toLowerCase().startsWith(filter.toLowerCase()))) } // eslint-disable-next-line react-hooks/exhaustive-deps @@ -438,7 +436,6 @@ export const SelectPanelRepositionInsideDialog = () => { selected={selected} onSelectedChange={setSelected} onFilterChange={setFilter} - overlayProps={{anchorSide: 'outside-top'}} message={filteredItems.length === 0 ? NoResultsMessage(filter) : undefined} /> @@ -446,6 +443,56 @@ export const SelectPanelRepositionInsideDialog = () => { ) } +export const AutogrowAfterLoadingWithOutsideTopAnchor = () => { + const autogrowItems = [...items] + + const [selected, setSelected] = React.useState([autogrowItems[0], autogrowItems[1]]) + const [open, setOpen] = useState(false) + const [filter, setFilter] = React.useState('') + const [filteredItems, setFilteredItems] = React.useState([]) + const [loading, setLoading] = useState(true) + + React.useEffect(() => { + // eslint-disable-next-line react-hooks/set-state-in-effect -- Reset loading state when panel closes + if (!open) setLoading(true) + const timer = window.setTimeout(() => { + if (open) { + setFilteredItems(autogrowItems.filter(item => item.text.toLowerCase().startsWith(filter.toLowerCase()))) + setLoading(false) + } + }, 2000) + + return () => window.clearTimeout(timer) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [open]) + + React.useEffect(() => { + if (!loading) { + setFilteredItems(autogrowItems.filter(item => item.text.toLowerCase().startsWith(filter.toLowerCase()))) + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [filter]) + + return ( + +

Autogrow panel after loading with outside-top anchor

+ +
+ ) +} + export const WithDefaultMessage = () => { const [selected, setSelected] = useState(items.slice(1, 3)) const [filter, setFilter] = useState('') @@ -624,7 +671,6 @@ export const VirtualizedConsumerSide = () => { [open], ) - // eslint-disable-next-line react-hooks/incompatible-library const virtualizer = useVirtualizer({ count: filteredItems.length, getScrollElement: () => scrollContainer ?? null, diff --git a/packages/react/src/SelectPanel/SelectPanel.test.tsx b/packages/react/src/SelectPanel/SelectPanel.test.tsx index c1d71b154c7..c7339413327 100644 --- a/packages/react/src/SelectPanel/SelectPanel.test.tsx +++ b/packages/react/src/SelectPanel/SelectPanel.test.tsx @@ -2291,3 +2291,151 @@ describe('SelectPanel displayInViewport prop', () => { expect(lastCall[2]?.displayInViewport).not.toBe(true) }) }) + +/** + * Test suite for SelectPanel first-open sizing regression + * Issue: https://github.com/github/issues/issues/18331 + * + * On first open with loading state, SelectPanel may render shorter than its content + * and show an unnecessary scrollbar. This occurs because position is calculated before + * items have loaded and rendered, using the spinner/loading state height rather than + * the final content height. + */ +describe('SelectPanel - First-Open Sizing with Loading State', () => { + const items: ItemInput[] = [ + {id: '1', text: 'Item 1'}, + {id: '2', text: 'Item 2'}, + {id: '3', text: 'Item 3'}, + {id: '4', text: 'Item 4'}, + {id: '5', text: 'Item 5'}, + {id: '6', text: 'Item 6'}, + {id: '7', text: 'Item 7'}, + {id: '8', text: 'Item 8'}, + ] + + const TestComponentWithLoadingDelay = () => { + const [selected, setSelected] = React.useState(items[0]) + const [open, setOpen] = React.useState(false) + const [loading, setLoading] = React.useState(true) + const [visibleItems, setVisibleItems] = React.useState([]) + + // Simulate items loading after a delay (typical async data fetch) + React.useEffect(() => { + if (!open) { + setLoading(true) + setVisibleItems([]) + } + + const timer = setTimeout(() => { + if (open) { + setVisibleItems(items) + setLoading(false) + } + }, 500) // 500ms delay simulates network/async operation + + return () => clearTimeout(timer) + }, [open]) + + return ( + <> + {}} + loading={loading} + items={visibleItems} + selected={selected} + onSelectedChange={setSelected} + height="large" + /> +
+ open:{open} loading:{loading} itemsCount:{visibleItems.length} +
+ + ) + } + + it('should measure overlay height correctly while loading', async () => { + const user = userEvent.setup() + render() + + const button = screen.getByRole('button', {name: /Select item/i}) + + // Open SelectPanel for the first time + await user.click(button) + + // Wait for overlay to appear (should show loading spinner) + await waitFor( + () => { + expect(screen.getByText(/^Item 1$/)).toBeInTheDocument() + }, + {timeout: 1000}, + ) + + // Get overlay element + const overlay = document.querySelector('[data-testid="overlay"]') as HTMLElement | null + + // Wait for items to load + await waitFor( + () => { + const state = screen.getByTestId('state') + expect(state).toHaveTextContent('loading:false') + }, + {timeout: 1500}, + ) + + // Get overlay measurements after loading + const clientHeightAfterLoading = overlay?.clientHeight + const scrollHeightAfterLoading = overlay?.scrollHeight + + // The overlay should have enough height to fit all content without scrollbar + if (clientHeightAfterLoading && scrollHeightAfterLoading) { + const hasScrollbar = scrollHeightAfterLoading > clientHeightAfterLoading + expect(hasScrollbar).toBe(false) + } + }) + + it('should have consistent height between first and second open', async () => { + const user = userEvent.setup() + render() + + const button = screen.getByRole('button', {name: /Select item/i}) + + // First open + await user.click(button) + await waitFor(() => { + const state = screen.getByTestId('state') + expect(state).toHaveTextContent('loading:false') + }) + + const overlay1 = document.querySelector('[data-testid="overlay"]') + const height1 = overlay1?.getBoundingClientRect().height + + // Close + await user.click(button) + await waitFor(() => { + const state = screen.getByTestId('state') + expect(state).toHaveTextContent('open:false') + }) + + // Second open (loading state happens again) + await user.click(button) + await waitFor( + () => { + const state = screen.getByTestId('state') + expect(state).toHaveTextContent('loading:false') + }, + {timeout: 1500}, + ) + + const overlay2 = document.querySelector('[data-testid="overlay"]') + const height2 = overlay2?.getBoundingClientRect().height + + // Heights should be very similar (allowing for minor variations) + if (height1 && height2) { + const difference = Math.abs(height1 - height2) + expect(difference).toBeLessThan(50) // Allow max 50px variance + } + }) +}) diff --git a/packages/react/src/hooks/__tests__/useAnchoredPosition.test.tsx b/packages/react/src/hooks/__tests__/useAnchoredPosition.test.tsx index 98a4d58fc2e..cd36856bfe3 100644 --- a/packages/react/src/hooks/__tests__/useAnchoredPosition.test.tsx +++ b/packages/react/src/hooks/__tests__/useAnchoredPosition.test.tsx @@ -1,8 +1,40 @@ import {render, waitFor, act} from '@testing-library/react' -import {it, expect, vi, describe} from 'vitest' +import {it, expect, vi, describe, beforeEach, afterEach} from 'vitest' import React from 'react' import {useAnchoredPosition} from '../../hooks/useAnchoredPosition' +type MockedAnchorPosition = { + anchorAlign: string + anchorSide: string + left: number + top: number +} + +type BehaviorsModule = Record & { + getAnchoredPosition: (...args: unknown[]) => MockedAnchorPosition +} + +const {mockedGetAnchoredPosition} = vi.hoisted(() => ({ + mockedGetAnchoredPosition: vi.fn(), +})) + +vi.mock('@primer/behaviors', async importOriginal => { + const actual = (await importOriginal()) as BehaviorsModule + + return { + ...actual, + getAnchoredPosition: (...args: unknown[]) => { + const implementation = mockedGetAnchoredPosition.getMockImplementation() + + if (implementation) { + return mockedGetAnchoredPosition(...args) + } + + return actual.getAnchoredPosition(...args) + }, + } +}) + const Component = ({callback}: {callback: (hookReturnValue: ReturnType) => void}) => { const floatingElementRef = React.useRef(null) const anchorElementRef = React.useRef(null) @@ -18,6 +50,33 @@ const Component = ({callback}: {callback: (hookReturnValue: ReturnType) => void + step: number +}) => { + const floatingElementRef = React.useRef(null) + const anchorElementRef = React.useRef(null) + callback(useAnchoredPosition({floatingElementRef, anchorElementRef, pinPosition: true}, [step])) + + return ( +
+
+
+
+ ) +} + +beforeEach(() => { + mockedGetAnchoredPosition.mockReset() +}) + +afterEach(() => { + vi.restoreAllMocks() +}) + it('should should return a position', async () => { const cb = vi.fn() render() @@ -142,3 +201,126 @@ describe('scroll recalculation', () => { }) }) }) + +describe('pinPosition', () => { + it('allows outside-top overlays to grow when content needs more height', async () => { + const callback = vi.fn() + let currentTop = 200 + let floatingHeight = 147 + let floatingScrollHeight = 147 + let overflowingDescendantHeight = 147 + let overflowingDescendantScrollHeight = 147 + + mockedGetAnchoredPosition.mockImplementation(() => ({ + anchorAlign: 'start', + anchorSide: 'outside-top', + left: 0, + top: currentTop, + })) + + const requestAnimationFrameSpy = vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => { + callback(0) + return 0 + }) + + const {container, rerender} = render() + const [floatingElement, anchorElement] = Array.from(container.firstElementChild!.children) as [ + HTMLDivElement, + HTMLDivElement, + ] + const overflowingDescendant = document.createElement('div') + floatingElement.append(overflowingDescendant) + + Object.defineProperty(floatingElement, 'clientHeight', {configurable: true, get: () => floatingHeight}) + Object.defineProperty(floatingElement, 'scrollHeight', {configurable: true, get: () => floatingScrollHeight}) + Object.defineProperty(overflowingDescendant, 'clientHeight', { + configurable: true, + get: () => overflowingDescendantHeight, + }) + Object.defineProperty(overflowingDescendant, 'scrollHeight', { + configurable: true, + get: () => overflowingDescendantScrollHeight, + }) + Object.defineProperty(anchorElement, 'getBoundingClientRect', { + configurable: true, + value: () => ({top: 500}), + }) + + await waitFor(() => { + expect(callback.mock.lastCall?.[0].position.top).toBe(200) + }) + + rerender() + + await waitFor(() => { + expect(callback.mock.lastCall?.[0].position.top).toBe(200) + }) + + currentTop = 210 + floatingHeight = 91 + floatingScrollHeight = 91 + overflowingDescendantHeight = 91 + overflowingDescendantScrollHeight = 317 + rerender() + + await waitFor(() => { + expect(callback.mock.lastCall?.[0].position.top).toBe(210) + }) + + expect(floatingElement.style.height).toBe('') + expect(requestAnimationFrameSpy).toHaveBeenCalled() + }) + + it('keeps the previous height when outside-top content is genuinely shrinking', async () => { + const callback = vi.fn() + let currentTop = 200 + let floatingHeight = 147 + let floatingScrollHeight = 147 + + mockedGetAnchoredPosition.mockImplementation(() => ({ + anchorAlign: 'start', + anchorSide: 'outside-top', + left: 0, + top: currentTop, + })) + + vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => { + callback(0) + return 0 + }) + + const {container, rerender} = render() + const [floatingElement, anchorElement] = Array.from(container.firstElementChild!.children) as [ + HTMLDivElement, + HTMLDivElement, + ] + + Object.defineProperty(floatingElement, 'clientHeight', {configurable: true, get: () => floatingHeight}) + Object.defineProperty(floatingElement, 'scrollHeight', {configurable: true, get: () => floatingScrollHeight}) + Object.defineProperty(anchorElement, 'getBoundingClientRect', { + configurable: true, + value: () => ({top: 500}), + }) + + await waitFor(() => { + expect(callback.mock.lastCall?.[0].position.top).toBe(200) + }) + + rerender() + + await waitFor(() => { + expect(callback.mock.lastCall?.[0].position.top).toBe(200) + }) + + currentTop = 210 + floatingHeight = 91 + floatingScrollHeight = 91 + rerender() + + await waitFor(() => { + expect(callback.mock.lastCall?.[0].position.top).toBe(200) + }) + + expect(floatingElement.style.height).toBe('147px') + }) +}) diff --git a/packages/react/src/hooks/useAnchoredPosition.ts b/packages/react/src/hooks/useAnchoredPosition.ts index 611d1b1e920..e2b5b1bb84a 100644 --- a/packages/react/src/hooks/useAnchoredPosition.ts +++ b/packages/react/src/hooks/useAnchoredPosition.ts @@ -34,6 +34,18 @@ export interface AnchoredPositionHookSettings extends Partial enabled?: boolean } +function hasOverflowingDescendant(element: HTMLElement | null) { + if (!element) return false + + for (const descendant of element.querySelectorAll('*')) { + if (descendant.scrollHeight > descendant.clientHeight || descendant.scrollWidth > descendant.clientWidth) { + return true + } + } + + return false +} + /** * Calculates the top and left values for an absolutely-positioned floating element * to be anchored to some anchor element. Returns refs for the floating element @@ -71,8 +83,24 @@ export function useAnchoredPosition( const updateElementHeight = () => { let heightUpdated = false setPrevHeight(prevHeight => { - // if the element is trying to shrink in height, restore to old height to prevent it from jumping - if (prevHeight && prevHeight > (floatingElementRef.current?.clientHeight ?? 0)) { + const floatingElement = floatingElementRef.current as HTMLElement | null + const currentHeight = floatingElement?.clientHeight ?? 0 + const desiredHeight = Math.max(floatingElement?.scrollHeight ?? 0, currentHeight) + const contentNeedsMoreHeight = + (prevHeight !== undefined && desiredHeight > prevHeight) || hasOverflowingDescendant(floatingElement) + + // if the element is trying to shrink in height, restore to old height to prevent it from jumping. + // When the content now needs to grow past the previous height, clear any stale inline height instead. + if (prevHeight && prevHeight > currentHeight) { + if (contentNeedsMoreHeight) { + requestAnimationFrame(() => { + if (floatingElementRef.current instanceof HTMLElement) { + floatingElementRef.current.style.height = '' + } + }) + return prevHeight + } + requestAnimationFrame(() => { ;(floatingElementRef.current as HTMLElement).style.height = `${prevHeight}px` }) @@ -111,7 +139,7 @@ export function useAnchoredPosition( } setPrevHeight(floatingElementRef.current?.clientHeight) }, - // eslint-disable-next-line react-hooks/exhaustive-deps, react-hooks/use-memo + // eslint-disable-next-line react-hooks/exhaustive-deps [floatingElementRef, anchorElementRef, enabled, ...dependencies], )