|
1
|
"use client" |
|
2
|
|
|
3
|
/* Copied from Docusaurus to maintain scroll position on re-renders. Useful when content of the page is updated dynamically */ |
|
4
|
|
|
5
|
/** |
|
6
|
* Copyright (c) Facebook, Inc. and its affiliates. |
|
7
|
* |
|
8
|
* This source code is licensed under the MIT license found in the |
|
9
|
* LICENSE file in the root directory of this source tree. |
|
10
|
*/ |
|
11
|
|
|
12
|
import React, { |
|
13
|
useCallback, |
|
14
|
useContext, |
|
15
|
useEffect, |
|
16
|
useLayoutEffect, |
|
17
|
useMemo, |
|
18
|
useRef, |
|
19
|
type ReactNode, |
|
20
|
useState, |
|
21
|
} from "react" |
|
22
|
import { getScrolledTop as getScrolledTopUtil, isElmWindow } from "../../utils" |
|
23
|
import { useKeyboardShortcut } from "../use-keyboard-shortcut" |
|
24
|
import { useLayout } from "../../providers/Layout" |
|
25
|
|
|
26
|
type EventFunc = (...args: never[]) => unknown |
|
27
|
|
|
28
|
export function useEvent<T extends EventFunc>(callback: T): T { |
|
29
|
const ref = useRef<T>(callback) |
|
30
|
|
|
31
|
useLayoutEffect(() => { |
|
32
|
ref.current = callback |
|
33
|
}, [callback]) |
|
34
|
|
|
35
|
// @ts-expect-error: TS is right that this callback may be a supertype of T, |
|
36
|
// but good enough for our use |
|
37
|
return useCallback<T>((...args) => ref.current(...args), []) |
|
38
|
} |
|
39
|
|
|
40
|
/** |
|
41
|
* Gets `value` from the last render. |
|
42
|
*/ |
|
43
|
export function usePrevious<T>(value: T): T | undefined { |
|
44
|
const ref = useRef<T>(undefined) |
|
45
|
|
|
46
|
useLayoutEffect(() => { |
|
47
|
ref.current = value |
|
48
|
}) |
|
49
|
|
|
50
|
return ref.current |
|
51
|
} |
|
52
|
|
|
53
|
type ScrollController = { |
|
54
|
/** A boolean ref tracking whether scroll events are enabled. */ |
|
55
|
scrollEventsEnabledRef: React.MutableRefObject<boolean> |
|
56
|
/** Enable scroll events in `useScrollPosition`. */ |
|
57
|
enableScrollEvents: () => void |
|
58
|
/** Disable scroll events in `useScrollPosition`. */ |
|
59
|
disableScrollEvents: () => void |
|
60
|
/** Retrieves the scrollable element. By default, it's window. */ |
|
61
|
scrollableElement: Element | Window | undefined |
|
62
|
/** Retrieves the scroll top if the scrollable element */ |
|
63
|
getScrolledTop: () => number |
|
64
|
/** Scrolls to an element */ |
|
65
|
scrollToElement: (elm: HTMLElement) => void |
|
66
|
/** Scrolls to a top value */ |
|
67
|
scrollToTop: (top: number, parentTop?: number) => void |
|
68
|
} |
|
69
|
|
|
70
|
function useScrollControllerContextValue({ |
|
71
|
scrollableSelector, |
|
72
|
}: { |
|
73
|
scrollableSelector: string |
|
74
|
restoreScrollOnReload?: boolean |
|
75
|
}): ScrollController { |
|
76
|
const scrollEventsEnabledRef = useRef(true) |
|
77
|
const { showCollapsedNavbar } = useLayout() |
|
78
|
|
|
79
|
const [scrollableElement, setScrollableElement] = useState< |
|
80
|
Element | Window | undefined |
|
81
|
>() |
|
82
|
|
|
83
|
useEffect(() => { |
|
84
|
setScrollableElement( |
|
85
|
(document.querySelector(scrollableSelector) as Element) || window |
|
86
|
) |
|
87
|
}, []) |
|
88
|
|
|
89
|
const getScrolledTop = () => { |
|
90
|
return scrollableElement ? getScrolledTopUtil(scrollableElement) : 0 |
|
91
|
} |
|
92
|
|
|
93
|
const scrollToElement = (elm: HTMLElement) => { |
|
94
|
scrollToTop(elm.offsetTop) |
|
95
|
} |
|
96
|
|
|
97
|
const topMargin = useMemo(() => { |
|
98
|
// might need a better way to set these static values |
|
99
|
return showCollapsedNavbar ? 112 : 56 |
|
100
|
}, [showCollapsedNavbar]) |
|
101
|
|
|
102
|
const scrollToTop = (top: number, parentTop?: number) => { |
|
103
|
const parentOffsetTop = |
|
104
|
parentTop !== undefined |
|
105
|
? parentTop |
|
106
|
: isElmWindow(scrollableElement) |
|
107
|
? 0 |
|
108
|
: scrollableElement instanceof HTMLElement |
|
109
|
? scrollableElement.offsetTop |
|
110
|
: 0 |
|
111
|
|
|
112
|
scrollableElement?.scrollTo({ |
|
113
|
top: top - parentOffsetTop - topMargin, |
|
114
|
behavior: "instant", |
|
115
|
}) |
|
116
|
} |
|
117
|
|
|
118
|
return useMemo( |
|
119
|
() => ({ |
|
120
|
scrollEventsEnabledRef, |
|
121
|
enableScrollEvents: () => { |
|
122
|
scrollEventsEnabledRef.current = true |
|
123
|
}, |
|
124
|
disableScrollEvents: () => { |
|
125
|
scrollEventsEnabledRef.current = false |
|
126
|
}, |
|
127
|
scrollableElement, |
|
128
|
getScrolledTop, |
|
129
|
scrollToElement, |
|
130
|
scrollToTop, |
|
131
|
}), |
|
132
|
[scrollableElement] |
|
133
|
) |
|
134
|
} |
|
135
|
|
|
136
|
const ScrollMonitorContext = React.createContext<ScrollController | undefined>( |
|
137
|
undefined |
|
138
|
) |
|
139
|
|
|
140
|
export function ScrollControllerProvider({ |
|
141
|
children, |
|
142
|
scrollableSelector = "", |
|
143
|
}: { |
|
144
|
children: ReactNode |
|
145
|
scrollableSelector?: string |
|
146
|
restoreScrollOnReload?: boolean |
|
147
|
}) { |
|
148
|
const value = useScrollControllerContextValue({ |
|
149
|
scrollableSelector, |
|
150
|
}) |
|
151
|
useKeyboardShortcut({ |
|
152
|
metakey: false, |
|
153
|
shortcutKeys: ["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End"], |
|
154
|
action: (e) => { |
|
155
|
// check that document or body are focused |
|
156
|
const activeElement = document.activeElement |
|
157
|
if ( |
|
158
|
isElmWindow(value.scrollableElement) || |
|
159
|
!value.scrollableElement || |
|
160
|
(activeElement !== document.body && |
|
161
|
activeElement !== document.documentElement) |
|
162
|
) { |
|
163
|
return |
|
164
|
} |
|
165
|
|
|
166
|
let newScroll = value.scrollableElement.scrollTop |
|
167
|
const scrollThreshold = 50 |
|
168
|
const pageScrollAmount = |
|
169
|
value.scrollableElement.clientHeight - scrollThreshold |
|
170
|
|
|
171
|
switch (e.key) { |
|
172
|
case "ArrowUp": |
|
173
|
newScroll = -scrollThreshold |
|
174
|
break |
|
175
|
case "ArrowDown": |
|
176
|
newScroll = scrollThreshold |
|
177
|
break |
|
178
|
case "PageUp": |
|
179
|
newScroll = -pageScrollAmount |
|
180
|
break |
|
181
|
case "PageDown": |
|
182
|
newScroll = pageScrollAmount |
|
183
|
break |
|
184
|
case "Home": |
|
185
|
newScroll = -newScroll |
|
186
|
break |
|
187
|
case "End": |
|
188
|
newScroll = value.scrollableElement.scrollHeight |
|
189
|
} |
|
190
|
|
|
191
|
value.scrollableElement?.scrollBy({ |
|
192
|
top: newScroll, |
|
193
|
behavior: "smooth", |
|
194
|
}) |
|
195
|
}, |
|
196
|
}) |
|
197
|
return ( |
|
198
|
<ScrollMonitorContext.Provider value={value}> |
|
199
|
{children} |
|
200
|
</ScrollMonitorContext.Provider> |
|
201
|
) |
|
202
|
} |
|
203
|
|
|
204
|
/** |
|
205
|
* We need a way to update the scroll position while ignoring scroll events |
|
206
|
* so as not to toggle Navbar/BackToTop visibility. |
|
207
|
* |
|
208
|
* This API permits to temporarily disable/ignore scroll events. Motivated by |
|
209
|
* https://github.com/facebook/docusaurus/pull/5618 |
|
210
|
*/ |
|
211
|
export function useScrollController(): ScrollController { |
|
212
|
const context = useContext(ScrollMonitorContext) |
|
213
|
if (context == null) { |
|
214
|
throw new Error( |
|
215
|
`useScrollController must be used by elements in ScrollControllerProvider` |
|
216
|
) |
|
217
|
} |
|
218
|
return context |
|
219
|
} |
|
220
|
|
|
221
|
type ScrollPosition = { scrollX: number; scrollY: number } |
|
222
|
|
|
223
|
const getScrollPosition = (): ScrollPosition | null => ({ |
|
224
|
scrollX: window.pageXOffset, |
|
225
|
scrollY: window.pageYOffset, |
|
226
|
}) |
|
227
|
|
|
228
|
/** |
|
229
|
* This hook fires an effect when the scroll position changes. The effect will |
|
230
|
* be provided with the before/after scroll positions. Note that the effect may |
|
231
|
* not be always run: if scrolling is disabled through `useScrollController`, it |
|
232
|
* will be a no-op. |
|
233
|
* |
|
234
|
* @see {@link useScrollController} |
|
235
|
*/ |
|
236
|
export function useScrollPosition( |
|
237
|
effect: ( |
|
238
|
position: ScrollPosition, |
|
239
|
lastPosition: ScrollPosition | null |
|
240
|
) => void, |
|
241
|
deps: unknown[] = [] |
|
242
|
): void { |
|
243
|
const { scrollEventsEnabledRef } = useScrollController() |
|
244
|
const lastPositionRef = useRef<ScrollPosition | null>(getScrollPosition()) |
|
245
|
|
|
246
|
const dynamicEffect = useEvent(effect) |
|
247
|
|
|
248
|
useEffect(() => { |
|
249
|
const handleScroll = () => { |
|
250
|
if (!scrollEventsEnabledRef.current) { |
|
251
|
return |
|
252
|
} |
|
253
|
const currentPosition = getScrollPosition()! |
|
254
|
dynamicEffect(currentPosition, lastPositionRef.current) |
|
255
|
lastPositionRef.current = currentPosition |
|
256
|
} |
|
257
|
|
|
258
|
const opts: AddEventListenerOptions & EventListenerOptions = { |
|
259
|
passive: true, |
|
260
|
} |
|
261
|
|
|
262
|
handleScroll() |
|
263
|
window.addEventListener("scroll", handleScroll, opts) |
|
264
|
|
|
265
|
return () => window.removeEventListener("scroll", handleScroll, opts) |
|
266
|
}, [dynamicEffect, scrollEventsEnabledRef, ...deps]) |
|
267
|
} |
|
268
|
|
|
269
|
type UseScrollPositionSaver = { |
|
270
|
/** Measure the top of an element, and store the details. */ |
|
271
|
save: (elem: HTMLElement) => void |
|
272
|
/** |
|
273
|
* Restore the page position to keep the stored element's position from |
|
274
|
* the top of the viewport, and remove the stored details. |
|
275
|
*/ |
|
276
|
restore: () => { restored: boolean } |
|
277
|
} |
|
278
|
|
|
279
|
function useScrollPositionSaver(): UseScrollPositionSaver { |
|
280
|
const { scrollableElement } = useScrollController() |
|
281
|
const lastElementRef = useRef<{ elem: HTMLElement | null; top: number }>({ |
|
282
|
elem: null, |
|
283
|
top: 0, |
|
284
|
}) |
|
285
|
|
|
286
|
const save = useCallback((elem: HTMLElement) => { |
|
287
|
lastElementRef.current = { |
|
288
|
elem, |
|
289
|
top: elem.getBoundingClientRect().top, |
|
290
|
} |
|
291
|
}, []) |
|
292
|
|
|
293
|
const restore = useCallback(() => { |
|
294
|
const { |
|
295
|
current: { elem, top }, |
|
296
|
} = lastElementRef |
|
297
|
if (!elem) { |
|
298
|
return { restored: false } |
|
299
|
} |
|
300
|
const newTop = elem.getBoundingClientRect().top |
|
301
|
const heightDiff = newTop - top |
|
302
|
if (heightDiff) { |
|
303
|
scrollableElement?.scrollBy({ left: 0, top: heightDiff }) |
|
304
|
} |
|
305
|
lastElementRef.current = { elem: null, top: 0 } |
|
306
|
|
|
307
|
return { restored: heightDiff !== 0 } |
|
308
|
}, []) |
|
309
|
|
|
310
|
return useMemo(() => ({ save, restore }), [restore, save]) |
|
311
|
} |
|
312
|
|
|
313
|
/** |
|
314
|
* This hook permits to "block" the scroll position of a DOM element. |
|
315
|
* The idea is that we should be able to update DOM content above this element |
|
316
|
* but the screen position of this element should not change. |
|
317
|
* |
|
318
|
* Feature motivated by the Tabs groups: clicking on a tab may affect tabs of |
|
319
|
* the same group upper in the tree, yet to avoid a bad UX, the clicked tab must |
|
320
|
* remain under the user mouse. |
|
321
|
* |
|
322
|
* @see https://github.com/facebook/docusaurus/pull/5618 |
|
323
|
*/ |
|
324
|
export function useScrollPositionBlocker(): { |
|
325
|
/** |
|
326
|
* Takes an element, and keeps its screen position no matter what's getting |
|
327
|
* rendered above it, until the next render. |
|
328
|
*/ |
|
329
|
blockElementScrollPositionUntilNextRender: (el: HTMLElement) => void |
|
330
|
} { |
|
331
|
const scrollController = useScrollController() |
|
332
|
const scrollPositionSaver = useScrollPositionSaver() |
|
333
|
|
|
334
|
const nextLayoutEffectCallbackRef = useRef<(() => void) | undefined>( |
|
335
|
undefined |
|
336
|
) |
|
337
|
|
|
338
|
const blockElementScrollPositionUntilNextRender = useCallback( |
|
339
|
(el: HTMLElement) => { |
|
340
|
scrollPositionSaver.save(el) |
|
341
|
scrollController.disableScrollEvents() |
|
342
|
nextLayoutEffectCallbackRef.current = () => { |
|
343
|
const { restored } = scrollPositionSaver.restore() |
|
344
|
nextLayoutEffectCallbackRef.current = undefined |
|
345
|
|
|
346
|
// Restoring the former scroll position will trigger a scroll event. We |
|
347
|
// need to wait for next scroll event to happen before enabling the |
|
348
|
// scrollController events again. |
|
349
|
if (restored) { |
|
350
|
const handleScrollRestoreEvent = () => { |
|
351
|
scrollController.enableScrollEvents() |
|
352
|
window.removeEventListener("scroll", handleScrollRestoreEvent) |
|
353
|
} |
|
354
|
window.addEventListener("scroll", handleScrollRestoreEvent) |
|
355
|
} else { |
|
356
|
scrollController.enableScrollEvents() |
|
357
|
} |
|
358
|
} |
|
359
|
}, |
|
360
|
[scrollController, scrollPositionSaver] |
|
361
|
) |
|
362
|
|
|
363
|
useLayoutEffect(() => { |
|
364
|
// Queuing permits to restore scroll position after all useLayoutEffect |
|
365
|
// have run, and yet preserve the sync nature of the scroll restoration |
|
366
|
// See https://github.com/facebook/docusaurus/issues/8625 |
|
367
|
queueMicrotask(() => nextLayoutEffectCallbackRef.current?.()) |
|
368
|
}) |
|
369
|
|
|
370
|
return { |
|
371
|
blockElementScrollPositionUntilNextRender, |
|
372
|
} |
|
373
|
} |