1 | "use strict";
|
2 |
|
3 | Object.defineProperty(exports, "__esModule", {
|
4 | value: true
|
5 | });
|
6 | exports.default = getStateFromPath;
|
7 |
|
8 | var _escapeStringRegexp = _interopRequireDefault(require("escape-string-regexp"));
|
9 |
|
10 | var queryString = _interopRequireWildcard(require("query-string"));
|
11 |
|
12 | var _findFocusedRoute = _interopRequireDefault(require("./findFocusedRoute"));
|
13 |
|
14 | var _validatePathConfig = _interopRequireDefault(require("./validatePathConfig"));
|
15 |
|
16 | function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
|
17 |
|
18 | function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
|
19 |
|
20 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 | function getStateFromPath(path, options) {
|
44 | if (options) {
|
45 | (0, _validatePathConfig.default)(options);
|
46 | }
|
47 |
|
48 | let initialRoutes = [];
|
49 |
|
50 | if (options !== null && options !== void 0 && options.initialRouteName) {
|
51 | initialRoutes.push({
|
52 | initialRouteName: options.initialRouteName,
|
53 | parentScreens: []
|
54 | });
|
55 | }
|
56 |
|
57 | const screens = options === null || options === void 0 ? void 0 : options.screens;
|
58 | let remaining = path.replace(/\/+/g, '/')
|
59 | .replace(/^\//, '')
|
60 | .replace(/\?.*$/, '');
|
61 |
|
62 |
|
63 | remaining = remaining.endsWith('/') ? remaining : `${remaining}/`;
|
64 |
|
65 | if (screens === undefined) {
|
66 |
|
67 | const routes = remaining.split('/').filter(Boolean).map(segment => {
|
68 | const name = decodeURIComponent(segment);
|
69 | return {
|
70 | name
|
71 | };
|
72 | });
|
73 |
|
74 | if (routes.length) {
|
75 | return createNestedStateObject(path, routes, initialRoutes);
|
76 | }
|
77 |
|
78 | return undefined;
|
79 | }
|
80 |
|
81 |
|
82 | const configs = [].concat(...Object.keys(screens).map(key => createNormalizedConfigs(key, screens, [], initialRoutes, []))).sort((a, b) => {
|
83 |
|
84 |
|
85 |
|
86 |
|
87 |
|
88 | if (a.pattern === b.pattern) {
|
89 | return b.routeNames.join('>').localeCompare(a.routeNames.join('>'));
|
90 | }
|
91 |
|
92 |
|
93 |
|
94 | if (a.pattern.startsWith(b.pattern)) {
|
95 | return -1;
|
96 | }
|
97 |
|
98 | if (b.pattern.startsWith(a.pattern)) {
|
99 | return 1;
|
100 | }
|
101 |
|
102 | const aParts = a.pattern.split('/');
|
103 | const bParts = b.pattern.split('/');
|
104 |
|
105 | for (let i = 0; i < Math.max(aParts.length, bParts.length); i++) {
|
106 |
|
107 | if (aParts[i] == null) {
|
108 | return 1;
|
109 | }
|
110 |
|
111 |
|
112 | if (bParts[i] == null) {
|
113 | return -1;
|
114 | }
|
115 |
|
116 | const aWildCard = aParts[i] === '*' || aParts[i].startsWith(':');
|
117 | const bWildCard = bParts[i] === '*' || bParts[i].startsWith(':');
|
118 |
|
119 | if (aWildCard && bWildCard) {
|
120 | continue;
|
121 | }
|
122 |
|
123 |
|
124 | if (aWildCard) {
|
125 | return 1;
|
126 | }
|
127 |
|
128 |
|
129 | if (bWildCard) {
|
130 | return -1;
|
131 | }
|
132 | }
|
133 |
|
134 | return bParts.length - aParts.length;
|
135 | });
|
136 |
|
137 | configs.reduce((acc, config) => {
|
138 | if (acc[config.pattern]) {
|
139 | const a = acc[config.pattern].routeNames;
|
140 | const b = config.routeNames;
|
141 |
|
142 |
|
143 | const intersects = a.length > b.length ? b.every((it, i) => a[i] === it) : a.every((it, i) => b[i] === it);
|
144 |
|
145 | if (!intersects) {
|
146 | throw new Error(`Found conflicting screens with the same pattern. The pattern '${config.pattern}' resolves to both '${a.join(' > ')}' and '${b.join(' > ')}'. Patterns must be unique and cannot resolve to more than one screen.`);
|
147 | }
|
148 | }
|
149 |
|
150 | return Object.assign(acc, {
|
151 | [config.pattern]: config
|
152 | });
|
153 | }, {});
|
154 |
|
155 | if (remaining === '/') {
|
156 |
|
157 |
|
158 | const match = configs.find(config => config.path === '' && config.routeNames.every(
|
159 | name => {
|
160 | var _configs$find;
|
161 |
|
162 | return !((_configs$find = configs.find(c => c.screen === name)) !== null && _configs$find !== void 0 && _configs$find.path);
|
163 | }));
|
164 |
|
165 | if (match) {
|
166 | return createNestedStateObject(path, match.routeNames.map(name => ({
|
167 | name
|
168 | })), initialRoutes, configs);
|
169 | }
|
170 |
|
171 | return undefined;
|
172 | }
|
173 |
|
174 | let result;
|
175 | let current;
|
176 |
|
177 |
|
178 | const {
|
179 | routes,
|
180 | remainingPath
|
181 | } = matchAgainstConfigs(remaining, configs.map(c => ({ ...c,
|
182 |
|
183 | regex: c.regex ? new RegExp(c.regex.source + '$') : undefined
|
184 | })));
|
185 |
|
186 | if (routes !== undefined) {
|
187 |
|
188 | current = createNestedStateObject(path, routes, initialRoutes, configs);
|
189 | remaining = remainingPath;
|
190 | result = current;
|
191 | }
|
192 |
|
193 | if (current == null || result == null) {
|
194 | return undefined;
|
195 | }
|
196 |
|
197 | return result;
|
198 | }
|
199 |
|
200 | const joinPaths = function () {
|
201 | for (var _len = arguments.length, paths = new Array(_len), _key = 0; _key < _len; _key++) {
|
202 | paths[_key] = arguments[_key];
|
203 | }
|
204 |
|
205 | return [].concat(...paths.map(p => p.split('/'))).filter(Boolean).join('/');
|
206 | };
|
207 |
|
208 | const matchAgainstConfigs = (remaining, configs) => {
|
209 | let routes;
|
210 | let remainingPath = remaining;
|
211 |
|
212 | for (const config of configs) {
|
213 | if (!config.regex) {
|
214 | continue;
|
215 | }
|
216 |
|
217 | const match = remainingPath.match(config.regex);
|
218 |
|
219 | if (match) {
|
220 | var _config$pattern;
|
221 |
|
222 | const matchedParams = (_config$pattern = config.pattern) === null || _config$pattern === void 0 ? void 0 : _config$pattern.split('/').filter(p => p.startsWith(':')).reduce((acc, p, i) => Object.assign(acc, {
|
223 |
|
224 | [p]: match[(i + 1) * 2].replace(/\//, '')
|
225 | }), {});
|
226 | routes = config.routeNames.map(name => {
|
227 | var _config$path;
|
228 |
|
229 | const config = configs.find(c => c.screen === name);
|
230 | const params = config === null || config === void 0 ? void 0 : (_config$path = config.path) === null || _config$path === void 0 ? void 0 : _config$path.split('/').filter(p => p.startsWith(':')).reduce((acc, p) => {
|
231 | const value = matchedParams[p];
|
232 |
|
233 | if (value) {
|
234 | var _config$parse;
|
235 |
|
236 | const key = p.replace(/^:/, '').replace(/\?$/, '');
|
237 | acc[key] = (_config$parse = config.parse) !== null && _config$parse !== void 0 && _config$parse[key] ? config.parse[key](value) : value;
|
238 | }
|
239 |
|
240 | return acc;
|
241 | }, {});
|
242 |
|
243 | if (params && Object.keys(params).length) {
|
244 | return {
|
245 | name,
|
246 | params
|
247 | };
|
248 | }
|
249 |
|
250 | return {
|
251 | name
|
252 | };
|
253 | });
|
254 | remainingPath = remainingPath.replace(match[1], '');
|
255 | break;
|
256 | }
|
257 | }
|
258 |
|
259 | return {
|
260 | routes,
|
261 | remainingPath
|
262 | };
|
263 | };
|
264 |
|
265 | const createNormalizedConfigs = function (screen, routeConfig) {
|
266 | let routeNames = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
|
267 | let initials = arguments.length > 3 ? arguments[3] : undefined;
|
268 | let parentScreens = arguments.length > 4 ? arguments[4] : undefined;
|
269 | let parentPattern = arguments.length > 5 ? arguments[5] : undefined;
|
270 | const configs = [];
|
271 | routeNames.push(screen);
|
272 | parentScreens.push(screen);
|
273 |
|
274 | const config = routeConfig[screen];
|
275 |
|
276 | if (typeof config === 'string') {
|
277 |
|
278 | const pattern = parentPattern ? joinPaths(parentPattern, config) : config;
|
279 | configs.push(createConfigItem(screen, routeNames, pattern, config));
|
280 | } else if (typeof config === 'object') {
|
281 | let pattern;
|
282 |
|
283 |
|
284 |
|
285 | if (typeof config.path === 'string') {
|
286 | if (config.exact && config.path === undefined) {
|
287 | throw new Error("A 'path' needs to be specified when specifying 'exact: true'. If you don't want this screen in the URL, specify it as empty string, e.g. `path: ''`.");
|
288 | }
|
289 |
|
290 | pattern = config.exact !== true ? joinPaths(parentPattern || '', config.path || '') : config.path || '';
|
291 | configs.push(createConfigItem(screen, routeNames, pattern, config.path, config.parse));
|
292 | }
|
293 |
|
294 | if (config.screens) {
|
295 |
|
296 | if (config.initialRouteName) {
|
297 | initials.push({
|
298 | initialRouteName: config.initialRouteName,
|
299 | parentScreens
|
300 | });
|
301 | }
|
302 |
|
303 | Object.keys(config.screens).forEach(nestedConfig => {
|
304 | var _pattern;
|
305 |
|
306 | const result = createNormalizedConfigs(nestedConfig, config.screens, routeNames, initials, [...parentScreens], (_pattern = pattern) !== null && _pattern !== void 0 ? _pattern : parentPattern);
|
307 | configs.push(...result);
|
308 | });
|
309 | }
|
310 | }
|
311 |
|
312 | routeNames.pop();
|
313 | return configs;
|
314 | };
|
315 |
|
316 | const createConfigItem = (screen, routeNames, pattern, path, parse) => {
|
317 |
|
318 | pattern = pattern.split('/').filter(Boolean).join('/');
|
319 | const regex = pattern ? new RegExp(`^(${pattern.split('/').map(it => {
|
320 | if (it.startsWith(':')) {
|
321 | return `(([^/]+\\/)${it.endsWith('?') ? '?' : ''})`;
|
322 | }
|
323 |
|
324 | return `${it === '*' ? '.*' : (0, _escapeStringRegexp.default)(it)}\\/`;
|
325 | }).join('')})`) : undefined;
|
326 | return {
|
327 | screen,
|
328 | regex,
|
329 | pattern,
|
330 | path,
|
331 |
|
332 | routeNames: [...routeNames],
|
333 | parse
|
334 | };
|
335 | };
|
336 |
|
337 | const findParseConfigForRoute = (routeName, flatConfig) => {
|
338 | for (const config of flatConfig) {
|
339 | if (routeName === config.routeNames[config.routeNames.length - 1]) {
|
340 | return config.parse;
|
341 | }
|
342 | }
|
343 |
|
344 | return undefined;
|
345 | };
|
346 |
|
347 |
|
348 | const findInitialRoute = (routeName, parentScreens, initialRoutes) => {
|
349 | for (const config of initialRoutes) {
|
350 | if (parentScreens.length === config.parentScreens.length) {
|
351 | let sameParents = true;
|
352 |
|
353 | for (let i = 0; i < parentScreens.length; i++) {
|
354 | if (parentScreens[i].localeCompare(config.parentScreens[i]) !== 0) {
|
355 | sameParents = false;
|
356 | break;
|
357 | }
|
358 | }
|
359 |
|
360 | if (sameParents) {
|
361 | return routeName !== config.initialRouteName ? config.initialRouteName : undefined;
|
362 | }
|
363 | }
|
364 | }
|
365 |
|
366 | return undefined;
|
367 | };
|
368 |
|
369 |
|
370 |
|
371 | const createStateObject = (initialRoute, route, isEmpty) => {
|
372 | if (isEmpty) {
|
373 | if (initialRoute) {
|
374 | return {
|
375 | index: 1,
|
376 | routes: [{
|
377 | name: initialRoute
|
378 | }, route]
|
379 | };
|
380 | } else {
|
381 | return {
|
382 | routes: [route]
|
383 | };
|
384 | }
|
385 | } else {
|
386 | if (initialRoute) {
|
387 | return {
|
388 | index: 1,
|
389 | routes: [{
|
390 | name: initialRoute
|
391 | }, { ...route,
|
392 | state: {
|
393 | routes: []
|
394 | }
|
395 | }]
|
396 | };
|
397 | } else {
|
398 | return {
|
399 | routes: [{ ...route,
|
400 | state: {
|
401 | routes: []
|
402 | }
|
403 | }]
|
404 | };
|
405 | }
|
406 | }
|
407 | };
|
408 |
|
409 | const createNestedStateObject = (path, routes, initialRoutes, flatConfig) => {
|
410 | let state;
|
411 | let route = routes.shift();
|
412 | const parentScreens = [];
|
413 | let initialRoute = findInitialRoute(route.name, parentScreens, initialRoutes);
|
414 | parentScreens.push(route.name);
|
415 | state = createStateObject(initialRoute, route, routes.length === 0);
|
416 |
|
417 | if (routes.length > 0) {
|
418 | let nestedState = state;
|
419 |
|
420 | while (route = routes.shift()) {
|
421 | initialRoute = findInitialRoute(route.name, parentScreens, initialRoutes);
|
422 | const nestedStateIndex = nestedState.index || nestedState.routes.length - 1;
|
423 | nestedState.routes[nestedStateIndex].state = createStateObject(initialRoute, route, routes.length === 0);
|
424 |
|
425 | if (routes.length > 0) {
|
426 | nestedState = nestedState.routes[nestedStateIndex].state;
|
427 | }
|
428 |
|
429 | parentScreens.push(route.name);
|
430 | }
|
431 | }
|
432 |
|
433 | route = (0, _findFocusedRoute.default)(state);
|
434 | route.path = path;
|
435 | const params = parseQueryParams(path, flatConfig ? findParseConfigForRoute(route.name, flatConfig) : undefined);
|
436 |
|
437 | if (params) {
|
438 | route.params = { ...route.params,
|
439 | ...params
|
440 | };
|
441 | }
|
442 |
|
443 | return state;
|
444 | };
|
445 |
|
446 | const parseQueryParams = (path, parseConfig) => {
|
447 | const query = path.split('?')[1];
|
448 | const params = queryString.parse(query);
|
449 |
|
450 | if (parseConfig) {
|
451 | Object.keys(params).forEach(name => {
|
452 | if (Object.hasOwnProperty.call(parseConfig, name) && typeof params[name] === 'string') {
|
453 | params[name] = parseConfig[name](params[name]);
|
454 | }
|
455 | });
|
456 | }
|
457 |
|
458 | return Object.keys(params).length ? params : undefined;
|
459 | };
|
460 |
|
\ | No newline at end of file |