UNPKG

18.5 kBTypeScriptView Raw
1declare module '@ember/routing/router' {
2 import type { OutletView } from '@ember/-internals/glimmer';
3 import type { default as Owner } from '@ember/owner';
4 import { default as BucketCache } from '@ember/routing/lib/cache';
5 import { default as DSL, type DSLCallback } from '@ember/routing/lib/dsl';
6 import RouterState from '@ember/routing/lib/router_state';
7 import type { RouteArgs, RouteOptions } from '@ember/routing/lib/utils';
8 import type {
9 default as EmberLocation,
10 Registry as LocationRegistry,
11 } from '@ember/routing/location';
12 import type RouterService from '@ember/routing/router-service';
13 import EmberObject from '@ember/object';
14 import Evented from '@ember/object/evented';
15 import { type QueryParamMeta, type default as Route } from '@ember/routing/route';
16 import type {
17 InternalRouteInfo,
18 ModelFor,
19 RouteInfo,
20 RouteInfoWithAttributes,
21 Transition,
22 TransitionState,
23 } from 'router_js';
24 import Router from 'router_js';
25 import type { Timer } from 'backburner.js';
26 import EngineInstance from '@ember/engine/instance';
27 import type { QueryParams } from 'route-recognizer';
28 import type { MethodNamesOf, OmitFirst } from '@ember/-internals/utility-types';
29 /**
30 @module @ember/routing/router
31 */
32 function defaultDidTransition(this: EmberRouter, infos: InternalRouteInfo<Route>[]): void;
33 function defaultWillTransition(
34 this: EmberRouter,
35 oldInfos: InternalRouteInfo<Route>[],
36 newInfos: InternalRouteInfo<Route>[]
37 ): void;
38 export interface QueryParam {
39 prop: string;
40 urlKey: string;
41 type: string;
42 route: Route;
43 parts?: string[];
44 values: {} | null;
45 scopedPropertyName: string;
46 scope: string;
47 defaultValue: unknown;
48 undecoratedDefaultValue: unknown;
49 serializedValue: string | null | undefined;
50 serializedDefaultValue: string | null | undefined;
51 controllerName: string;
52 }
53 const EmberRouter_base: Readonly<typeof EmberObject> &
54 (new (owner?: Owner | undefined) => EmberObject) &
55 import('@ember/object/mixin').default;
56 /**
57 The `EmberRouter` class manages the application state and URLs. Refer to
58 the [routing guide](https://guides.emberjs.com/release/routing/) for documentation.
59
60 @class EmberRouter
61 @extends EmberObject
62 @uses Evented
63 @public
64 */
65 class EmberRouter extends EmberRouter_base implements Evented {
66 /**
67 Represents the URL of the root of the application, often '/'. This prefix is
68 assumed on all routes defined on this router.
69
70 @property rootURL
71 @default '/'
72 @public
73 */
74 rootURL: string;
75 /**
76 The `location` property determines the type of URL's that your
77 application will use.
78
79 The following location types are currently available:
80
81 * `history` - use the browser's history API to make the URLs look just like any standard URL
82 * `hash` - use `#` to separate the server part of the URL from the Ember part: `/blog/#/posts/new`
83 * `none` - do not store the Ember URL in the actual browser URL (mainly used for testing)
84 * `auto` - use the best option based on browser capabilities: `history` if possible, then `hash` if possible, otherwise `none`
85
86 This value is defaulted to `history` by the `locationType` setting of `/config/environment.js`
87
88 @property location
89 @default 'hash'
90 @see {Location}
91 @public
92 */
93 location: (keyof LocationRegistry & string) | EmberLocation;
94 _routerMicrolib: Router<Route>;
95 _didSetupRouter: boolean;
96 _initialTransitionStarted: boolean;
97 currentURL: string | null;
98 currentRouteName: string | null;
99 currentPath: string | null;
100 currentRoute: RouteInfo | RouteInfoWithAttributes | null;
101 _qpCache: Record<
102 string,
103 {
104 qps: QueryParam[];
105 map: QueryParamMeta['map'];
106 }
107 >;
108 _qpUpdates: Set<string>;
109 _queuedQPChanges: Record<string, unknown>;
110 _bucketCache: BucketCache;
111 _toplevelView: OutletView | null;
112 _handledErrors: Set<unknown>;
113 _engineInstances: Record<string, Record<string, EngineInstance>>;
114 _engineInfoByRoute: any;
115 _routerService: RouterService;
116 _slowTransitionTimer: Timer | null;
117 private namespace;
118 on: (name: string, method: ((...args: any[]) => void) | string) => this;
119 one: (name: string, method: string | ((...args: any[]) => void)) => this;
120 trigger: (name: string, ...args: any[]) => unknown;
121 off: (name: string, method: string | ((...args: any[]) => void)) => this;
122 has: (name: string) => boolean;
123 private static dslCallbacks?;
124 /**
125 The `Router.map` function allows you to define mappings from URLs to routes
126 in your application. These mappings are defined within the
127 supplied callback function using `this.route`.
128
129 The first parameter is the name of the route which is used by default as the
130 path name as well.
131
132 The second parameter is the optional options hash. Available options are:
133
134 * `path`: allows you to provide your own path as well as mark dynamic
135 segments.
136 * `resetNamespace`: false by default; when nesting routes, ember will
137 combine the route names to form the fully-qualified route name, which is
138 used with `{{link-to}}` or manually transitioning to routes. Setting
139 `resetNamespace: true` will cause the route not to inherit from its
140 parent route's names. This is handy for preventing extremely long route names.
141 Keep in mind that the actual URL path behavior is still retained.
142
143 The third parameter is a function, which can be used to nest routes.
144 Nested routes, by default, will have the parent route tree's route name and
145 path prepended to it's own.
146
147 ```app/router.js
148 Router.map(function(){
149 this.route('post', { path: '/post/:post_id' }, function() {
150 this.route('edit');
151 this.route('comments', { resetNamespace: true }, function() {
152 this.route('new');
153 });
154 });
155 });
156 ```
157
158 @method map
159 @param callback
160 @public
161 */
162 static map(callback: DSLCallback): typeof EmberRouter;
163 static _routePath(routeInfos: InternalRouteInfo<Route>[]): string;
164 constructor(owner?: Owner);
165 _initRouterJs(): void;
166 _buildDSL(): DSL;
167 _resetQueuedQueryParameterChanges(): void;
168 _hasModuleBasedResolver(): boolean;
169 /**
170 Initializes the current router instance and sets up the change handling
171 event listeners used by the instances `location` implementation.
172
173 A property named `initialURL` will be used to determine the initial URL.
174 If no value is found `/` will be used.
175
176 @method startRouting
177 @private
178 */
179 startRouting(): void;
180 setupRouter(): boolean;
181 _setOutlets(): void;
182 handleURL(url: string): import('router_js').InternalTransition<Route<unknown>>;
183 _doURLTransition<M extends 'handleURL' | 'transitionTo'>(
184 routerJsMethod: M,
185 url: string
186 ): import('router_js').InternalTransition<Route<unknown>>;
187 /**
188 Transition the application into another route. The route may
189 be either a single route or route path:
190
191 @method transitionTo
192 @param {String} [name] the name of the route or a URL
193 @param {...Object} models the model(s) or identifier(s) to be used while
194 transitioning to the route.
195 @param {Object} [options] optional hash with a queryParams property
196 containing a mapping of query parameters
197 @return {Transition} the transition object associated with this
198 attempted transition
199 @public
200 */
201 transitionTo(...args: RouteArgs): Transition;
202 intermediateTransitionTo(name: string, ...args: any[]): void;
203 /**
204 Similar to `transitionTo`, but instead of adding the destination to the browser's URL history,
205 it replaces the entry for the current route.
206 When the user clicks the "back" button in the browser, there will be fewer steps.
207 This is most commonly used to manage redirects in a way that does not cause confusing additions
208 to the user's browsing history.
209
210 @method replaceWith
211 @param {String} [name] the name of the route or a URL
212 @param {...Object} models the model(s) or identifier(s) to be used while
213 transitioning to the route.
214 @param {Object} [options] optional hash with a queryParams property
215 containing a mapping of query parameters
216 @return {Transition} the transition object associated with this
217 attempted transition
218 @public
219 */
220 replaceWith(...args: RouteArgs): Transition;
221 generate(
222 name: string,
223 ...args: ModelFor<Route>[] | [...ModelFor<Route>[], RouteOptions]
224 ): string;
225 /**
226 Determines if the supplied route is currently active.
227
228 @method isActive
229 @param routeName
230 @return {Boolean}
231 @private
232 */
233 isActive(routeName: string): boolean;
234 /**
235 An alternative form of `isActive` that doesn't require
236 manual concatenation of the arguments into a single
237 array.
238
239 @method isActiveIntent
240 @param routeName
241 @param models
242 @param queryParams
243 @return {Boolean}
244 @private
245 @since 1.7.0
246 */
247 isActiveIntent(
248 routeName: string,
249 models: ModelFor<Route>[],
250 queryParams: Record<string, unknown>
251 ): boolean;
252 send(name: string, ...args: any[]): void;
253 /**
254 Does this router instance have the given route.
255
256 @method hasRoute
257 @return {Boolean}
258 @private
259 */
260 hasRoute(route: string): boolean;
261 /**
262 Resets the state of the router by clearing the current route
263 handlers and deactivating them.
264
265 @private
266 @method reset
267 */
268 reset(): void;
269 willDestroy(): void;
270 _activeQPChanged(queryParameterName: string, newValue: unknown): void;
271 _updatingQPChanged(queryParameterName: string): void;
272 _fireQueryParamTransition(): void;
273 _setupLocation(): void;
274 /**
275 Serializes the given query params according to their QP meta information.
276
277 @private
278 @method _serializeQueryParams
279 @param {Arrray<RouteInfo>} routeInfos
280 @param {Object} queryParams
281 @return {Void}
282 */
283 _serializeQueryParams(
284 routeInfos: InternalRouteInfo<Route>[],
285 queryParams: Record<string, unknown>
286 ): asserts queryParams is Record<string, string | null | undefined>;
287 /**
288 Serializes the value of a query parameter based on a type
289
290 @private
291 @method _serializeQueryParam
292 @param {Object} value
293 @param {String} type
294 */
295 _serializeQueryParam(value: unknown, type: string): string | null | undefined;
296 /**
297 Deserializes the given query params according to their QP meta information.
298
299 @private
300 @method _deserializeQueryParams
301 @param {Array<RouteInfo>} routeInfos
302 @param {Object} queryParams
303 @return {Void}
304 */
305 _deserializeQueryParams(
306 routeInfos: InternalRouteInfo<Route>[],
307 queryParams: Record<string, unknown>
308 ): void;
309 /**
310 Deserializes the value of a query parameter based on a default type
311
312 @private
313 @method _deserializeQueryParam
314 @param {Object} value
315 @param {String} defaultType
316 */
317 _deserializeQueryParam(value: unknown, defaultType: string): {} | null | undefined;
318 /**
319 Removes (prunes) any query params with default values from the given QP
320 object. Default values are determined from the QP meta information per key.
321
322 @private
323 @method _pruneDefaultQueryParamValues
324 @param {Array<RouteInfo>} routeInfos
325 @param {Object} queryParams
326 @return {Void}
327 */
328 _pruneDefaultQueryParamValues(
329 routeInfos: InternalRouteInfo<Route>[],
330 queryParams: Record<string, string | null | undefined>
331 ): void;
332 _doTransition(
333 _targetRouteName: string | undefined,
334 models: ModelFor<Route>[],
335 _queryParams: Record<string, unknown>,
336 _fromRouterService?: boolean
337 ): Transition;
338 _processActiveTransitionQueryParams(
339 targetRouteName: string,
340 models: ModelFor<Route>[],
341 queryParams: Record<string, unknown>,
342 _queryParams: {}
343 ): void;
344 /**
345 Prepares the query params for a URL or Transition. Restores any undefined QP
346 keys/values, serializes all values, and then prunes any default values.
347
348 @private
349 @method _prepareQueryParams
350 @param {String} targetRouteName
351 @param {Array<Object>} models
352 @param {Object} queryParams
353 @param {boolean} keepDefaultQueryParamValues
354 @return {Void}
355 */
356 _prepareQueryParams(
357 targetRouteName: string,
358 models: ModelFor<Route>[],
359 queryParams: Record<string, unknown>,
360 _fromRouterService?: boolean
361 ): void;
362 /**
363 Returns the meta information for the query params of a given route. This
364 will be overridden to allow support for lazy routes.
365
366 @private
367 @method _getQPMeta
368 @param {RouteInfo} routeInfo
369 @return {Object}
370 */
371 _getQPMeta(routeInfo: InternalRouteInfo<Route>): QueryParamMeta | undefined;
372 /**
373 Returns a merged query params meta object for a given set of routeInfos.
374 Useful for knowing what query params are available for a given route hierarchy.
375
376 @private
377 @method _queryParamsFor
378 @param {Array<RouteInfo>} routeInfos
379 @return {Object}
380 */
381 _queryParamsFor(routeInfos: InternalRouteInfo<Route>[]): {
382 qps: QueryParam[];
383 map: Record<string, QueryParam>;
384 };
385 /**
386 Maps all query param keys to their fully scoped property name of the form
387 `controllerName:propName`.
388
389 @private
390 @method _fullyScopeQueryParams
391 @param {String} leafRouteName
392 @param {Array<Object>} contexts
393 @param {Object} queryParams
394 @return {Void}
395 */
396 _fullyScopeQueryParams(
397 leafRouteName: string,
398 contexts: ModelFor<Route>[],
399 queryParams: QueryParams
400 ): void;
401 /**
402 Hydrates (adds/restores) any query params that have pre-existing values into
403 the given queryParams hash. This is what allows query params to be "sticky"
404 and restore their last known values for their scope.
405
406 @private
407 @method _hydrateUnsuppliedQueryParams
408 @param {TransitionState} state
409 @param {Object} queryParams
410 @return {Void}
411 */
412 _hydrateUnsuppliedQueryParams(
413 state: TransitionState<Route>,
414 queryParams: QueryParams,
415 _fromRouterService: boolean
416 ): void;
417 _scheduleLoadingEvent(transition: Transition, originRoute: Route): void;
418 currentState: null | RouterState;
419 targetState: null | RouterState;
420 _handleSlowTransition(transition: Transition, originRoute: Route): void;
421 _cancelSlowTransitionTimer(): void;
422 _markErrorAsHandled(error: Error): void;
423 _isErrorHandled(error: Error): boolean;
424 _clearHandledError(error: Error): void;
425 _getEngineInstance({
426 name,
427 instanceId,
428 mountPoint,
429 }: {
430 name: string;
431 instanceId: number;
432 mountPoint: string;
433 }): EngineInstance;
434 /**
435 Handles updating the paths and notifying any listeners of the URL
436 change.
437
438 Triggers the router level `didTransition` hook.
439
440 For example, to notify google analytics when the route changes,
441 you could use this hook. (Note: requires also including GA scripts, etc.)
442
443 ```javascript
444 import config from './config/environment';
445 import EmberRouter from '@ember/routing/router';
446 import { service } from '@ember/service';
447
448 let Router = EmberRouter.extend({
449 location: config.locationType,
450
451 router: service(),
452
453 didTransition: function() {
454 this._super(...arguments);
455
456 ga('send', 'pageview', {
457 page: this.router.currentURL,
458 title: this.router.currentRouteName,
459 });
460 }
461 });
462 ```
463
464 @method didTransition
465 @private
466 @since 1.2.0
467 */
468 didTransition: typeof defaultDidTransition;
469 /**
470 Handles notifying any listeners of an impending URL
471 change.
472
473 Triggers the router level `willTransition` hook.
474
475 @method willTransition
476 @private
477 @since 1.11.0
478 */
479 willTransition: typeof defaultWillTransition;
480 /**
481 Represents the current URL.
482
483 @property url
484 @type {String}
485 @private
486 */
487 url: string;
488 }
489 let defaultActionHandlers: {
490 willResolveModel<R extends Route<unknown>>(
491 this: EmberRouter,
492 _routeInfos: InternalRouteInfo<Route>[],
493 transition: Transition,
494 originRoute: R
495 ): void;
496 error(
497 this: EmberRouter,
498 routeInfos: InternalRouteInfo<Route>[],
499 error: Error,
500 transition: Transition
501 ): void;
502 loading(
503 this: EmberRouter,
504 routeInfos: InternalRouteInfo<Route>[],
505 transition: Transition
506 ): void;
507 };
508 export function triggerEvent<N extends MethodNamesOf<typeof defaultActionHandlers>>(
509 this: EmberRouter,
510 routeInfos: InternalRouteInfo<Route>[],
511 ignoreFailure: boolean,
512 name: N,
513 args: OmitFirst<Parameters<(typeof defaultActionHandlers)[N]>>
514 ): void;
515 export default EmberRouter;
516}