-
Notifications
You must be signed in to change notification settings - Fork 24
/
AppProgressBar.tsx
369 lines (312 loc) · 10.3 KB
/
AppProgressBar.tsx
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
'use client';
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import NProgress from 'nprogress';
import { isSameURL, isSameURLWithoutSearch } from './utils/sameURL';
import {
usePathname,
useSearchParams,
useRouter as useNextRouter,
} from 'next/navigation';
import { ProgressBarProps, RouterNProgressOptions } from '.';
import { getAnchorProperty } from './utils/getAnchorProperty';
import { NavigateOptions } from 'next/dist/shared/lib/app-router-context.shared-runtime';
type PushStateInput = [
data: any,
unused: string,
url?: string | URL | null | undefined,
];
export const AppProgressBar = React.memo(
({
color = '#0A2FFF',
height = '2px',
options,
shallowRouting = false,
disableSameURL = true,
startPosition = 0,
delay = 0,
stopDelay = 0,
style,
nonce,
targetPreprocessor,
disableAnchorClick = false,
}: ProgressBarProps) => {
const styles = (
<style nonce={nonce}>
{style ||
`
#nprogress {
pointer-events: none;
}
#nprogress .bar {
background: ${color};
position: fixed;
z-index: 99999;
top: 0;
left: 0;
width: 100%;
height: ${height};
}
/* Fancy blur effect */
#nprogress .peg {
display: block;
position: absolute;
right: 0px;
width: 100px;
height: 100%;
box-shadow: 0 0 10px ${color}, 0 0 5px ${color};
opacity: 1.0;
-webkit-transform: rotate(3deg) translate(0px, -4px);
-ms-transform: rotate(3deg) translate(0px, -4px);
transform: rotate(3deg) translate(0px, -4px);
}
/* Remove these to get rid of the spinner */
#nprogress .spinner {
display: block;
position: fixed;
z-index: 1031;
top: 15px;
right: 15px;
}
#nprogress .spinner-icon {
width: 18px;
height: 18px;
box-sizing: border-box;
border: solid 2px transparent;
border-top-color: ${color};
border-left-color: ${color};
border-radius: 50%;
-webkit-animation: nprogress-spinner 400ms linear infinite;
animation: nprogress-spinner 400ms linear infinite;
}
.nprogress-custom-parent {
overflow: hidden;
position: relative;
}
.nprogress-custom-parent #nprogress .spinner,
.nprogress-custom-parent #nprogress .bar {
position: absolute;
}
@-webkit-keyframes nprogress-spinner {
0% { -webkit-transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); }
}
@keyframes nprogress-spinner {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`}
</style>
);
NProgress.configure(options || {});
let progressDoneTimer: NodeJS.Timeout;
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
if (progressDoneTimer) clearTimeout(progressDoneTimer);
progressDoneTimer = setTimeout(() => {
NProgress.done();
}, stopDelay);
}, [pathname, searchParams]);
const elementsWithAttachedHandlers = useRef<
(HTMLAnchorElement | SVGAElement)[]
>([]);
useEffect(() => {
if (disableAnchorClick) {
return;
}
let timer: NodeJS.Timeout;
const startProgress = () => {
timer = setTimeout(() => {
if (startPosition > 0) NProgress.set(startPosition);
NProgress.start();
}, delay);
};
const stopProgress = () => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
NProgress.done();
}, stopDelay);
};
const handleAnchorClick = (event: MouseEvent) => {
// Skip preventDefault
if (event.defaultPrevented) return;
const anchorElement = event.currentTarget as
| HTMLAnchorElement
| SVGAElement;
const target = event.target as HTMLElement | Element;
let preventProgress =
target?.getAttribute('data-prevent-nprogress') === 'true' ||
anchorElement?.getAttribute('data-prevent-nprogress') === 'true';
if (!preventProgress) {
let element: HTMLElement | Element | null = target;
while (element && element.tagName.toLowerCase() !== 'a') {
if (
element.parentElement?.getAttribute('data-prevent-nprogress') ===
'true'
) {
preventProgress = true;
break;
}
element = element.parentElement;
}
}
if (preventProgress) return;
const anchorTarget = getAnchorProperty(anchorElement, 'target');
// Skip anchors with target="_blank"
if (anchorTarget === '_blank') return;
// Skip control/command/option/alt+click
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
return;
const targetHref = getAnchorProperty(anchorElement, 'href');
const targetUrl = targetPreprocessor
? targetPreprocessor(new URL(targetHref))
: new URL(targetHref);
const currentUrl = new URL(location.href);
if (
shallowRouting &&
isSameURLWithoutSearch(targetUrl, currentUrl) &&
disableSameURL
)
return;
if (isSameURL(targetUrl, currentUrl) && disableSameURL) return;
startProgress();
};
const handleMutation: MutationCallback = () => {
const anchorElements = Array.from(document.querySelectorAll('a')) as (
| HTMLAnchorElement
| SVGAElement
)[];
const validAnchorElements = anchorElements.filter((anchor) => {
const href = getAnchorProperty(anchor, 'href');
const isNProgressDisabled =
anchor.getAttribute('data-disable-nprogress') === 'true';
const isNotTelOrMailto =
href &&
!href.startsWith('tel:') &&
!href.startsWith('mailto:') &&
!href.startsWith('blob:') &&
!href.startsWith('javascript:');
return (
!isNProgressDisabled &&
isNotTelOrMailto &&
getAnchorProperty(anchor, 'target') !== '_blank'
);
});
validAnchorElements.forEach((anchor) => {
anchor.addEventListener('click', handleAnchorClick, true);
});
elementsWithAttachedHandlers.current = validAnchorElements;
};
const mutationObserver = new MutationObserver(handleMutation);
mutationObserver.observe(document, { childList: true, subtree: true });
const originalWindowHistoryPushState = window.history.pushState;
window.history.pushState = new Proxy(window.history.pushState, {
apply: (target, thisArg, argArray: PushStateInput) => {
stopProgress();
return target.apply(thisArg, argArray);
},
});
return () => {
mutationObserver.disconnect();
elementsWithAttachedHandlers.current.forEach((anchor) => {
anchor.removeEventListener('click', handleAnchorClick, true);
});
elementsWithAttachedHandlers.current = [];
window.history.pushState = originalWindowHistoryPushState;
};
}, [
disableAnchorClick,
targetPreprocessor,
shallowRouting,
disableSameURL,
]);
return styles;
},
(prevProps, nextProps) => {
if (nextProps?.memo === false) {
return false;
}
if (!nextProps?.shouldCompareComplexProps) {
return true;
}
return (
prevProps?.color === nextProps?.color &&
prevProps?.height === nextProps?.height &&
prevProps?.shallowRouting === nextProps?.shallowRouting &&
prevProps?.startPosition === nextProps?.startPosition &&
prevProps?.delay === nextProps?.delay &&
prevProps?.disableSameURL === nextProps?.disableSameURL &&
prevProps?.stopDelay === nextProps?.stopDelay &&
prevProps?.nonce === nextProps?.nonce &&
JSON.stringify(prevProps?.options) ===
JSON.stringify(nextProps?.options) &&
prevProps?.style === nextProps?.style &&
prevProps.disableAnchorClick === nextProps.disableAnchorClick
);
},
);
AppProgressBar.displayName = 'AppProgressBar';
export function useRouter() {
const router = useNextRouter();
const startProgress = useCallback(
(startPosition?: number) => {
if (startPosition && startPosition > 0) NProgress.set(startPosition);
NProgress.start();
},
[router],
);
const progress = useCallback(
(
href: string,
options?: NavigateOptions,
NProgressOptions?: RouterNProgressOptions,
) => {
if (NProgressOptions?.showProgressBar === false) {
return router.push(href, options);
}
const currentUrl = new URL(location.href);
const targetUrl = new URL(href, location.href);
if (
isSameURL(targetUrl, currentUrl) &&
NProgressOptions?.disableSameURL !== false
)
return router.push(href, options);
startProgress(NProgressOptions?.startPosition);
},
[router],
);
const push = useCallback(
(
href: string,
options?: NavigateOptions,
NProgressOptions?: RouterNProgressOptions,
) => {
progress(href, options, NProgressOptions);
return router.push(href, options);
},
[router, startProgress],
);
const replace = useCallback(
(
href: string,
options?: NavigateOptions,
NProgressOptions?: RouterNProgressOptions,
) => {
progress(href, options, NProgressOptions);
return router.replace(href, options);
},
[router, startProgress],
);
const back = useCallback(
(NProgressOptions?: RouterNProgressOptions) => {
if (NProgressOptions?.showProgressBar === false) return router.back();
startProgress(NProgressOptions?.startPosition);
return router.back();
},
[router],
);
const enhancedRouter = useMemo(() => {
return { ...router, push, replace, back };
}, [router, push, replace, back]);
return enhancedRouter;
}