Skip to content

Commit 1fca093

Browse files
committed
Fix horizontal RTL list positioning (#1395)
1 parent 38156db commit 1fca093

7 files changed

Lines changed: 191 additions & 24 deletions

File tree

‎.changeset/fix-horizontal-rtl.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'react-virtuoso': patch
3+
---
4+
5+
Fix horizontal Virtuoso item positioning and scrolling in RTL layouts.
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { expect, test } from '@playwright/test'
2+
3+
import { navigateToExample } from './utils.ts'
4+
5+
import type { Page } from '@playwright/test'
6+
7+
function itemPosition(page: Page, index: number) {
8+
return page.evaluate((index) => {
9+
const scroller = document.querySelector('[data-testid=virtuoso-scroller]')!
10+
const item = document.querySelector(`[data-item-index="${index}"]`)!
11+
const scrollerRect = scroller.getBoundingClientRect()
12+
const itemRect = item.getBoundingClientRect()
13+
14+
return {
15+
itemLeft: Math.round(itemRect.left),
16+
itemRight: Math.round(itemRect.right),
17+
scrollerLeft: Math.round(scrollerRect.left),
18+
scrollerRight: Math.round(scrollerRect.right),
19+
}
20+
}, index)
21+
}
22+
23+
function expectClosePosition(actual: number, expected: number) {
24+
expect(Math.abs(actual - expected)).toBeLessThanOrEqual(1)
25+
}
26+
27+
test.describe('horizontal list in rtl', () => {
28+
test.beforeEach(async ({ baseURL, page }) => {
29+
await navigateToExample(page, baseURL, 'horizontal-rtl')
30+
})
31+
32+
test('renders initial items from the right edge', async ({ page }) => {
33+
const position = await itemPosition(page, 0)
34+
35+
expectClosePosition(position.itemRight, position.scrollerRight)
36+
})
37+
38+
test('scrolls to an index using logical offsets', async ({ page }) => {
39+
await page.click('#start-20')
40+
await expect(page.locator('[data-testid=range]')).toHaveText('20-25')
41+
42+
let position = await itemPosition(page, 20)
43+
expectClosePosition(position.itemRight, position.scrollerRight)
44+
45+
await page.click('#end-20')
46+
await expect(page.locator('[data-testid=range]')).toHaveText('15-20')
47+
48+
position = await itemPosition(page, 20)
49+
expectClosePosition(position.itemLeft, position.scrollerLeft)
50+
})
51+
})
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import * as React from 'react'
2+
3+
import { Virtuoso } from '../src'
4+
5+
import type { ListRange, VirtuosoHandle } from '../src'
6+
7+
const itemStyle: React.CSSProperties = {
8+
alignItems: 'center',
9+
background: '#e8edf5',
10+
border: '1px solid #aeb7c6',
11+
boxSizing: 'border-box',
12+
display: 'flex',
13+
height: '100%',
14+
justifyContent: 'center',
15+
width: 100,
16+
}
17+
18+
export function Example() {
19+
const ref = React.useRef<VirtuosoHandle>(null)
20+
const [range, setRange] = React.useState<ListRange>({ endIndex: 0, startIndex: 0 })
21+
22+
return (
23+
<div style={{ height: 160, width: 520 }}>
24+
<div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
25+
<button
26+
id="start-0"
27+
onClick={() => {
28+
ref.current!.scrollToIndex({ align: 'start', index: 0 })
29+
}}
30+
>
31+
Start 0
32+
</button>
33+
<button
34+
id="start-20"
35+
onClick={() => {
36+
ref.current!.scrollToIndex({ align: 'start', index: 20 })
37+
}}
38+
>
39+
Start 20
40+
</button>
41+
<button
42+
id="end-20"
43+
onClick={() => {
44+
ref.current!.scrollToIndex({ align: 'end', index: 20 })
45+
}}
46+
>
47+
End 20
48+
</button>
49+
<span data-testid="range">
50+
{range.startIndex}-{range.endIndex}
51+
</span>
52+
</div>
53+
<Virtuoso
54+
computeItemKey={(key: number) => `item-${key.toString()}`}
55+
horizontalDirection
56+
itemContent={(index) => <div style={itemStyle}>Item {index}</div>}
57+
rangeChanged={setRange}
58+
ref={ref}
59+
style={{ direction: 'rtl', height: 100, width: '100%' }}
60+
totalCount={100}
61+
/>
62+
</div>
63+
)
64+
}

‎packages/react-virtuoso/src/Virtuoso.tsx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,9 +128,9 @@ const Items = /*#__PURE__*/ React.memo(function VirtuosoItems({ showTopList = fa
128128
? {
129129
display: 'inline-block',
130130
height: '100%',
131-
marginLeft: deviation !== 0 ? deviation : alignToBottom ? 'auto' : 0,
132-
paddingLeft: listState.offsetTop,
133-
paddingRight: listState.offsetBottom,
131+
marginInlineStart: deviation !== 0 ? deviation : alignToBottom ? 'auto' : 0,
132+
paddingInlineEnd: listState.offsetBottom,
133+
paddingInlineStart: listState.offsetTop,
134134
whiteSpace: 'nowrap',
135135
}
136136
: {

‎packages/react-virtuoso/src/hooks/useChangedChildSizes.ts‎

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import React from 'react'
22

33
import { LogLevel } from '../loggerSystem'
4+
import { getLogicalScrollLeft } from '../utils/horizontalScroll'
45
import { useSizeWithElRef } from './useSize'
56

67
import type { ScrollContainerState, SizeFunction, SizeRange } from '../interfaces'
@@ -31,18 +32,6 @@ export default function useChangedListContentsSizes(
3132
theWindow = scrollableElement.ownerDocument.defaultView!
3233
}
3334

34-
const scrollTop = customScrollParent
35-
? horizontalDirection
36-
? customScrollParent.scrollLeft
37-
: customScrollParent.scrollTop
38-
: windowScrolling
39-
? horizontalDirection
40-
? theWindow.scrollX || theWindow.document.documentElement.scrollLeft
41-
: theWindow.scrollY || theWindow.document.documentElement.scrollTop
42-
: horizontalDirection
43-
? scrollableElement.scrollLeft
44-
: scrollableElement.scrollTop
45-
4635
const scrollHeight = customScrollParent
4736
? horizontalDirection
4837
? customScrollParent.scrollWidth
@@ -67,6 +56,18 @@ export default function useChangedListContentsSizes(
6756
? scrollableElement.offsetWidth
6857
: scrollableElement.offsetHeight
6958

59+
const scrollTop = customScrollParent
60+
? horizontalDirection
61+
? getLogicalScrollLeft(customScrollParent, customScrollParent.scrollLeft)
62+
: customScrollParent.scrollTop
63+
: windowScrolling
64+
? horizontalDirection
65+
? getLogicalScrollLeft(theWindow, theWindow.scrollX || theWindow.document.documentElement.scrollLeft)
66+
: theWindow.scrollY || theWindow.document.documentElement.scrollTop
67+
: horizontalDirection
68+
? getLogicalScrollLeft(scrollableElement, scrollableElement.scrollLeft)
69+
: scrollableElement.scrollTop
70+
7071
scrollContainerStateCallback({
7172
scrollHeight,
7273
scrollTop: Math.max(scrollTop, 0),

‎packages/react-virtuoso/src/hooks/useScrollTop.ts‎

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import ReactDOM from 'react-dom'
44
import * as u from '../urx'
55
import { approximatelyEqual } from '../utils/approximatelyEqual'
66
import { correctItemSize } from '../utils/correctItemSize'
7+
import { clearHorizontalScrollDirectionCache, getLogicalScrollLeft, getPhysicalScrollLeft } from '../utils/horizontalScroll'
78

89
import type { ScrollContainerState } from '../interfaces'
910

@@ -39,14 +40,14 @@ export default function useScrollTop(
3940

4041
if (isDocument(el) || isWindow(el)) {
4142
const theWindow = isWindow(el) ? el : (el as unknown as Document).defaultView!
42-
scrollTop = horizontalDirection === true ? theWindow.scrollX : theWindow.scrollY
43+
scrollTop = horizontalDirection === true ? getLogicalScrollLeft(theWindow, theWindow.scrollX) : theWindow.scrollY
4344

4445
scrollHeight =
4546
horizontalDirection === true ? theWindow.document.documentElement.scrollWidth : theWindow.document.documentElement.scrollHeight
4647

4748
viewportHeight = horizontalDirection === true ? theWindow.innerWidth : theWindow.innerHeight
4849
} else {
49-
scrollTop = horizontalDirection === true ? el.scrollLeft : el.scrollTop
50+
scrollTop = horizontalDirection === true ? getLogicalScrollLeft(el, el.scrollLeft) : el.scrollTop
5051

5152
scrollHeight = horizontalDirection === true ? el.scrollWidth : el.scrollHeight
5253

@@ -83,11 +84,13 @@ export default function useScrollTop(
8384
React.useEffect(() => {
8485
const localRef = customScrollParent ? customScrollParent : scrollerRef.current!
8586

87+
clearHorizontalScrollDirectionCache(localRef)
8688
scrollerRefCallback(customScrollParent ? customScrollParent : scrollerRef.current)
8789
handler({ suppressFlushSync: true, target: localRef } as unknown as Event)
8890
localRef.addEventListener('scroll', handler, { passive: true })
8991

9092
return () => {
93+
clearHorizontalScrollDirectionCache(localRef)
9194
scrollerRefCallback(null)
9295
localRef.removeEventListener('scroll', handler)
9396
}
@@ -119,20 +122,27 @@ export default function useScrollTop(
119122
: scrollerElement.document.documentElement.scrollHeight
120123
)
121124
offsetHeight = horizontalDirection === true ? scrollerElement.innerWidth : scrollerElement.innerHeight
122-
scrollTop = horizontalDirection === true ? window.scrollX : window.scrollY
125+
scrollTop = horizontalDirection === true ? getLogicalScrollLeft(scrollerElement, scrollerElement.scrollX) : scrollerElement.scrollY
123126
} else {
124127
scrollHeight = scrollerElement[horizontalDirection === true ? 'scrollWidth' : 'scrollHeight']
125128
offsetHeight = correctItemSize(scrollerElement, horizontalDirection === true ? 'width' : 'height')
126-
scrollTop = scrollerElement[horizontalDirection === true ? 'scrollLeft' : 'scrollTop']
129+
scrollTop =
130+
horizontalDirection === true ? getLogicalScrollLeft(scrollerElement, scrollerElement.scrollLeft) : scrollerElement.scrollTop
127131
}
128132

129133
const maxScrollTop = scrollHeight - offsetHeight
130-
location.top = Math.ceil(Math.max(Math.min(maxScrollTop, location.top!), 0))
134+
if (location.top === undefined) {
135+
scrollerElement.scrollTo(location)
136+
return
137+
}
138+
139+
const top = Math.ceil(Math.max(Math.min(maxScrollTop, location.top), 0))
140+
location.top = top
131141

132142
// avoid system hanging because the DOM never called back
133143
// with the scrollTop
134144
// scroller is already at this location
135-
if (approximatelyEqual(offsetHeight, scrollHeight) || location.top === scrollTop) {
145+
if (approximatelyEqual(offsetHeight, scrollHeight) || top === scrollTop) {
136146
scrollContainerStateCallback({ scrollHeight, scrollTop, viewportHeight: offsetHeight })
137147
if (isSmooth) {
138148
smoothScrollTargetReached(true)
@@ -141,7 +151,7 @@ export default function useScrollTop(
141151
}
142152

143153
if (isSmooth) {
144-
scrollTopTarget.current = location.top
154+
scrollTopTarget.current = top
145155
if (timeoutRef.current) {
146156
clearTimeout(timeoutRef.current)
147157
}
@@ -156,7 +166,10 @@ export default function useScrollTop(
156166
}
157167

158168
if (horizontalDirection === true) {
159-
location = { ...(location.behavior !== undefined ? { behavior: location.behavior } : {}), left: location.top }
169+
location = {
170+
...(location.behavior !== undefined ? { behavior: location.behavior } : {}),
171+
left: getPhysicalScrollLeft(scrollerElement, top),
172+
}
160173
}
161174

162175
scrollerElement.scrollTo(location)
@@ -166,7 +179,7 @@ export default function useScrollTop(
166179
if (horizontalDirection === true) {
167180
location = {
168181
...(location.behavior !== undefined ? { behavior: location.behavior } : {}),
169-
...(location.top !== undefined ? { left: location.top } : {}),
182+
...(location.top !== undefined ? { left: getPhysicalScrollLeft(scrollerRef.current!, location.top) } : {}),
170183
}
171184
}
172185
scrollerRef.current!.scrollBy(location)
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
const cachedRtlElements = new WeakMap<HTMLElement, boolean>()
2+
3+
function scrollerElement(scroller: HTMLElement | Window) {
4+
return 'self' in scroller ? scroller.document.documentElement : scroller
5+
}
6+
7+
function isRtl(scroller: HTMLElement | Window) {
8+
const element = scrollerElement(scroller)
9+
const cached = cachedRtlElements.get(element)
10+
11+
if (cached !== undefined) {
12+
return cached
13+
}
14+
15+
const value = element.ownerDocument.defaultView!.getComputedStyle(element).direction === 'rtl'
16+
cachedRtlElements.set(element, value)
17+
return value
18+
}
19+
20+
export function clearHorizontalScrollDirectionCache(scroller: HTMLElement | Window) {
21+
cachedRtlElements.delete(scrollerElement(scroller))
22+
}
23+
24+
function convertHorizontalScrollLeft(scroller: HTMLElement | Window, scrollLeft: number) {
25+
// Supported browsers expose RTL horizontal scrolling as 0 at the right edge
26+
// and negative values while scrolling left, making the conversion symmetric.
27+
return isRtl(scroller) ? -scrollLeft : scrollLeft
28+
}
29+
30+
export const getLogicalScrollLeft = convertHorizontalScrollLeft
31+
export function getPhysicalScrollLeft(scroller: HTMLElement | Window, scrollLeft: number) {
32+
return convertHorizontalScrollLeft(scroller, scrollLeft)
33+
}

0 commit comments

Comments
 (0)