-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathuseVirtualizerItem.ts
More file actions
62 lines (54 loc) · 2.31 KB
/
Copy pathuseVirtualizerItem.ts
File metadata and controls
62 lines (54 loc) · 2.31 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
/*
* 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.
*/
import {Key, RefObject} from '@react-types/shared';
import {LayoutInfo, Size} from 'react-stately/useVirtualizerState';
import {useCallback} from 'react';
import {useLayoutEffect} from '../utils/useLayoutEffect';
interface IVirtualizer {
updateItemSize(key: Key, size: Size): void;
}
export interface VirtualizerItemOptions {
layoutInfo: LayoutInfo | null;
virtualizer: IVirtualizer;
ref: RefObject<HTMLElement | null>;
}
export function useVirtualizerItem(options: VirtualizerItemOptions): {updateSize: () => void} {
let {layoutInfo, virtualizer, ref} = options;
let key = layoutInfo?.key;
let updateSize = useCallback(() => {
if (key != null && ref.current) {
// offsetParent is null if element or ancestor has display: none, see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent
// for that case we want to avoid reporting size 0 otherwise we get into a state
// where the virtualizer renders 0 items when it is hidden and thus won't remeasure when it is is unhidden
// in jsdom tests, offsetParent can be null, so skip the check there.
if (!navigator.userAgent.includes('jsdom') && ref.current.offsetParent === null) {
return;
}
let size = getSize(ref.current);
virtualizer.updateItemSize(key, size);
}
}, [virtualizer, key, ref]);
useLayoutEffect(() => {
if (layoutInfo?.estimatedSize) {
updateSize();
}
});
return {updateSize};
}
function getSize(node: HTMLElement): Size {
// Reset height before measuring so we get the intrinsic size
let height = node.style.height;
node.style.height = '';
let size = new Size(node.scrollWidth, node.scrollHeight);
node.style.height = height;
return size;
}