forked from stackblitz-labs/use-stick-to-bottom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseStickToBottom.ts
536 lines (435 loc) · 14.5 KB
/
useStickToBottom.ts
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
import {
type DependencyList,
type MutableRefObject,
useCallback,
useMemo,
useRef,
useState,
type RefCallback,
} from 'react';
interface StickToBottomState {
scrollTop: number;
lastScrollTop?: number;
ignoreScrollToTop?: number;
targetScrollTop: number;
calculatedTargetScrollTop: number;
scrollDifference: number;
resizeDifference: number;
animation?: {
behavior: 'instant' | Required<SpringAnimation>;
ignoreEscapes: boolean;
promise: Promise<boolean>;
};
lastTick?: number;
velocity: number;
accumulated: number;
escapedFromLock: boolean;
isAtBottom: boolean;
isNearBottom: boolean;
resizeObserver?: ResizeObserver;
}
const DEFAULT_SPRING_ANIMATION = {
/**
* A value from 0 to 1, on how much to damp the animation.
* 0 means no damping, 1 means full damping.
*
* @default 0.7
*/
damping: 0.7,
/**
* The stiffness of how fast/slow the animation gets up to speed.
*
* @default 0.05
*/
stiffness: 0.05,
/**
* The inertial mass associated with the animation.
* Higher numbers make the animation slower.
*
* @default 1.25
*/
mass: 1.25,
};
export interface SpringAnimation extends Partial<typeof DEFAULT_SPRING_ANIMATION> {}
export type Animation = ScrollBehavior | SpringAnimation;
export interface ScrollElements {
scrollElement: HTMLElement;
contentElement: HTMLElement;
}
export type GetTargetScrollTop = (targetScrollTop: number, context: ScrollElements) => number;
export interface StickToBottomOptions extends SpringAnimation {
resize?: Animation;
initial?: Animation | boolean;
targetScrollTop?: GetTargetScrollTop;
}
export type ScrollToBottomOptions =
| ScrollBehavior
| {
animation?: Animation;
/**
* Whether to wait for any existing scrolls to finish before
* performing this one. Or if a millisecond is passed,
* it will wait for that duration before performing the scroll.
*
* @default false
*/
wait?: boolean | number;
/**
* Whether to prevent the user from escaping the scroll,
* by scrolling up with their mouse.
*/
ignoreEscapes?: boolean;
/**
* Only scroll to the bottom if we're already at the bottom.
*
* @default false
*/
preserveScrollPosition?: boolean;
/**
* The duration in ms that this scroll event should persist for.
* Not to be confused with the duration of the animation -
* for that you should adjust the animation option.
*
* @default 350
*/
duration?: number | Promise<void>;
};
export type ScrollToBottom = (scrollOptions?: ScrollToBottomOptions) => Promise<boolean> | boolean;
const STICK_TO_BOTTOM_OFFSET_PX = 70;
const SIXTY_FPS_INTERVAL_MS = 1000 / 60;
const RETAIN_ANIMATION_DURATION_MS = 350;
export const useStickToBottom = (options: StickToBottomOptions = {}) => {
const [escapedFromLock, updateEscapedFromLock] = useState(false);
const [isAtBottom, updateIsAtBottom] = useState(options.initial !== false);
const [isNearBottom, setIsNearBottom] = useState(false);
const optionsRef = useRef<StickToBottomOptions>(null!);
optionsRef.current = options;
const setIsAtBottom = useCallback((isAtBottom: boolean) => {
state.isAtBottom = isAtBottom;
updateIsAtBottom(isAtBottom);
}, []);
const setEscapedFromLock = useCallback((escapedFromLock: boolean) => {
state.escapedFromLock = escapedFromLock;
updateEscapedFromLock(escapedFromLock);
}, []);
const state = useMemo<StickToBottomState>(() => {
let lastCalculation: { targetScrollTop: number; calculatedScrollTop: number } | undefined;
return {
escapedFromLock,
isAtBottom,
resizeDifference: 0,
accumulated: 0,
velocity: 0,
listeners: new Set(),
get scrollTop() {
return scrollRef.current?.scrollTop ?? 0;
},
set scrollTop(scrollTop: number) {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollTop;
state.ignoreScrollToTop = scrollRef.current.scrollTop;
}
},
get targetScrollTop() {
if (!scrollRef.current || !contentRef.current) {
return 0;
}
return scrollRef.current.scrollHeight - 1 - scrollRef.current.clientHeight;
},
get calculatedTargetScrollTop() {
if (!scrollRef.current || !contentRef.current) {
return 0;
}
const { targetScrollTop } = this;
if (!options.targetScrollTop) {
return targetScrollTop;
}
if (lastCalculation?.targetScrollTop === targetScrollTop) {
return lastCalculation.calculatedScrollTop;
}
const calculatedScrollTop = Math.max(
Math.min(
options.targetScrollTop(targetScrollTop, {
scrollElement: scrollRef.current,
contentElement: contentRef.current,
}),
targetScrollTop
),
0
);
lastCalculation = { targetScrollTop, calculatedScrollTop };
requestAnimationFrame(() => {
lastCalculation = undefined;
});
return calculatedScrollTop;
},
get scrollDifference() {
return this.calculatedTargetScrollTop - this.scrollTop;
},
get isNearBottom() {
return this.scrollDifference <= STICK_TO_BOTTOM_OFFSET_PX;
},
};
}, []);
const scrollToBottom = useCallback<ScrollToBottom>((scrollOptions = {}) => {
if (typeof scrollOptions === 'string') {
scrollOptions = { animation: scrollOptions };
}
if (!scrollOptions.preserveScrollPosition) {
setIsAtBottom(true);
}
const waitElapsed = Date.now() + (Number(scrollOptions.wait) || 0);
const behavior = mergeAnimations(optionsRef.current, scrollOptions.animation);
const { ignoreEscapes = false } = scrollOptions;
let durationElapsed: number;
let startTarget = state.calculatedTargetScrollTop;
if (scrollOptions.duration instanceof Promise) {
scrollOptions.duration.finally(() => {
durationElapsed = Date.now();
});
} else {
durationElapsed =
waitElapsed + (scrollOptions.duration ?? (behavior === 'instant' ? 0 : RETAIN_ANIMATION_DURATION_MS));
}
const next = async (): Promise<boolean> => {
const promise = new Promise(requestAnimationFrame).then(() => {
if (!state.isAtBottom) {
state.animation = undefined;
return false;
}
const { scrollTop } = state;
const tick = performance.now();
const tickDelta = (tick - (state.lastTick ?? tick)) / SIXTY_FPS_INTERVAL_MS;
state.animation ||= { behavior, promise, ignoreEscapes };
if (state.animation.behavior === behavior) {
state.lastTick = tick;
}
if (waitElapsed > Date.now()) {
return next();
}
if (scrollTop < Math.min(startTarget, state.calculatedTargetScrollTop)) {
if (state.animation?.behavior === behavior) {
if (behavior === 'instant') {
state.scrollTop = state.calculatedTargetScrollTop;
return next();
}
state.velocity =
(behavior.damping * state.velocity + behavior.stiffness * state.scrollDifference) / behavior.mass;
state.accumulated += state.velocity * tickDelta;
state.scrollTop += state.accumulated;
if (state.scrollTop !== scrollTop) {
state.accumulated = 0;
}
}
return next();
}
if (durationElapsed > Date.now()) {
startTarget = state.calculatedTargetScrollTop;
return next();
}
state.animation = undefined;
/**
* If we're still below the target, then queue
* up another scroll to the bottom with the last
* requested animatino.
*/
if (state.scrollTop < state.calculatedTargetScrollTop) {
return scrollToBottom({
animation: mergeAnimations(optionsRef.current, optionsRef.current.resize),
ignoreEscapes,
});
}
return state.isAtBottom;
});
return promise.then((isAtBottom) => {
requestAnimationFrame(() => {
if (!state.animation) {
state.lastTick = undefined;
state.velocity = 0;
}
});
return isAtBottom;
});
};
if (scrollOptions.wait !== true) {
state.animation = undefined;
}
if (state.animation?.behavior === behavior) {
return state.animation.promise;
}
return next();
}, []);
const handleScroll = useCallback(({ target }: Event) => {
if (target !== scrollRef.current) {
return;
}
const { scrollTop, ignoreScrollToTop } = state;
let { lastScrollTop = scrollTop } = state;
state.lastScrollTop = scrollTop;
state.ignoreScrollToTop = undefined;
if (ignoreScrollToTop && ignoreScrollToTop > scrollTop) {
/**
* When the user scrolls up while the animation plays, the `scrollTop` may
* not come in separate events; if this happens, to make sure `isScrollingUp`
* is correct, set the lastScrollTop to the ignored event.
*/
lastScrollTop = ignoreScrollToTop;
}
setIsNearBottom(state.isNearBottom);
/**
* Scroll events may come before a ResizeObserver event,
* so in order to ignore resize events correctly we use a
* timeout.
*
* @see https://github.com/WICG/resize-observer/issues/25#issuecomment-248757228
*/
setTimeout(() => {
/**
* When theres a resize difference ignore the resize event.
*/
if (state.resizeDifference || scrollTop === ignoreScrollToTop) {
return;
}
const isScrollingDown = scrollTop > lastScrollTop;
const isScrollingUp = scrollTop < lastScrollTop;
if (state.animation?.ignoreEscapes) {
state.scrollTop = lastScrollTop;
return;
}
if (isScrollingUp) {
setEscapedFromLock(true);
setIsAtBottom(false);
}
if (isScrollingDown) {
setEscapedFromLock(false);
}
if (!state.escapedFromLock && state.isNearBottom) {
setIsAtBottom(true);
}
}, 1);
}, []);
const handleWheel = useCallback(({ target, deltaY }: WheelEvent) => {
let element = target as HTMLElement;
while (!['scroll', 'auto'].includes(getComputedStyle(element).overflow)) {
if (!element.parentElement) {
return;
}
element = element.parentElement;
}
/**
* The browser may cancel the scrolling from the mouse wheel
* if we update it from the animation in meantime.
* To prevent this, always escape when the wheel is scrolled up.
*/
if (
element === scrollRef.current &&
deltaY < 0 &&
scrollRef.current.scrollHeight > scrollRef.current.clientHeight &&
!state.animation?.ignoreEscapes
) {
setEscapedFromLock(true);
setIsAtBottom(false);
}
}, []);
const scrollRef = useRefCallback((scroll) => {
scrollRef.current?.removeEventListener('scroll', handleScroll);
scrollRef.current?.removeEventListener('wheel', handleWheel);
scroll?.addEventListener('scroll', handleScroll, { passive: true });
scroll?.addEventListener('wheel', handleWheel);
}, []);
const contentRef = useRefCallback((content) => {
state.resizeObserver?.disconnect();
if (!content) {
return;
}
let previousHeight: number | undefined;
state.resizeObserver = new ResizeObserver(([entry]) => {
const { height } = entry.contentRect;
const difference = height - (previousHeight ?? height);
state.resizeDifference = difference;
/**
* Sometimes the browser can overscroll past the target,
* so check for this and adjust appropriately.
*/
if (state.scrollTop > state.targetScrollTop) {
state.scrollTop = state.targetScrollTop;
}
setIsNearBottom(state.isNearBottom);
if (difference >= 0) {
/**
* If it's a positive resize, scroll to the bottom when
* we're already at the bottom.
*/
const animation = mergeAnimations(
optionsRef.current,
previousHeight ? optionsRef.current.resize : optionsRef.current.initial
);
scrollToBottom({ animation, wait: true, preserveScrollPosition: true });
} else {
/**
* Else if it's a negative resize, check if we're near the bottom
* if we are want to un-escape from the lock, because the resize
* could have caused the container to be at the bottom.
*/
if (state.isNearBottom) {
setEscapedFromLock(false);
setIsAtBottom(true);
}
}
previousHeight = height;
/**
* Reset the resize difference after the scroll event
* has fired. Requires a rAF to wait for the scroll event,
* and a setTimeout to wait for the other timeout we have in
* resizeObserver in case the scroll event happens after the
* resize event.
*/
requestAnimationFrame(() => {
setTimeout(() => {
if (state.resizeDifference === difference) {
state.resizeDifference = 0;
}
}, 1);
});
});
state.resizeObserver?.observe(content);
}, []);
return {
contentRef,
scrollRef,
scrollToBottom,
isAtBottom: isAtBottom || isNearBottom,
isNearBottom,
escapedFromLock,
};
};
function useRefCallback<T extends (ref: HTMLElement | null) => any>(callback: T, deps: DependencyList) {
const result = useCallback((ref: HTMLElement | null) => {
result.current = ref;
return callback(ref);
}, deps) as any as MutableRefObject<HTMLElement | null> & RefCallback<HTMLElement>;
return result;
}
const animationCache = new Map<string, Readonly<Required<SpringAnimation>>>();
function mergeAnimations(...animations: (Animation | boolean | undefined)[]) {
const result = { ...DEFAULT_SPRING_ANIMATION };
let instant = false;
for (const animation of animations) {
if (animation === 'instant') {
instant = true;
continue;
}
if (typeof animation !== 'object') {
continue;
}
instant = false;
result.damping = animation.damping ?? result.damping;
result.stiffness = animation.stiffness ?? result.stiffness;
result.mass = animation.mass ?? result.mass;
}
const key = JSON.stringify(result);
if (!animationCache.has(key)) {
animationCache.set(key, Object.freeze(result));
}
return instant ? 'instant' : animationCache.get(key)!;
}