forked from openedx/frontend-app-authoring
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroutes.ts
More file actions
291 lines (272 loc) · 10.3 KB
/
routes.ts
File metadata and controls
291 lines (272 loc) · 10.3 KB
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
/**
* Constants and utility hook for the Library Authoring routes.
*/
import {
useCallback,
useMemo,
useState,
useRef,
useEffect,
} from 'react';
import {
generatePath,
matchPath,
useParams,
useLocation,
useNavigate,
useSearchParams,
useNavigation,
type PathMatch,
} from 'react-router-dom';
import { ContainerType, getBlockType } from '../generic/key-utils';
export const BASE_ROUTE = '/library/:libraryId';
export const ROUTES = {
// LibraryAuthoringPage routes:
// * Components tab, with an optionally selected component in the sidebar.
COMPONENTS: '/components/:selectedItemId?',
// * Collections tab, with an optionally selected collectionId in the sidebar.
COLLECTIONS: '/collections/:selectedItemId?',
// * Sections tab, with an optionally selected section in the sidebar.
SECTIONS: '/sections/:selectedItemId?',
// * Subsections tab, with an optionally selected subsection in the sidebar.
SUBSECTIONS: '/subsections/:selectedItemId?',
// * Units tab, with an optionally selected unit in the sidebar.
UNITS: '/units/:selectedItemId?',
// * All Content tab, with an optionally selected collection or unit in the sidebar.
HOME: '/:selectedItemId?',
// LibraryCollectionPage route:
// * with a selected collectionId and/or an optionally selected componentId.
COLLECTION: '/collection/:collectionId/:selectedItemId?',
// LibrarySectionPage route:
// * with a selected containerId and an optionally selected subsection.
SECTION: '/section/:containerId/:selectedItemId?',
// LibrarySubsectionPage route:
// * with a selected containerId and an optionally selected unit.
SUBSECTION: '/subsection/:containerId/:selectedItemId?',
// LibraryUnitPage route:
// * with a selected containerId and/or an optionally selected componentId.
UNIT: '/unit/:containerId/:selectedItemId?',
};
export enum ContentType {
home = '',
collections = 'collections',
components = 'components',
units = 'units',
subsections = 'subsections',
sections = 'sections',
}
export const allLibraryPageTabs: ContentType[] = Object.values(ContentType);
export type NavigateToData = {
selectedItemId?: string,
collectionId?: string,
containerId?: string,
contentType?: ContentType,
};
export type LibraryRoutesData = {
insideCollection: PathMatch<string> | null;
insideCollections: PathMatch<string> | null;
insideComponents: PathMatch<string> | null;
insideSections: PathMatch<string> | null;
insideSection: PathMatch<string> | null;
insideSubsections: PathMatch<string> | null;
insideSubsection: PathMatch<string> | null;
insideUnits: PathMatch<string> | null;
insideUnit: PathMatch<string> | null;
/** Navigate using the best route from the current location for the given parameters.
* This function can be mutated if there are changes in the current route, so always include
* it in the dependencies array if used on a `useCallback`.
*/
navigateTo: (dict?: NavigateToData, callback?: () => void) => void;
};
export const useLibraryRoutes = (): LibraryRoutesData => {
const { pathname } = useLocation();
const params = useParams();
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const navigation = useNavigation();
const [hasNavigated, setHasNavigated] = useState(false);
const navigationCallbackRef = useRef<() => void>();
const insideCollection = matchPath(BASE_ROUTE + ROUTES.COLLECTION, pathname);
const insideCollections = matchPath(BASE_ROUTE + ROUTES.COLLECTIONS, pathname);
const insideComponents = matchPath(BASE_ROUTE + ROUTES.COMPONENTS, pathname);
const insideSections = matchPath(BASE_ROUTE + ROUTES.SECTIONS, pathname);
const insideSection = matchPath(BASE_ROUTE + ROUTES.SECTION, pathname);
const insideSubsections = matchPath(BASE_ROUTE + ROUTES.SUBSECTIONS, pathname);
const insideSubsection = matchPath(BASE_ROUTE + ROUTES.SUBSECTION, pathname);
const insideUnits = matchPath(BASE_ROUTE + ROUTES.UNITS, pathname);
const insideUnit = matchPath(BASE_ROUTE + ROUTES.UNIT, pathname);
// Sanity check to ensure that we are not inside more than one route at the same time.
// istanbul ignore if: this is a developer error, not a user error.
if (
[
insideCollection,
insideCollections,
insideComponents,
insideSections,
insideSection,
insideSubsections,
insideSubsection,
insideUnits,
insideUnit,
].filter((match): match is PathMatch<string> => match !== null).length > 1) {
throw new Error('Cannot be inside more than one route at the same time.');
}
/** This function is used to navigate to a specific route based on the provided parameters.
*/
const navigateTo = useCallback(({
selectedItemId,
collectionId,
containerId,
contentType,
}: NavigateToData = {}, callback?: () => void) => {
const routeParams = {
...params,
// Overwrite the params with the provided values.
...((selectedItemId !== undefined) && { selectedItemId }),
...((containerId !== undefined) && { containerId }),
...((collectionId !== undefined) && { collectionId }),
};
let route: string;
if (routeParams.selectedItemId
&& (['components', 'units', 'sections', 'subsections'].includes(routeParams.selectedItemId || ''))) {
// These are not valid selectedItemIds, but routes
routeParams.selectedItemId = undefined;
}
// Update containerId/collectionId in library context if is not undefined.
// Ids can be cleared from route by passing in empty string so we need to set it.
if (containerId !== undefined) {
routeParams.selectedItemId = undefined;
// If we can have a containerId alongside a routeParams.collectionId,
// it means we are inside a collection trying to navigate to a unit/section/subsection,
// so we want to clear the collectionId to not have ambiguity.
if (routeParams.collectionId !== undefined) {
routeParams.collectionId = undefined;
}
} else if (collectionId !== undefined) {
routeParams.selectedItemId = undefined;
} else if (contentType) {
// We are navigating to the library home, so we need to clear the containerId and collectionId
routeParams.containerId = undefined;
routeParams.collectionId = undefined;
}
// The code below determines the best route to navigate to based on the
// current pathname and the provided parameters.
// Providing contentType overrides the current route so we can change tabs.
if (contentType === ContentType.components) {
if (!routeParams.selectedItemId?.startsWith('lb:')) {
// If the selectedItemId is not a component, we need to set it to undefined
routeParams.selectedItemId = undefined;
}
route = ROUTES.COMPONENTS;
} else if (contentType === ContentType.collections) {
// FIXME: We are using the Collection key, not the full OpaqueKey. So we
// can't directly use the selectedItemId to determine if it's a collection.
// We need to change this to use the full OpaqueKey in the future.
if (routeParams.selectedItemId?.startsWith('lct:')
|| routeParams.selectedItemId?.startsWith('lb:')) {
routeParams.selectedItemId = undefined;
}
route = ROUTES.COLLECTIONS;
} else if (contentType === ContentType.units) {
if (!routeParams.selectedItemId?.includes(':unit:')) {
// Clear selectedItemId if it is not a unit.
routeParams.selectedItemId = undefined;
}
route = ROUTES.UNITS;
} else if (contentType === ContentType.subsections) {
if (!routeParams.selectedItemId?.includes(':subsection:')) {
// If the selectedItemId is not a subsection, we need to set it to undefined
routeParams.selectedItemId = undefined;
}
route = ROUTES.SUBSECTIONS;
} else if (contentType === ContentType.sections) {
if (!routeParams.selectedItemId?.includes(':section:')) {
// If the selectedItemId is not a section, we need to set it to undefined
routeParams.selectedItemId = undefined;
}
route = ROUTES.SECTIONS;
} else if (contentType === ContentType.home) {
route = ROUTES.HOME;
} else if (routeParams.containerId) {
const containerType = getBlockType(routeParams.containerId);
switch (containerType) {
case ContainerType.Unit:
route = ROUTES.UNIT;
break;
case ContainerType.Subsection:
route = ROUTES.SUBSECTION;
break;
case ContainerType.Section:
route = ROUTES.SECTION;
break;
default:
// Fall back to home if unrecognized container type
route = ROUTES.HOME;
routeParams.containerId = undefined;
break;
}
} else if (routeParams.collectionId) {
route = ROUTES.COLLECTION;
// From here, we will just stay in the current route
} else if (insideComponents) {
route = ROUTES.COMPONENTS;
} else if (insideCollections) {
route = ROUTES.COLLECTIONS;
} else if (insideUnits) {
route = ROUTES.UNITS;
} else if (insideSubsections) {
route = ROUTES.SUBSECTIONS;
} else if (insideSections) {
route = ROUTES.SECTIONS;
} else {
route = ROUTES.HOME;
}
// Also remove the `sa` (sidebar action) search param if it exists.
searchParams.delete('sa');
const newPath = generatePath(BASE_ROUTE + route, routeParams);
// Prevent unnecessary navigation if the path is the same.
if (newPath !== pathname) {
navigate({
pathname: newPath,
search: searchParams.toString(),
});
navigationCallbackRef.current = callback;
setHasNavigated(true);
}
}, [
navigate,
params,
searchParams,
pathname,
]);
useEffect(() => {
if (hasNavigated && navigation.state === 'idle') {
navigationCallbackRef.current?.();
navigationCallbackRef.current = undefined;
setHasNavigated(false);
}
}, [navigation.state, hasNavigated]);
return useMemo(() => ({
navigateTo,
insideCollection,
insideCollections,
insideComponents,
insideSections,
insideSection,
insideSubsections,
insideSubsection,
insideUnits,
insideUnit,
}), [
navigateTo,
insideCollection,
insideCollections,
insideComponents,
insideSections,
insideSection,
insideSubsections,
insideSubsection,
insideUnits,
insideUnit,
]);
};