-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathScrollView.tsx
More file actions
342 lines (299 loc) · 12.8 KB
/
ScrollView.tsx
File metadata and controls
342 lines (299 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
// @ts-ignore
import {flushSync} from 'react-dom';
import {getEventTarget, nodeContains, useEffectEvent, useLayoutEffect, useObjectRef, useResizeObserver} from '@react-aria/utils';
import {getScrollLeft} from './utils';
import {Point, Rect, Size} from '@react-stately/virtualizer';
import React, {
CSSProperties,
ForwardedRef,
HTMLAttributes,
ReactNode,
RefObject,
useCallback,
useEffect,
useRef,
useState
} from 'react';
import {useLocale} from '@react-aria/i18n';
interface ScrollViewProps extends Omit<HTMLAttributes<HTMLElement>, 'onScroll'> {
contentSize: Size,
onVisibleRectChange: (rect: Rect) => void,
children?: ReactNode,
innerStyle?: CSSProperties,
onScrollStart?: () => void,
onScrollEnd?: () => void,
scrollDirection?: 'horizontal' | 'vertical' | 'both',
onScroll?: (e: Event) => void
}
function ScrollView(props: ScrollViewProps, ref: ForwardedRef<HTMLDivElement | null>) {
ref = useObjectRef(ref);
let {scrollViewProps, contentProps} = useScrollView(props, ref);
return (
<div role="presentation" {...scrollViewProps} ref={ref}>
<div {...contentProps}>
{props.children}
</div>
</div>
);
}
const ScrollViewForwardRef:
React.ForwardRefExoticComponent<ScrollViewProps & React.RefAttributes<HTMLDivElement | null>> =
React.forwardRef(ScrollView);
export {ScrollViewForwardRef as ScrollView};
interface ScrollViewAria {
isScrolling: boolean,
scrollViewProps: HTMLAttributes<HTMLElement>,
contentProps: HTMLAttributes<HTMLElement>
}
export function useScrollView(props: ScrollViewProps, ref: RefObject<HTMLElement | null>): ScrollViewAria {
let {
contentSize,
onVisibleRectChange,
innerStyle,
onScrollStart,
onScrollEnd,
scrollDirection = 'both',
onScroll: onScrollProp,
...otherProps
} = props;
let state = useRef({
// Internal scroll position of the scroll view.
scrollPosition: new Point(),
// Size of the scroll view.
size: new Size(),
// Offset of the scroll view relative to the window viewport.
viewportOffset: new Point(),
// Size of the window viewport.
viewportSize: new Size(),
scrollEndTime: 0,
scrollTimeout: null as ReturnType<typeof setTimeout> | null,
isScrolling: false
}).current;
let {direction} = useLocale();
let updateVisibleRect = useCallback(() => {
// Intersect the window viewport with the scroll view itself to find the actual visible rectangle.
// This allows virtualized components to have unbounded height but still virtualize when scrolled with the page.
// While there may be other scrollable elements between the <body> and the scroll view, we do not take
// their sizes into account for performance reasons. Their scroll positions are accounted for in viewportOffset
// though (due to getBoundingClientRect). This may result in more rows than absolutely necessary being rendered,
// but no more than the entire height of the viewport which is good enough for virtualization use cases.
let visibleRect = new Rect(
state.viewportOffset.x + state.scrollPosition.x,
state.viewportOffset.y + state.scrollPosition.y,
Math.max(0, Math.min(state.size.width - state.viewportOffset.x, state.viewportSize.width)),
Math.max(0, Math.min(state.size.height - state.viewportOffset.y, state.viewportSize.height))
);
onVisibleRectChange(visibleRect);
}, [state, onVisibleRectChange]);
let [isScrolling, setScrolling] = useState(false);
let onScroll = useCallback((e: Event) => {
let target = getEventTarget(e) as Element;
if (!nodeContains(target, ref.current!)) {
return;
}
if (onScrollProp && target === ref.current) {
onScrollProp(e);
}
if (target !== ref.current) {
// An ancestor element or the window was scrolled. Update the position of the scroll view relative to the viewport.
let boundingRect = ref.current!.getBoundingClientRect();
let x = boundingRect.x < 0 ? -boundingRect.x : 0;
let y = boundingRect.y < 0 ? -boundingRect.y : 0;
if (x === state.viewportOffset.x && y === state.viewportOffset.y) {
return;
}
state.viewportOffset = new Point(x, y);
} else {
// The scroll view itself was scrolled. Update the local scroll position.
// Prevent rubber band scrolling from shaking when scrolling out of bounds
let scrollTop = target.scrollTop;
let scrollLeft = getScrollLeft(target, direction);
state.scrollPosition = new Point(
Math.max(0, Math.min(scrollLeft, contentSize.width - state.size.width)),
Math.max(0, Math.min(scrollTop, contentSize.height - state.size.height))
);
}
flushSync(() => {
updateVisibleRect();
if (!state.isScrolling) {
state.isScrolling = true;
setScrolling(true);
// Pause typekit MutationObserver during scrolling.
window.dispatchEvent(new Event('tk.disconnect-observer'));
if (onScrollStart) {
onScrollStart();
}
}
// So we don't constantly call clearTimeout and setTimeout,
// keep track of the current timeout time and only reschedule
// the timer when it is getting close.
let now = Date.now();
if (state.scrollEndTime <= now + 50) {
state.scrollEndTime = now + 300;
if (state.scrollTimeout != null) {
clearTimeout(state.scrollTimeout);
}
state.scrollTimeout = setTimeout(() => {
state.isScrolling = false;
setScrolling(false);
state.scrollTimeout = null;
window.dispatchEvent(new Event('tk.connect-observer'));
if (onScrollEnd) {
onScrollEnd();
}
}, 300);
}
});
}, [onScrollProp, ref, direction, state, contentSize, updateVisibleRect, onScrollStart, onScrollEnd]);
// Attach a document-level capturing scroll listener so we can account for scrollable ancestors.
useEffect(() => {
document.addEventListener('scroll', onScroll, true);
return () => document.removeEventListener('scroll', onScroll, true);
}, [onScroll]);
useEffect(() => {
return () => {
if (state.scrollTimeout != null) {
clearTimeout(state.scrollTimeout);
}
if (state.isScrolling) {
window.dispatchEvent(new Event('tk.connect-observer'));
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
let isUpdatingSize = useRef(false);
let updateSize = useCallback((flush: typeof flushSync) => {
let dom = ref.current;
if (!dom || isUpdatingSize.current) {
return;
}
// Prevent reentrancy when resize observer fires, triggers re-layout that results in
// content size update, causing below layout effect to fire. This avoids infinite loops.
isUpdatingSize.current = true;
let isTestEnv = process.env.NODE_ENV === 'test' && !process.env.VIRT_ON;
let isClientWidthMocked = Object.getOwnPropertyNames(window.HTMLElement.prototype).includes('clientWidth');
let isClientHeightMocked = Object.getOwnPropertyNames(window.HTMLElement.prototype).includes('clientHeight');
let clientWidth = dom.clientWidth;
let clientHeight = dom.clientHeight;
let w = isTestEnv && !isClientWidthMocked ? Infinity : clientWidth;
let h = isTestEnv && !isClientHeightMocked ? Infinity : clientHeight;
// Update the window viewport size.
let viewportWidth = window.innerWidth;
let viewportHeight = window.innerHeight;
let viewportSizeChanged = state.viewportSize.width !== viewportWidth || state.viewportSize.height !== viewportHeight;
if (viewportSizeChanged) {
state.viewportSize = new Rect(viewportWidth, viewportHeight);
}
if (state.size.width !== w || state.size.height !== h || viewportSizeChanged) {
state.size = new Size(w, h);
flush(() => {
updateVisibleRect();
});
// If the clientWidth or clientHeight changed, scrollbars appeared or disappeared as
// a result of the layout update. In this case, re-layout again to account for the
// adjusted space. In very specific cases this might result in the scrollbars disappearing
// again, resulting in extra padding. We stop after a maximum of two layout passes to avoid
// an infinite loop. This matches how browsers behavior with native CSS grid layout.
if (!isTestEnv && clientWidth !== dom.clientWidth || clientHeight !== dom.clientHeight) {
state.size = new Size(dom.clientWidth, dom.clientHeight);
flush(() => {
updateVisibleRect();
});
}
}
isUpdatingSize.current = false;
}, [ref, state, updateVisibleRect]);
let updateSizeEvent = useEffectEvent(updateSize);
// Track the size of the entire window viewport, which is used to bound the size of the virtualizer's visible rectangle.
useLayoutEffect(() => {
// Initialize viewportRect before updating size for the first time.
state.viewportSize = new Size(window.innerWidth, window.innerHeight);
let onWindowResize = () => {
updateSizeEvent(flushSync);
};
window.addEventListener('resize', onWindowResize);
return () => window.removeEventListener('resize', onWindowResize);
}, [state]);
// Update visible rect when the content size changes, in case scrollbars need to appear or disappear.
let lastContentSize = useRef<Size | null>(null);
let [update, setUpdate] = useState({});
// We only contain a call to setState in here for testing environments.
// eslint-disable-next-line react-hooks/exhaustive-deps
useLayoutEffect(() => {
if (!isUpdatingSize.current && (lastContentSize.current == null || !contentSize.equals(lastContentSize.current))) {
// React doesn't allow flushSync inside effects, so queue a microtask.
// We also need to wait until all refs are set (e.g. when passing a ref down from a parent).
// If we are in an `act` environment, update immediately without a microtask so you don't need
// to mock timers in tests. In this case, the update is synchronous already.
// IS_REACT_ACT_ENVIRONMENT is used by React 18. Previous versions checked for the `jest` global.
// https://github.com/reactwg/react-18/discussions/102
// @ts-ignore
if (typeof IS_REACT_ACT_ENVIRONMENT === 'boolean' ? IS_REACT_ACT_ENVIRONMENT : typeof jest !== 'undefined') {
// This is so we update size in a separate render but within the same act. Needs to be setState instead of refs
// due to strict mode.
setUpdate({});
lastContentSize.current = contentSize;
return;
} else {
queueMicrotask(() => updateSizeEvent(flushSync));
}
}
lastContentSize.current = contentSize;
});
// Will only run in tests, needs to be in separate effect so it is properly run in the next render in strict mode.
useLayoutEffect(() => {
updateSizeEvent(fn => fn());
}, [update]);
let onResize = useCallback(() => {
updateSize(flushSync);
}, [updateSize]);
// Watch border-box instead of of content-box so that we don't go into
// an infinite loop when scrollbars appear or disappear.
useResizeObserver({ref, box: 'border-box', onResize});
let style: React.CSSProperties = {
// Reset padding so that relative positioning works correctly. Padding will be done in JS layout.
padding: 0,
...otherProps.style
};
if (scrollDirection === 'horizontal') {
style.overflowX = 'auto';
style.overflowY = 'hidden';
} else if (scrollDirection === 'vertical' || contentSize.width === state.size.width) {
// Set overflow-x: hidden if content size is equal to the width of the scroll view.
// This prevents horizontal scrollbars from flickering during resizing due to resize observer
// firing slower than the frame rate, which may cause an infinite re-render loop.
style.overflowY = 'auto';
style.overflowX = 'hidden';
} else {
style.overflow = 'auto';
}
innerStyle = {
width: Number.isFinite(contentSize.width) ? contentSize.width : undefined,
height: Number.isFinite(contentSize.height) ? contentSize.height : undefined,
pointerEvents: isScrolling ? 'none' : 'auto',
position: 'relative',
...innerStyle
};
return {
isScrolling,
scrollViewProps: {
...otherProps,
style
},
contentProps: {
role: 'presentation',
style: innerStyle
}
};
}