diff --git a/pages/list/sortable-sticky-drawer-autoscroll.page.tsx b/pages/list/sortable-sticky-drawer-autoscroll.page.tsx index a15379ae263..20f20373854 100644 --- a/pages/list/sortable-sticky-drawer-autoscroll.page.tsx +++ b/pages/list/sortable-sticky-drawer-autoscroll.page.tsx @@ -1,30 +1,38 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import React, { useContext, useState } from 'react'; +import React, { useContext, useEffect, useState } from 'react'; -import { Box, List, SegmentedControl } from '~components'; +import { Box, Input, List, SegmentedControl, SpaceBetween } from '~components'; import AppContext, { AppContextType } from '../app/app-context'; import { SimplePage } from '../app/templates'; -type Layout = 'drawer-scroller' | 'drawer' | 'page'; +type Layout = + | 'drawer-scroller' + | 'drawer' + | 'drawer-nested' + | 'container' + | 'container-x' + | 'page' + | 'body-viewport' + | 'body-scroller'; -type PageContext = React.Context>; +type PageContext = React.Context>; interface Item { id: string; content: string; } -const initialItems: Item[] = Array.from({ length: 30 }, (_, index) => ({ - id: `item-${index + 1}`, - content: `Item ${index + 1}`, -})); - const outerHeight = 600; +const innerHeight = 300; + +function createItems(count: number): Item[] { + return Array.from({ length: count }, (_, index) => ({ id: `item-${index + 1}`, content: `Item ${index + 1}` })); +} -function SortableList() { - const [items, setItems] = useState(initialItems); +function SortableList({ itemCount }: { itemCount: number }) { + const [items, setItems] = useState(() => createItems(itemCount)); return ( + {Array.from({ length: count }, (_, index) => ( + + {prefix} row {index + 1} + + ))} + + ); +} + +function StickyDrawerLayout({ layout, itemCount }: { layout: Layout; itemCount: number }) { + const ownScroller = layout !== 'drawer'; return (
- {Array.from({ length: 150 }, (_, index) => ( - - Main content row {index + 1} - - ))} +
); } +function ContainerLayout({ layout, itemCount }: { layout: Layout; itemCount: number }) { + const style: React.CSSProperties = + layout === 'container-x' + ? { blockSize: innerHeight, overflowX: 'auto', overflowY: 'hidden' } + : { blockSize: innerHeight, overflowY: 'auto' }; + return ( +
+ +
+ +
+ +
+ ); +} + +// body-viewport: body has overflow-y: auto while html keeps overflow: visible, so the body's overflow applies to the +// viewport and the document scroller scrolls. body-scroller: html clips, so body is an independent scroll container. +function BodyOverflowLayout({ layout, itemCount }: { layout: Layout; itemCount: number }) { + useEffect(() => { + const html = document.documentElement; + const body = document.body; + const previous = { htmlOverflow: html.style.overflow, htmlHeight: html.style.blockSize, body: body.style.cssText }; + body.style.overflowY = 'auto'; + if (layout === 'body-scroller') { + html.style.overflow = 'hidden'; + html.style.blockSize = '100%'; + body.style.blockSize = '100%'; + } + return () => { + html.style.overflow = previous.htmlOverflow; + html.style.blockSize = previous.htmlHeight; + body.style.cssText = previous.body; + }; + }, [layout]); + return ( +
+ + + +
+ ); +} + export default function SortableListAutoScrollPage() { const { - urlParams: { layout = 'drawer-scroller' }, + urlParams: { layout = 'drawer-scroller', itemCount = '30' }, setUrlParams, } = useContext(AppContext as PageContext); + const parsedItemCount = Math.max(1, parseInt(itemCount, 10) || 30); + const content = + layout === 'body-viewport' || layout === 'body-scroller' ? ( + + ) : layout === 'page' ? ( + + ) : layout === 'container' || layout === 'container-x' ? ( + + ) : ( + + ); return ( setUrlParams({ layout: detail.selectedId as Layout })} - options={[ - { id: 'drawer-scroller', text: 'Sticky drawer with own scroller' }, - { id: 'drawer', text: 'Sticky drawer without own scroller' }, - { id: 'page', text: 'Page flow' }, - ]} - /> + + setUrlParams({ layout: detail.selectedId as Layout })} + options={[ + { id: 'drawer-scroller', text: 'Sticky drawer with own scroller' }, + { id: 'drawer', text: 'Sticky drawer without own scroller' }, + { id: 'drawer-nested', text: 'Nested scroller in sticky drawer' }, + { id: 'container', text: 'Fixed-height container' }, + { id: 'container-x', text: 'Horizontal-only container' }, + { id: 'page', text: 'Page flow' }, + { id: 'body-viewport', text: 'Body overflow on viewport' }, + { id: 'body-scroller', text: 'Body as own scroller' }, + ]} + /> + setUrlParams({ itemCount: detail.value })} + /> + } > - {layout === 'page' ? : } +
{content}
); } diff --git a/src/internal/components/sortable-area/index.tsx b/src/internal/components/sortable-area/index.tsx index 977014b5de9..d3104af3349 100644 --- a/src/internal/components/sortable-area/index.tsx +++ b/src/internal/components/sortable-area/index.tsx @@ -123,7 +123,9 @@ export default function SortableArea({ // dnd-kit auto-scrolls every scrollable ancestor up to the first fixed-position element, outermost first by default // (https://github.com/clauderic/dnd-kit/issues/1893). Restrict it to the sortable area's nearest scroll container so -// that dragging inside e.g. a sticky drawer does not scroll unrelated outer containers. Without a scrollable ancestor, +// that dragging inside e.g. a sticky drawer does not scroll unrelated outer containers. The boundary is the nearest +// ancestor with a scrolling overflow-y even if its content does not currently overflow: such a container then simply +// has nothing to auto-scroll, rather than letting the outer containers scroll instead. Without such an ancestor, // all containers (including the window) remain eligible. function useScopedAutoScroll() { const boundaryRef = useRef(null); @@ -136,7 +138,7 @@ function useScopedAutoScroll() { while (element && !isHTMLElement(element)) { element = element.parentElement; } - boundaryRef.current = element ? (getFirstScrollableParent(element) ?? null) : null; + boundaryRef.current = element ? (getFirstScrollableParent(element, { requireOverflow: false }) ?? null) : null; }; return { autoScroll, setAutoScrollBoundary }; } diff --git a/src/internal/utils/__tests__/scrollable-containers.test.tsx b/src/internal/utils/__tests__/scrollable-containers.test.tsx index 4d877cf2cb3..d818ba07981 100644 --- a/src/internal/utils/__tests__/scrollable-containers.test.tsx +++ b/src/internal/utils/__tests__/scrollable-containers.test.tsx @@ -116,3 +116,180 @@ describe('getScrollableParents', () => { expect(getScrollableParents(target)).toEqual([]); }); }); + +describe('getFirstScrollableParent with requireOverflow: false', () => { + const originalGetComputedStyle = window.getComputedStyle; + + afterEach(() => { + window.getComputedStyle = originalGetComputedStyle; + }); + + function mockOverflow(overflowByTestId: Record) { + window.getComputedStyle = ((element: Element, pseudoElt?: string | null) => { + const result = originalGetComputedStyle(element as Element, pseudoElt); + const testId = (element as HTMLElement).dataset?.testid; + const overflow = testId ? overflowByTestId[testId] : undefined; + if (overflow?.overflowX) { + result.overflowX = overflow.overflowX; + } + if (overflow?.overflowY) { + result.overflowY = overflow.overflowY; + } + return result; + }) as Window['getComputedStyle']; + } + + function renderTree() { + const { container } = render( +
+
+
+
+
+
+
+ ); + const get = (testId: string) => container.querySelector(`[data-testid="${testId}"]`)!; + return { outer: get('outer'), middle: get('middle'), parent: get('parent'), target: get('target') }; + } + + test.each(['auto', 'scroll', 'overlay'])('returns the nearest ancestor with overflow-y: %s', overflowY => { + const { outer, parent, target } = renderTree(); + mockOverflow({ outer: { overflowY: 'auto' }, parent: { overflowY } }); + expect(getFirstScrollableParent(target, { requireOverflow: false })).toBe(parent); + expect(getFirstScrollableParent(parent, { requireOverflow: false })).toBe(outer); + }); + + test('returns the scroll container even when its content does not overflow', () => { + const { outer, middle, target } = renderTree(); + mockOverflow({ outer: { overflowY: 'auto' }, middle: { overflowY: 'auto' } }); + Object.defineProperty(outer, 'scrollHeight', { configurable: true, value: 1000 }); + Object.defineProperty(outer, 'clientHeight', { configurable: true, value: 100 }); + Object.defineProperty(middle, 'scrollHeight', { configurable: true, value: 100 }); + Object.defineProperty(middle, 'clientHeight', { configurable: true, value: 100 }); + + expect(getFirstScrollableParent(target, { requireOverflow: false })).toBe(middle); + expect(getFirstScrollableParent(target)).toBe(outer); + }); + + test('ignores the element itself and ancestors that only scroll horizontally or clip', () => { + const { outer, target } = renderTree(); + mockOverflow({ + target: { overflowY: 'auto' }, + parent: { overflowX: 'auto', overflowY: 'hidden' }, + middle: { overflowY: 'clip' }, + outer: { overflowY: 'scroll' }, + }); + expect(getFirstScrollableParent(target, { requireOverflow: false })).toBe(outer); + }); + + test('returns undefined when no ancestor scrolls vertically', () => { + const { target } = renderTree(); + mockOverflow({ outer: { overflowY: 'visible' }, parent: { overflowY: 'hidden' } }); + expect(getFirstScrollableParent(target, { requireOverflow: false })).toBeUndefined(); + }); + + describe('when the nearest scroll container is the body', () => { + let target: HTMLElement; + + // jsdom does not resolve the initial `visible` value for the root element, so it is set explicitly. + function mockRootOverflow(overflowX: string, overflowY: string) { + window.getComputedStyle = ((element: Element, pseudoElt?: string | null) => { + const result = originalGetComputedStyle(element as Element, pseudoElt); + if (element === document.documentElement) { + result.overflowX = overflowX; + result.overflowY = overflowY; + } + return result; + }) as Window['getComputedStyle']; + } + + beforeEach(() => { + target = document.createElement('div'); + document.body.appendChild(target); + document.body.style.overflowY = 'auto'; + }); + + afterEach(() => { + target.remove(); + document.body.removeAttribute('style'); + document.documentElement.removeAttribute('style'); + }); + + function mockDocument(property: 'scrollingElement' | 'compatMode', value: unknown) { + Object.defineProperty(document, property, { configurable: true, get: () => value }); + } + + afterEach(() => { + delete (document as unknown as Record).scrollingElement; + delete (document as unknown as Record).compatMode; + }); + + test('returns document.scrollingElement when the body overflow propagates to the viewport', () => { + mockRootOverflow('visible', 'visible'); + mockDocument('scrollingElement', document.documentElement); + expect(getFirstScrollableParent(target, { requireOverflow: false })).toBe(document.documentElement); + }); + + test('returns the body as document.scrollingElement in quirks mode', () => { + mockRootOverflow('visible', 'visible'); + mockDocument('compatMode', 'BackCompat'); + mockDocument('scrollingElement', document.body); + expect(getFirstScrollableParent(target, { requireOverflow: false })).toBe(document.body); + }); + + test('falls back to the root element in standards mode when scrollingElement is unavailable', () => { + mockRootOverflow('visible', 'visible'); + mockDocument('scrollingElement', null); + expect(getFirstScrollableParent(target, { requireOverflow: false })).toBe(document.documentElement); + }); + + test('falls back to the body in quirks mode when scrollingElement is unavailable', () => { + mockRootOverflow('visible', 'visible'); + mockDocument('compatMode', 'BackCompat'); + mockDocument('scrollingElement', null); + expect(getFirstScrollableParent(target, { requireOverflow: false })).toBe(document.body); + }); + + test.each([ + ['hidden', 'hidden'], + ['auto', 'auto'], + ['clip', 'clip'], + ['hidden', 'visible'], + ['visible', 'hidden'], + ])('keeps the body as an independent scroller when the root overflow is %s / %s', (overflowX, overflowY) => { + mockRootOverflow(overflowX, overflowY); + expect(getFirstScrollableParent(target, { requireOverflow: false })).toBe(document.body); + }); + + test.each(['documentElement', 'body'] as const)( + 'keeps the body as an independent scroller when %s has CSS containment', + element => { + mockRootOverflow('visible', 'visible'); + mockDocument('scrollingElement', document.documentElement); + document[element].style.contain = 'layout'; + expect(getFirstScrollableParent(target, { requireOverflow: false })).toBe(document.body); + } + ); + + test('treats contain: none as no containment', () => { + mockRootOverflow('visible', 'visible'); + mockDocument('scrollingElement', document.documentElement); + document.body.style.contain = 'none'; + expect(getFirstScrollableParent(target, { requireOverflow: false })).toBe(document.documentElement); + }); + + test('keeps a non-body nearest scroll container unchanged', () => { + mockRootOverflow('visible', 'visible'); + const scroller = document.createElement('div'); + scroller.style.overflowY = 'auto'; + document.body.appendChild(scroller); + scroller.appendChild(target); + try { + expect(getFirstScrollableParent(target, { requireOverflow: false })).toBe(scroller); + } finally { + scroller.remove(); + } + }); + }); +}); diff --git a/src/internal/utils/scrollable-containers.ts b/src/internal/utils/scrollable-containers.ts index fab6aa1cca2..9b0f148834f 100644 --- a/src/internal/utils/scrollable-containers.ts +++ b/src/internal/utils/scrollable-containers.ts @@ -135,7 +135,49 @@ export function getScrollableParents(element: HTMLElement): HTMLElement[] { return parents; } -export function getFirstScrollableParent(element: HTMLElement): HTMLElement | undefined { +// https://drafts.csswg.org/css-overflow-3/#overflow-propagation: when the root element's overflow is visible in +// both axes, the body's overflow applies to the viewport (in standards and quirks mode alike), so the body itself +// does not scroll and the viewport is the actual scroll container. +function isViewportPropagatedBody(node: HTMLElement) { + const root = node.ownerDocument.documentElement; + if (node !== node.ownerDocument.body || node.parentElement !== root) { + return false; + } + const rootStyle = getComputedStyle(root); + // Containment on the root or body disables the propagation, so the body scrolls independently. + const contained = [rootStyle, getComputedStyle(node)].some(style => !!style.contain && style.contain !== 'none'); + return !contained && rootStyle.overflowX === 'visible' && rootStyle.overflowY === 'visible'; +} + +function getDocumentScroller(document: Document): HTMLElement { + const { scrollingElement, compatMode, body, documentElement } = document; + if (isHTMLElement(scrollingElement)) { + return scrollingElement; + } + return compatMode === 'BackCompat' ? body : documentElement; +} + +interface FirstScrollableParentOptions { + /** + * When `false`, returns the nearest ancestor (excluding the element itself) whose computed `overflow-y` is + * `auto`, `scroll` or `overlay`, even if its content does not currently overflow. A `body` whose overflow is + * propagated to the viewport is normalized to the document's scrolling element. Defaults to `true`. + */ + requireOverflow?: boolean; +} + +/** + * Returns the first scrollable element, starting from the element itself, whose `overflow-y` is `auto` or + * `scroll` and whose content currently overflows. See `requireOverflow` for finding the scroll container an + * element lives in regardless of overflow. Returns `undefined` when none is found. + */ +export function getFirstScrollableParent( + element: HTMLElement, + { requireOverflow = true }: FirstScrollableParentOptions = {} +): HTMLElement | undefined { + if (!requireOverflow) { + return getNearestScrollContainer(element); + } return ( findUpUntil(element, el => { const overflows = el.scrollHeight > el.clientHeight; @@ -143,3 +185,14 @@ export function getFirstScrollableParent(element: HTMLElement): HTMLElement | un }) || undefined ); } + +function getNearestScrollContainer(element: HTMLElement): HTMLElement | undefined { + let node = element.parentElement; + while (node) { + if (isHTMLElement(node) && ['auto', 'scroll', 'overlay'].includes(getComputedStyle(node).overflowY)) { + return isViewportPropagatedBody(node) ? getDocumentScroller(node.ownerDocument) : node; + } + node = node.parentElement; + } + return undefined; +} diff --git a/src/list/__tests__/list-sortable.test.tsx b/src/list/__tests__/list-sortable.test.tsx index 1fa2d704e92..5d7ff032946 100644 --- a/src/list/__tests__/list-sortable.test.tsx +++ b/src/list/__tests__/list-sortable.test.tsx @@ -317,13 +317,121 @@ describe('List - Sortable', () => { expect(canAutoScroll(document.documentElement)).toBe(true); }); - test('keeps every container eligible for auto-scroll when the list has no scrollable ancestor', async () => { - const { outer, inner, handle } = renderInScrollContainers({ innerScrolls: false }); + test('limits auto-scroll to the nearest scroll container even when it does not overflow', async () => { + const { outer, inner, item, handle } = renderInScrollContainers({ innerScrolls: false }); await interact(() => pressKey(handle, 'Space')); expect(canAutoScroll(inner)).toBe(true); + expect(canAutoScroll(item)).toBe(true); + expect(canAutoScroll(outer)).toBe(false); + expect(canAutoScroll(document.documentElement)).toBe(false); + + await interact(() => pressKey(handle, 'Escape')); + + expect(canAutoScroll(outer)).toBe(true); + }); + + test('ignores ancestors that only scroll horizontally', async () => { + const { container } = render( +
+
+ ({ id: item.id, content: item.content })} + sortable={true} + /> +
+
+ ); + const outer = container.querySelector('[data-testid="outer"]')!; + const handle = createWrapper(container).findList()!.findItemById('item1')!.findDragHandle()!.getElement(); + + await interact(() => pressKey(handle, 'Space')); + expect(canAutoScroll(outer)).toBe(true); + expect(canAutoScroll(document.documentElement)).toBe(false); + + await interact(() => pressKey(handle, 'Escape')); + }); + + test('keeps the document scroller eligible when the body overflow propagates to the viewport', async () => { + const originalGetComputedStyle = window.getComputedStyle; + // jsdom neither resolves the root's initial overflow: visible nor implements document.scrollingElement. + window.getComputedStyle = ((element: Element, pseudoElt?: string | null) => { + const result = originalGetComputedStyle(element, pseudoElt); + if (element === document.documentElement) { + result.overflowX = 'visible'; + result.overflowY = 'visible'; + } + return result; + }) as Window['getComputedStyle']; + Object.defineProperty(document, 'scrollingElement', { configurable: true, get: () => document.documentElement }); + document.body.style.overflowY = 'auto'; + try { + const { container } = render( + ({ id: item.id, content: item.content })} + sortable={true} + /> + ); + const handle = createWrapper(container).findList()!.findItemById('item1')!.findDragHandle()!.getElement(); + + await interact(() => pressKey(handle, 'Space')); + + expect(canAutoScroll(document.documentElement)).toBe(true); + expect(canAutoScroll(document.body)).toBe(true); + + await interact(() => pressKey(handle, 'Escape')); + } finally { + window.getComputedStyle = originalGetComputedStyle; + delete (document as unknown as Record).scrollingElement; + document.body.style.overflowY = ''; + } + }); + + test('limits auto-scroll to the body when it is an independent scroller', async () => { + document.documentElement.style.overflow = 'hidden'; + document.body.style.overflowY = 'auto'; + try { + const { container } = render( + ({ id: item.id, content: item.content })} + sortable={true} + /> + ); + const handle = createWrapper(container).findList()!.findItemById('item1')!.findDragHandle()!.getElement(); + + await interact(() => pressKey(handle, 'Space')); + + expect(canAutoScroll(document.body)).toBe(true); + expect(canAutoScroll(document.documentElement)).toBe(false); + + await interact(() => pressKey(handle, 'Escape')); + } finally { + document.documentElement.style.overflow = ''; + document.body.style.overflowY = ''; + } + }); + + test('keeps every container eligible for auto-scroll when the list has no scroll container ancestor', async () => { + const { container } = render( +
+ ({ id: item.id, content: item.content })} + sortable={true} + /> +
+ ); + const plain = container.querySelector('[data-testid="plain"]')!; + const handle = createWrapper(container).findList()!.findItemById('item1')!.findDragHandle()!.getElement(); + + await interact(() => pressKey(handle, 'Space')); + + expect(canAutoScroll(plain)).toBe(true); expect(canAutoScroll(document.documentElement)).toBe(true); await interact(() => pressKey(handle, 'Escape'));