-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathindex.tsx
535 lines (474 loc) · 14.5 KB
/
index.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
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
/**
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* This script exports a hook that accepts a routes array of objects
* and an options object.
*
* API:
*
* useBreadcrumbs(
* routes?: Array<Route>,
* options? Object<Options>,
* ): Array<BreadcrumbData>
*
* More Info:
*
* https://github.com/icd2k3/use-react-router-breadcrumbs
*
*/
import React, { createElement } from 'react';
import {
matchPath,
useLocation,
RouteObject,
Params,
Route,
PathRouteProps,
LayoutRouteProps,
IndexRouteProps,
} from 'react-router-dom';
type Location = ReturnType<typeof useLocation>;
/**
* This type interface is copied in directly from react-router (react-router-dom does not export it)
*/
interface PathPattern<Path extends string = string> {
path: Path;
caseSensitive?: boolean;
end?: boolean;
}
export interface Options {
disableDefaults?: boolean;
excludePaths?: string[];
defaultFormatter?: (str: string) => string
}
export interface BreadcrumbMatch<ParamKey extends string = string> {
/**
* The names and values of dynamic parameters in the URL.
*/
params: Params<ParamKey>;
/**
* The portion of the URL pathname that was matched.
*/
pathname: string;
/**
* The pattern that was used to match.
*/
pattern: PathPattern;
/**
* The route object that was used to match.
*/
route?: BreadcrumbsRoute;
}
export interface BreadcrumbComponentProps<ParamKey extends string = string> {
key: string;
match: BreadcrumbMatch<ParamKey>;
location: Location;
[x: string]: unknown;
}
export type BreadcrumbComponentType<ParamKey extends string = string> =
React.ComponentType<BreadcrumbComponentProps<ParamKey>>;
export type BreadcrumbsRoute<ParamKey extends string = string> = RouteObject & {
children?: BreadcrumbsRoute[];
breadcrumb?: BreadcrumbComponentType<ParamKey> | string | null;
props?: { [x: string]: unknown };
};
export interface BreadcrumbData<ParamKey extends string = string> {
match: BreadcrumbMatch<ParamKey>;
location: Location;
key: string;
breadcrumb: React.ReactNode;
}
// The code below is modified from React Router
interface BreadcrumbsRouteMeta {
relativePath: string;
childrenIndex: number;
route: BreadcrumbsRoute;
}
interface BreadcrumbsRouteBranch {
path: string;
score: number;
routesMeta: BreadcrumbsRouteMeta[];
}
const joinPaths = (paths: string[]): string => paths.join('/').replace(/\/\/+/g, '/');
const paramRe = /^:\w+$/;
const dynamicSegmentValue = 3;
const indexRouteValue = 2;
const emptySegmentValue = 1;
const staticSegmentValue = 10;
const splatPenalty = -2;
const isSplat = (s: string) => s === '*';
function computeScore(path: string, index: boolean | undefined): number {
const segments = path.split('/');
let initialScore = segments.length;
if (segments.some(isSplat)) {
initialScore += splatPenalty;
}
if (index) {
initialScore += indexRouteValue;
}
return segments
.filter((s) => !isSplat(s))
.reduce((score, segment) => {
if (paramRe.test(segment)) {
return score + dynamicSegmentValue;
}
if (segment === '') {
return score + emptySegmentValue;
}
return score + staticSegmentValue;
}, initialScore);
}
function compareIndexes(a: number[], b: number[]): number {
const siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
return siblings ? a[a.length - 1] - b[b.length - 1] : 0;
}
function flattenRoutes(
routes: BreadcrumbsRoute[],
branches: BreadcrumbsRouteBranch[] = [],
parentsMeta: BreadcrumbsRouteMeta[] = [],
parentPath = '',
): BreadcrumbsRouteBranch[] {
routes.forEach((route, index) => {
if (typeof route.path !== 'string' && !route.index && !route.children?.length) {
throw new Error(
'useBreadcrumbs: `path` or `index` must be provided in every route object',
);
}
if (route.path && route.index) {
throw new Error(
'useBreadcrumbs: `path` and `index` cannot be provided at the same time',
);
}
const meta: BreadcrumbsRouteMeta = {
relativePath: route.path || '',
childrenIndex: index,
route,
};
if (meta.relativePath.charAt(0) === '/') {
if (!meta.relativePath.startsWith(parentPath)) {
throw new Error(
'useBreadcrumbs: The absolute path of the child route must start with the parent path',
);
}
meta.relativePath = meta.relativePath.slice(parentPath.length);
}
const path = joinPaths([parentPath, meta.relativePath]);
const routesMeta = parentsMeta.concat(meta);
if (route.children && route.children.length > 0) {
if (route.index) {
throw new Error('useBreadcrumbs: Index route cannot have child routes');
}
flattenRoutes(route.children, branches, routesMeta, path);
}
branches.push({
path,
score: computeScore(path, route.index),
routesMeta,
});
});
return branches;
}
function rankRouteBranches(
branches: BreadcrumbsRouteBranch[],
): BreadcrumbsRouteBranch[] {
return branches.sort((a, b) => (a.score !== b.score
? b.score - a.score // Higher score first
: compareIndexes(
a.routesMeta.map((meta) => meta.childrenIndex),
b.routesMeta.map((meta) => meta.childrenIndex),
)));
}
// Begin: useBreadcrumbs
const NO_BREADCRUMB = Symbol('NO_BREADCRUMB');
/**
* This method was "borrowed" from https://stackoverflow.com/a/28339742
* we used to use the humanize-string package, but it added a lot of bundle
* size and issues with compilation. This 4-liner seems to cover most cases.
*/
export const humanize = (str: string): string => str
.replace(/^[\s_]+|[\s_]+$/g, '')
.replace(/[-_\s]+/g, ' ')
.replace(/^[a-z]/, (m) => m.toUpperCase());
/**
* Renders and returns the breadcrumb complete
* with `match`, `location`, and `key` props.
*/
const render = ({
breadcrumb: Breadcrumb,
match,
location,
props,
}: {
breadcrumb: BreadcrumbComponentType | string;
match: BreadcrumbMatch;
location: Location;
props?: { [x: string]: unknown };
}): BreadcrumbData => {
const componentProps = {
match,
location,
key: match.pathname,
...(props || {}),
};
return {
...componentProps,
breadcrumb:
typeof Breadcrumb === 'string' ? (
createElement('span', { key: componentProps.key }, Breadcrumb)
) : (
<Breadcrumb {...componentProps} />
),
};
};
/**
* Small helper method to get a default breadcrumb if the user hasn't provided one.
*/
const getDefaultBreadcrumb = ({
currentSection,
location,
pathSection,
defaultFormatter,
}: {
currentSection: string;
location: Location;
pathSection: string;
defaultFormatter?: (str: string) => string
}): BreadcrumbData => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const match = matchPath(
{
end: true,
path: pathSection,
},
pathSection,
)!;
return render({
breadcrumb: defaultFormatter ? defaultFormatter(currentSection) : humanize(currentSection),
match,
location,
});
};
/**
* Loops through the route array (if provided) and returns either a
* user-provided breadcrumb OR a sensible default (if enabled)
*/
const getBreadcrumbMatch = ({
currentSection,
disableDefaults,
excludePaths,
defaultFormatter,
location,
pathSection,
branches,
}: {
currentSection: string;
disableDefaults?: boolean;
excludePaths?: string[];
defaultFormatter?: (str: string) => string
location: Location;
pathSection: string;
branches: BreadcrumbsRouteBranch[];
}): typeof NO_BREADCRUMB | BreadcrumbData => {
let breadcrumb: BreadcrumbData | typeof NO_BREADCRUMB | undefined;
// Check the optional `excludePaths` option in `options` to see if the
// current path should not include a breadcrumb.
const getIsPathExcluded = (path: string): boolean => matchPath(
{
path,
end: true,
},
pathSection,
) != null;
if (excludePaths && excludePaths.some(getIsPathExcluded)) {
return NO_BREADCRUMB;
}
// Loop through the route array and see if the user has provided a custom breadcrumb.
branches.some(({ path, routesMeta }) => {
const { route } = routesMeta[routesMeta.length - 1];
let userProvidedBreadcrumb = route.breadcrumb;
// If the route is an index, but no breadcrumb is set,
// We try to use the breadcrumbs of the parent route instead
if (!userProvidedBreadcrumb && route.index) {
const parentMeta = routesMeta[routesMeta.length - 2];
if (parentMeta && parentMeta.route.breadcrumb) {
userProvidedBreadcrumb = parentMeta.route.breadcrumb;
}
}
const { caseSensitive, props } = route;
const match = matchPath(
{
path,
end: true,
caseSensitive,
},
pathSection,
);
// If user passed breadcrumb: null
// we need to know NOT to add it to the matches array
// see: `if (breadcrumb !== NO_BREADCRUMB)` below.
if (match && userProvidedBreadcrumb === null) {
breadcrumb = NO_BREADCRUMB;
return true;
}
if (match) {
// This covers the case where a user may be extending their react-router route
// config with breadcrumbs, but also does not want default breadcrumbs to be
// automatically generated (opt-in).
if (!userProvidedBreadcrumb && disableDefaults) {
breadcrumb = NO_BREADCRUMB;
return true;
}
breadcrumb = render({
// Although we have a match, the user may be passing their react-router config object
// which we support. The route config object may not have a `breadcrumb` param specified.
// If this is the case, we should provide a default via `humanize`.
breadcrumb: userProvidedBreadcrumb
|| (defaultFormatter ? defaultFormatter(currentSection) : humanize(currentSection)),
match: { ...match, route },
location,
props,
});
return true;
}
return false;
});
// User provided a breadcrumb prop, or we generated one above.
if (breadcrumb) {
return breadcrumb;
}
// If there was no breadcrumb provided and user has disableDefaults turned on.
if (disableDefaults) {
return NO_BREADCRUMB;
}
// If the above conditionals don't fire, generate a default breadcrumb based on the path.
return getDefaultBreadcrumb({
pathSection,
// include a "Home" breadcrumb by default (can be overrode or disabled in config).
currentSection: pathSection === '/' ? 'Home' : currentSection,
location,
defaultFormatter,
});
};
/**
* Splits the pathname into sections, then search for matches in the routes
* a user-provided breadcrumb OR a sensible default.
*/
export const getBreadcrumbs = ({
routes,
location,
options = {},
}: {
routes: BreadcrumbsRoute[];
location: Location;
options?: Options;
}): BreadcrumbData[] => {
const { pathname } = location;
const branches = rankRouteBranches(flattenRoutes(routes));
const breadcrumbs: BreadcrumbData[] = [];
pathname
.split('?')[0]
.split('/')
.reduce(
(previousSection: string, currentSection: string, index: number) => {
// Combine the last route section with the currentSection.
// For example, `pathname = /1/2/3` results in match checks for
// `/1`, `/1/2`, `/1/2/3`.
const pathSection = !currentSection
? '/'
: `${previousSection}/${currentSection}`;
// Ignore trailing slash or double slashes in the URL
if (pathSection === '/' && index !== 0) {
return '';
}
const breadcrumb = getBreadcrumbMatch({
currentSection,
location,
pathSection,
branches,
...options,
});
// Add the breadcrumb to the matches array
// unless the user has explicitly passed.
// { path: x, breadcrumb: null } to disable.
if (breadcrumb !== NO_BREADCRUMB) {
breadcrumbs.push(breadcrumb);
}
return pathSection === '/' ? '' : pathSection;
},
'',
);
return breadcrumbs;
};
/**
* Default hook function export.
*/
const useReactRouterBreadcrumbs = (
routes?: BreadcrumbsRoute[],
options?: Options,
): BreadcrumbData[] => getBreadcrumbs({
routes: routes || [],
location: useLocation(),
options,
});
export default useReactRouterBreadcrumbs;
// https://github.com/remix-run/react-router/blob/main/packages/react-router/index.tsx#L760
// The createRoutesFromChildren function has been modified to accept the breadcrumb route.
// UTILS
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function invariant(cond: any, message: string): asserts cond {
if (!cond) throw new Error(message);
}
/**
* Creates a route config from a React "children" object, which is usually
* either a `<Route>` element or an array of them. Used internally by
* `<Routes>` to create a route config from its children.
*
* @see https://reactrouter.com/docs/en/v6/api#createroutesfromchildren
*/
export function createRoutesFromChildren(
children: React.ReactNode,
): BreadcrumbsRoute[] {
const routes: BreadcrumbsRoute[] = [];
React.Children.forEach(children, (element) => {
if (!React.isValidElement(element)) {
// Ignore non-elements. This allows people to more easily inline
// conditionals in their route config.
return;
}
if (element.type === React.Fragment) {
// Transparently support React.Fragment and its children.
// eslint-disable-next-line prefer-spread
routes.push.apply(
routes,
createRoutesFromChildren(element.props.children),
);
return;
}
invariant(
element.type === Route,
`[${
typeof element.type === 'string' ? element.type : element.type.name
}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`,
);
const route: BreadcrumbsRoute = {
caseSensitive: element.props.caseSensitive,
element: element.props.element,
index: element.props.index,
path: element.props.path,
breadcrumb: element.props.breadcrumb,
};
if (element.props.children) {
route.children = createRoutesFromChildren(element.props.children);
}
routes.push(route);
});
return routes;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type BreadCrumb = { breadcrumb?: string | ((param: any) => JSX.Element) | JSX.Element | null };
type BreadCrumbRouteType = (
_props: (PathRouteProps | LayoutRouteProps | IndexRouteProps) & BreadCrumb
) => React.ReactElement | null;
const BreadCrumbRoute: BreadCrumbRouteType = Route;
export { BreadCrumbRoute as Route };