Skip to content

Commit 8a11e76

Browse files
authored
feat: support offset (#63)
1 parent 137588e commit 8a11e76

File tree

3 files changed

+32
-4
lines changed

3 files changed

+32
-4
lines changed

examples/basic.tsx

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,30 @@ const Demo = () => {
113113
>
114114
Scroll To 50 (auto)
115115
</button>
116+
<button
117+
type="button"
118+
onClick={() => {
119+
listRef.current.scrollTo({
120+
index: 50,
121+
align: 'top',
122+
offset: 15,
123+
});
124+
}}
125+
>
126+
Scroll To 50 (top) + 15 offset
127+
</button>
128+
<button
129+
type="button"
130+
onClick={() => {
131+
listRef.current.scrollTo({
132+
index: 50,
133+
align: 'bottom',
134+
offset: 15,
135+
});
136+
}}
137+
>
138+
Scroll To 50 (bottom) + 15 offset
139+
</button>
116140
<button
117141
type="button"
118142
onClick={() => {

src/List.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,12 @@ export type ScrollConfig =
2424
| {
2525
index: number;
2626
align?: ScrollAlign;
27+
offset?: number;
2728
}
2829
| {
2930
key: React.Key;
3031
align?: ScrollAlign;
32+
offset?: number;
3133
};
3234
export type ScrollTo = (arg: number | ScrollConfig) => void;
3335
export type ListRef = {

src/hooks/useScrollTo.tsx

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ export default function useScrollTo<T>(
1616
): ScrollTo {
1717
const scrollRef = React.useRef<number>();
1818

19-
return arg => {
19+
return (arg) => {
2020
raf.cancel(scrollRef.current);
2121

2222
if (typeof arg === 'number') {
@@ -28,9 +28,11 @@ export default function useScrollTo<T>(
2828
if ('index' in arg) {
2929
({ index } = arg);
3030
} else {
31-
index = data.findIndex(item => getKey(item) === arg.key);
31+
index = data.findIndex((item) => getKey(item) === arg.key);
3232
}
3333

34+
const { offset = 0 } = arg;
35+
3436
// We will retry 3 times in case dynamic height shaking
3537
const syncScroll = (times: number, targetAlign?: 'top' | 'bottom') => {
3638
if (times < 0 || !containerRef.current) return;
@@ -66,10 +68,10 @@ export default function useScrollTo<T>(
6668

6769
switch (mergedAlign) {
6870
case 'top':
69-
targetTop = itemTop;
71+
targetTop = itemTop - offset;
7072
break;
7173
case 'bottom':
72-
targetTop = itemBottom - height;
74+
targetTop = itemBottom - height + offset;
7375
break;
7476

7577
default: {

0 commit comments

Comments
 (0)