-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
Copy pathutils.ts
291 lines (241 loc) · 8.13 KB
/
utils.ts
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
import { get } from '@ember/-internals/metal';
import { getOwner } from '@ember/-internals/owner';
import type { ControllerQueryParam, ControllerQueryParamType } from '@ember/controller';
import { assert } from '@ember/debug';
import EngineInstance from '@ember/engine/instance';
import type { InternalRouteInfo } from 'router_js';
import type Router from 'router_js';
import { STATE_SYMBOL } from 'router_js';
import type { ExtendedInternalRouteInfo } from '@ember/routing/route';
import type Route from '@ember/routing/route';
import type EmberRouter from '@ember/routing/router';
const ALL_PERIODS_REGEX = /\./g;
export type ExpandedControllerQueryParam = {
as: string | null;
scope: string;
type?: ControllerQueryParamType;
};
export type NamedRouteArgs =
| [routeNameOrUrl: string, ...modelsAndOptions: [...unknown[], RouteOptions]]
| [routeNameOrUrl: string, ...models: unknown[]];
export type UnnamedRouteArgs =
| [...modelsAndOptions: [...unknown[], RouteOptions]]
| [...models: unknown[]]
| [options: RouteOptions];
export type RouteArgs = NamedRouteArgs | UnnamedRouteArgs;
type ExtractedArgs = {
routeName: string | undefined;
models: unknown[];
queryParams: Record<string, unknown>;
};
export type RouteOptions = { queryParams: Record<string, unknown> };
export function extractRouteArgs(args: RouteArgs): ExtractedArgs {
// SAFETY: This should just be the same thing
args = args.slice() as RouteArgs;
let possibleOptions = args[args.length - 1];
let queryParams: Record<string, unknown>;
if (isRouteOptions(possibleOptions)) {
args.pop(); // Remove options
queryParams = possibleOptions.queryParams;
} else {
queryParams = {};
}
let routeName;
if (typeof args[0] === 'string') {
routeName = args.shift();
// We just checked this!
assert('routeName is a string', typeof routeName === 'string');
}
// SAFTEY: We removed the name and options if they existed, only models left.
let models = args;
return { routeName, models, queryParams };
}
export function getActiveTargetName(router: Router<Route>): string {
let routeInfos = router.activeTransition
? router.activeTransition[STATE_SYMBOL]!.routeInfos
: router.state!.routeInfos;
let lastRouteInfo = routeInfos[routeInfos.length - 1];
assert('has last route info', lastRouteInfo);
return lastRouteInfo.name;
}
export function stashParamNames(
router: EmberRouter,
routeInfos: Array<ExtendedInternalRouteInfo<Route>> & { _namesStashed?: boolean }
): void {
if (routeInfos['_namesStashed']) {
return;
}
// This helper exists because router.js/route-recognizer.js awkwardly
// keeps separate a routeInfo's list of parameter names depending
// on whether a URL transition or named transition is happening.
// Hopefully we can remove this in the future.
let routeInfo = routeInfos[routeInfos.length - 1];
assert('has route info', routeInfo);
let targetRouteName = routeInfo.name;
let recogHandlers = router._routerMicrolib.recognizer.handlersFor(targetRouteName);
let dynamicParent: InternalRouteInfo<Route>;
for (let i = 0; i < routeInfos.length; ++i) {
let routeInfo = routeInfos[i];
assert('has route info', routeInfo);
let names = recogHandlers[i].names;
if (names.length) {
dynamicParent = routeInfo;
}
routeInfo['_names'] = names;
let route = routeInfo.route!;
route._stashNames(routeInfo, dynamicParent!);
}
routeInfos['_namesStashed'] = true;
}
function _calculateCacheValuePrefix(prefix: string, part: string) {
// calculates the dot separated sections from prefix that are also
// at the start of part - which gives us the route name
// given : prefix = site.article.comments, part = site.article.id
// - returns: site.article (use get(values[site.article], 'id') to get the dynamic part - used below)
// given : prefix = site.article, part = site.article.id
// - returns: site.article. (use get(values[site.article], 'id') to get the dynamic part - used below)
let prefixParts = prefix.split('.');
let currPrefix = '';
for (let i = 0; i < prefixParts.length; i++) {
let currPart = prefixParts.slice(0, i + 1).join('.');
if (part.indexOf(currPart) !== 0) {
break;
}
currPrefix = currPart;
}
return currPrefix;
}
/*
Stolen from Controller
*/
export function calculateCacheKey(prefix: string, parts: string[] = [], values: {} | null): string {
let suffixes = '';
for (let part of parts) {
let cacheValuePrefix = _calculateCacheValuePrefix(prefix, part);
let value;
if (values) {
if (cacheValuePrefix && cacheValuePrefix in values) {
let partRemovedPrefix =
part.indexOf(cacheValuePrefix) === 0 ? part.substring(cacheValuePrefix.length + 1) : part;
value = get((values as any)[cacheValuePrefix], partRemovedPrefix);
} else {
value = get(values, part);
}
}
suffixes += `::${part}:${value}`;
}
return prefix + suffixes.replace(ALL_PERIODS_REGEX, '-');
}
/*
Controller-defined query parameters can come in three shapes:
Array
queryParams: ['foo', 'bar']
Array of simple objects where value is an alias
queryParams: [
{
'foo': 'rename_foo_to_this'
},
{
'bar': 'call_bar_this_instead'
}
]
Array of fully defined objects
queryParams: [
{
'foo': {
as: 'rename_foo_to_this'
},
}
{
'bar': {
as: 'call_bar_this_instead',
scope: 'controller'
}
}
]
This helper normalizes all three possible styles into the
'Array of fully defined objects' style.
*/
export function normalizeControllerQueryParams(queryParams: Readonly<ControllerQueryParam[]>) {
let qpMap: Record<string, ExpandedControllerQueryParam> = {};
for (let queryParam of queryParams) {
accumulateQueryParamDescriptors(queryParam, qpMap);
}
return qpMap;
}
function accumulateQueryParamDescriptors(
_desc: ControllerQueryParam,
accum: Record<string, ExpandedControllerQueryParam>
) {
let desc = typeof _desc === 'string' ? { [_desc]: { as: null } } : _desc;
for (let key in desc) {
if (!Object.prototype.hasOwnProperty.call(desc, key)) {
return;
}
let _singleDesc = desc[key];
let singleDesc = typeof _singleDesc === 'string' ? { as: _singleDesc } : _singleDesc;
let partialVal = accum[key] || { as: null, scope: 'model' };
let val = { ...partialVal, ...singleDesc };
accum[key] = val;
}
}
/*
Check if a routeName resembles a url instead
@private
*/
export function resemblesURL(str: unknown): str is string {
return typeof str === 'string' && (str === '' || str[0] === '/');
}
/*
Returns an arguments array where the route name arg is prefixed based on the mount point
@private
*/
export function prefixRouteNameArg<T extends NamedRouteArgs | UnnamedRouteArgs>(
route: Route,
args: T
): T {
let routeName: string;
let owner = getOwner(route);
assert('Expected route to have EngineInstance as owner', owner instanceof EngineInstance);
let prefix = owner.mountPoint;
// only alter the routeName if it's actually referencing a route.
if (owner.routable && typeof args[0] === 'string') {
routeName = args[0];
if (resemblesURL(routeName)) {
throw new Error(
'Programmatic transitions by URL cannot be used within an Engine. Please use the route name instead.'
);
} else {
routeName = `${prefix}.${routeName}`;
args[0] = routeName;
}
}
return args;
}
export function shallowEqual<A extends object, B extends object>(a: A, b: B): boolean {
let aCount = 0;
let bCount = 0;
for (let kA in a) {
if (Object.prototype.hasOwnProperty.call(a, kA)) {
if (a[kA] !== (b as any)[kA]) {
return false;
}
aCount++;
}
}
for (let kB in b) {
if (Object.prototype.hasOwnProperty.call(b, kB)) {
bCount++;
}
}
return aCount === bCount;
}
function isRouteOptions(value: unknown): value is RouteOptions {
if (value && typeof value === 'object') {
let qps = (value as RouteOptions).queryParams;
if (qps && typeof qps === 'object') {
return Object.keys(qps).every((k) => typeof k === 'string');
}
}
return false;
}