-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
Copy pathlink-to.ts
929 lines (745 loc) · 22.5 KB
/
link-to.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
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
/**
@module ember
*/
import { alias, computed } from '@ember/-internals/metal';
import { getOwner } from '@ember/-internals/owner';
import RouterState from '@ember/-internals/routing/lib/system/router_state';
import { isSimpleClick } from '@ember/-internals/views';
import { assert, warn } from '@ember/debug';
import { EngineInstance, getEngineParent } from '@ember/engine';
import { flaggedInstrument } from '@ember/instrumentation';
import { inject as injectService } from '@ember/service';
import { DEBUG } from '@glimmer/env';
import EmberComponent from '../component';
import { HAS_BLOCK } from '../component-managers/curly';
import layout from '../templates/link-to';
/**
The `LinkTo` component renders a link to the supplied `routeName` passing an optionally
supplied model to the route as its `model` context of the route. The block for `LinkTo`
becomes the contents of the rendered element:
```handlebars
<LinkTo @route='photoGallery'>
Great Hamster Photos
</LinkTo>
```
This will result in:
```html
<a href="/hamster-photos">
Great Hamster Photos
</a>
```
### Disabling the `LinkTo` component
The `LinkTo` component can be disabled by using the `disabled` argument. A disabled link
doesn't result in a transition when activated, and adds the `disabled` class to the `<a>`
element.
(The class name to apply to the element can be overridden by using the `disabledClass`
argument)
```handlebars
<LinkTo @route='photoGallery' @disabled={{true}}>
Great Hamster Photos
</LinkTo>
```
### Handling `href`
`<LinkTo>` will use your application's Router to fill the element's `href` property with a URL
that matches the path to the supplied `routeName`.
### Handling current route
The `LinkTo` component will apply a CSS class name of 'active' when the application's current
route matches the supplied routeName. For example, if the application's current route is
'photoGallery.recent', then the following invocation of `LinkTo`:
```handlebars
<LinkTo @route='photoGallery.recent'>
Great Hamster Photos
</LinkTo>
```
will result in
```html
<a href="/hamster-photos/this-week" class="active">
Great Hamster Photos
</a>
```
The CSS class used for active classes can be customized by passing an `activeClass` argument:
```handlebars
<LinkTo @route='photoGallery.recent' @activeClass="current-url">
Great Hamster Photos
</LinkTo>
```
```html
<a href="/hamster-photos/this-week" class="current-url">
Great Hamster Photos
</a>
```
### Keeping a link active for other routes
If you need a link to be 'active' even when it doesn't match the current route, you can use the
`current-when` argument.
```handlebars
<LinkTo @route='photoGallery' @current-when='photos'>
Photo Gallery
</LinkTo>
```
This may be helpful for keeping links active for:
* non-nested routes that are logically related
* some secondary menu approaches
* 'top navigation' with 'sub navigation' scenarios
A link will be active if `current-when` is `true` or the current
route is the route this link would transition to.
To match multiple routes 'space-separate' the routes:
```handlebars
<LinkTo @route='gallery' @current-when='photos drawings paintings'>
Art Gallery
</LinkTo>
```
### Supplying a model
An optional `model` argument can be used for routes whose
paths contain dynamic segments. This argument will become
the model context of the linked route:
```javascript
Router.map(function() {
this.route("photoGallery", {path: "hamster-photos/:photo_id"});
});
```
```handlebars
<LinkTo @route='photoGallery' @model={{this.aPhoto}}>
{{aPhoto.title}}
</LinkTo>
```
```html
<a href="/hamster-photos/42">
Tomster
</a>
```
### Supplying multiple models
For deep-linking to route paths that contain multiple
dynamic segments, the `models` argument can be used.
As the router transitions through the route path, each
supplied model argument will become the context for the
route with the dynamic segments:
```javascript
Router.map(function() {
this.route("photoGallery", { path: "hamster-photos/:photo_id" }, function() {
this.route("comment", {path: "comments/:comment_id"});
});
});
```
This argument will become the model context of the linked route:
```handlebars
<LinkTo @route='photoGallery.comment' @models={{array this.aPhoto this.comment}}>
{{comment.body}}
</LinkTo>
```
```html
<a href="/hamster-photos/42/comments/718">
A+++ would snuggle again.
</a>
```
### Supplying an explicit dynamic segment value
If you don't have a model object available to pass to `LinkTo`,
an optional string or integer argument can be passed for routes whose
paths contain dynamic segments. This argument will become the value
of the dynamic segment:
```javascript
Router.map(function() {
this.route("photoGallery", { path: "hamster-photos/:photo_id" });
});
```
```handlebars
<LinkTo @route='photoGallery' @model={{aPhotoId}}>
{{this.aPhoto.title}}
</LinkTo>
```
```html
<a href="/hamster-photos/42">
Tomster
</a>
```
When transitioning into the linked route, the `model` hook will
be triggered with parameters including this passed identifier.
### Allowing Default Action
By default the `<LinkTo>` component prevents the default browser action by calling
`preventDefault()` to avoid reloading the browser page.
If you need to trigger a full browser reload pass `@preventDefault={{false}}`:
```handlebars
<LinkTo @route='photoGallery' @model={{this.aPhotoId}} @preventDefault={{false}}>
{{this.aPhotoId.title}}
</LinkTo>
```
### Supplying a `tagName`
By default `<LinkTo>` renders an `<a>` element. This can be overridden for a single use of
`<LinkTo>` by supplying a `tagName` argument:
```handlebars
<LinkTo @route='photoGallery' @tagName='li'>
Great Hamster Photos
</LinkTo>
```
This produces:
```html
<li>
Great Hamster Photos
</li>
```
In general, this is not recommended.
### Supplying query parameters
If you need to add optional key-value pairs that appear to the right of the ? in a URL,
you can use the `query` argument.
```handlebars
<LinkTo @route='photoGallery' @query={{hash page=1 per_page=20}}>
Great Hamster Photos
</LinkTo>
```
This will result in:
```html
<a href="/hamster-photos?page=1&per_page=20">
Great Hamster Photos
</a>
```
@for Ember.Templates.components
@method LinkTo
@see {LinkComponent}
@public
*/
/**
@module @ember/routing
*/
/**
See [Ember.Templates.components.LinkTo](/ember/release/classes/Ember.Templates.components/methods/input?anchor=LinkTo).
@for Ember.Templates.helpers
@method link-to
@see {Ember.Templates.components.LinkTo}
@public
**/
/**
`LinkComponent` is the internal component invoked with `<LinkTo>` or `{{link-to}}`.
@class LinkComponent
@extends Component
@see {Ember.Templates.components.LinkTo}
@public
**/
const UNDEFINED = Object.freeze({
toString() {
return 'UNDEFINED';
},
});
const EMPTY_QUERY_PARAMS = Object.freeze({});
const LinkComponent = EmberComponent.extend({
layout,
tagName: 'a',
/**
@property route
@public
*/
route: UNDEFINED,
/**
@property model
@public
*/
model: UNDEFINED,
/**
@property models
@public
*/
models: UNDEFINED,
/**
@property query
@public
*/
query: UNDEFINED,
/**
Used to determine when this `LinkComponent` is active.
@property current-when
@public
*/
'current-when': null,
/**
Sets the `title` attribute of the `LinkComponent`'s HTML element.
@property title
@default null
@public
**/
title: null,
/**
Sets the `rel` attribute of the `LinkComponent`'s HTML element.
@property rel
@default null
@public
**/
rel: null,
/**
Sets the `tabindex` attribute of the `LinkComponent`'s HTML element.
@property tabindex
@default null
@public
**/
tabindex: null,
/**
Sets the `target` attribute of the `LinkComponent`'s HTML element.
@since 1.8.0
@property target
@default null
@public
**/
target: null,
/**
The CSS class to apply to `LinkComponent`'s element when its `active`
property is `true`.
@property activeClass
@type String
@default active
@public
**/
activeClass: 'active',
/**
The CSS class to apply to `LinkComponent`'s element when its `loading`
property is `true`.
@property loadingClass
@type String
@default loading
@private
**/
loadingClass: 'loading',
/**
The CSS class to apply to a `LinkComponent`'s element when its `disabled`
property is `true`.
@property disabledClass
@type String
@default disabled
@private
**/
disabledClass: 'disabled',
/**
Determines whether the `LinkComponent` will trigger routing via
the `replaceWith` routing strategy.
@property replace
@type Boolean
@default false
@public
**/
replace: false,
/**
By default this component will forward `href`, `title`, `rel`, `tabindex`, and `target`
arguments to attributes on the component's element. When invoked with `{{link-to}}`, you can
only customize these attributes. When invoked with `<LinkTo>`, you can just use HTML
attributes directly.
@property attributeBindings
@type Array | String
@default ['title', 'rel', 'tabindex', 'target']
@public
*/
attributeBindings: ['href', 'title', 'rel', 'tabindex', 'target'],
/**
By default this component will set classes on its element when any of the following arguments
are truthy:
* active
* loading
* disabled
When these arguments are truthy, a class with the same name will be set on the element. When
falsy, the associated class will not be on the element.
@property classNameBindings
@type Array
@default ['active', 'loading', 'disabled', 'ember-transitioning-in', 'ember-transitioning-out']
@public
*/
classNameBindings: ['active', 'loading', 'disabled', 'transitioningIn', 'transitioningOut'],
/**
By default this component responds to the `click` event. When the component element is an
`<a>` element, activating the link in another way, such as using the keyboard, triggers the
click event.
@property eventName
@type String
@default click
@private
*/
eventName: 'click',
// this is doc'ed here so it shows up in the events
// section of the API documentation, which is where
// people will likely go looking for it.
/**
Triggers the `LinkComponent`'s routing behavior. If
`eventName` is changed to a value other than `click`
the routing behavior will trigger on that custom event
instead.
@event click
@private
*/
/**
An overridable method called when `LinkComponent` objects are instantiated.
Example:
```app/components/my-link.js
import LinkComponent from '@ember/routing/link-component';
export default LinkComponent.extend({
init() {
this._super(...arguments);
console.log('Event is ' + this.get('eventName'));
}
});
```
NOTE: If you do override `init` for a framework class like `Component`,
be sure to call `this._super(...arguments)` in your
`init` declaration! If you don't, Ember may not have an opportunity to
do important setup work, and you'll see strange behavior in your
application.
@method init
@private
*/
init() {
this._super(...arguments);
assert(
'You attempted to use the <LinkTo> component within a routeless engine, this is not supported. ' +
'If you are using the ember-engines addon, use the <LinkToExternal> component instead. ' +
'See https://ember-engines.com/docs/links for more info.',
!this._isEngine || this._engineMountPoint !== undefined
);
// Map desired event name to invoke function
let { eventName } = this;
this.on(eventName, this, this._invoke);
},
_routing: injectService('-routing'),
_currentRoute: alias('_routing.currentRouteName'),
_currentRouterState: alias('_routing.currentState'),
_targetRouterState: alias('_routing.targetState'),
_isEngine: computed(function (this: any) {
return getEngineParent(getOwner(this) as EngineInstance) !== undefined;
}),
_engineMountPoint: computed(function (this: any) {
return (getOwner(this) as EngineInstance).mountPoint;
}),
_route: computed('route', '_currentRouterState', function computeLinkToComponentRoute(this: any) {
let { route } = this;
return route === UNDEFINED ? this._currentRoute : this._namespaceRoute(route);
}),
_models: computed('model', 'models', function computeLinkToComponentModels(this: any) {
let { model, models } = this;
assert(
'You cannot provide both the `@model` and `@models` arguments to the <LinkTo> component.',
model === UNDEFINED || models === UNDEFINED
);
if (model !== UNDEFINED) {
return [model];
} else if (models !== UNDEFINED) {
assert('The `@models` argument must be an array.', Array.isArray(models));
return models;
} else {
return [];
}
}),
_query: computed('query', function computeLinkToComponentQuery(this: any) {
let { query } = this;
if (query === UNDEFINED) {
return EMPTY_QUERY_PARAMS;
} else {
return Object.assign({}, query);
}
}),
/**
Accessed as a classname binding to apply the component's `disabledClass`
CSS `class` to the element when the link is disabled.
When `true`, interactions with the element will not trigger route changes.
@property disabled
@private
*/
disabled: computed({
get(_key: string): boolean {
// always returns false for `get` because (due to the `set` just below)
// the cached return value from the set will prevent this getter from _ever_
// being called after a set has occurred
return false;
},
set(this: any, _key: string, value: any): boolean {
this._isDisabled = value;
return value ? this.disabledClass : false;
},
}),
/**
Accessed as a classname binding to apply the component's `activeClass`
CSS `class` to the element when the link is active.
This component is considered active when its `currentWhen` property is `true`
or the application's current route is the route this component would trigger
transitions into.
The `currentWhen` property can match against multiple routes by separating
route names using the ` ` (space) character.
@property active
@private
*/
active: computed('activeClass', '_active', function computeLinkToComponentActiveClass(this: any) {
return this._active ? this.activeClass : false;
}),
_active: computed(
'_currentRouterState',
'_route',
'_models',
'_query',
'loading',
'current-when',
function computeLinkToComponentActive(this: any) {
let { _currentRouterState: state } = this;
if (state) {
return this._isActive(state);
} else {
return false;
}
}
),
willBeActive: computed(
'_currentRouterState',
'_targetRouterState',
'_route',
'_models',
'_query',
'loading',
'current-when',
function computeLinkToComponentWillBeActive(this: any) {
let { _currentRouterState: current, _targetRouterState: target } = this;
if (current === target) {
return;
}
return this._isActive(target);
}
),
_isActive(routerState: RouterState): boolean {
if (this.loading) {
return false;
}
let currentWhen = this['current-when'];
if (typeof currentWhen === 'boolean') {
return currentWhen;
}
let { _models: models, _routing: routing } = this;
if (typeof currentWhen === 'string') {
return currentWhen
.split(' ')
.some((route) =>
routing.isActiveForRoute(models, undefined, this._namespaceRoute(route), routerState)
);
} else {
return routing.isActiveForRoute(models, this._query, this._route, routerState);
}
},
transitioningIn: computed(
'_active',
'willBeActive',
function computeLinkToComponentTransitioningIn(this: any) {
if (this.willBeActive === true && !this._active) {
return 'ember-transitioning-in';
} else {
return false;
}
}
),
transitioningOut: computed(
'_active',
'willBeActive',
function computeLinkToComponentTransitioningOut(this: any) {
if (this.willBeActive === false && this._active) {
return 'ember-transitioning-out';
} else {
return false;
}
}
),
_namespaceRoute(route: string): string {
let { _engineMountPoint: mountPoint } = this;
if (mountPoint === undefined) {
return route;
} else if (route === 'application') {
return mountPoint;
} else {
return `${mountPoint}.${route}`;
}
},
/**
Event handler that invokes the link, activating the associated route.
@method _invoke
@param {Event} event
@private
*/
_invoke(this: any, event: Event): boolean {
if (!isSimpleClick(event)) {
return true;
}
let { bubbles, preventDefault } = this;
let target = this.element.target;
let isSelf = !target || target === '_self';
if (preventDefault !== false && isSelf) {
event.preventDefault();
}
if (bubbles === false) {
event.stopPropagation();
}
if (this._isDisabled) {
return false;
}
if (this.loading) {
// tslint:disable-next-line:max-line-length
warn(
'This link is in an inactive loading state because at least one of its models ' +
'currently has a null/undefined value, or the provided route name is invalid.',
false,
{
id: 'ember-glimmer.link-to.inactive-loading-state',
}
);
return false;
}
if (!isSelf) {
return false;
}
let { _route: routeName, _models: models, _query: queryParams, replace: shouldReplace } = this;
let payload = {
queryParams,
routeName,
};
flaggedInstrument(
'interaction.link-to',
payload,
this._generateTransition(payload, routeName, models, queryParams, shouldReplace)
);
return false;
},
_generateTransition(
payload: any,
qualifiedRouteName: string,
models: any[],
queryParams: any[],
shouldReplace: boolean
) {
let { _routing: routing } = this;
return () => {
payload.transition = routing.transitionTo(
qualifiedRouteName,
models,
queryParams,
shouldReplace
);
};
},
/**
Sets the element's `href` attribute to the url for
the `LinkComponent`'s targeted route.
If the `LinkComponent`'s `tagName` is changed to a value other
than `a`, this property will be ignored.
@property href
@private
*/
href: computed(
'_currentRouterState',
'_route',
'_models',
'_query',
'tagName',
'loading',
'loadingHref',
function computeLinkToComponentHref(this: any) {
if (this.tagName !== 'a') {
return;
}
if (this.loading) {
return this.loadingHref;
}
let { _route: route, _models: models, _query: query, _routing: routing } = this;
if (DEBUG) {
/*
* Unfortunately, to get decent error messages, we need to do this.
* In some future state we should be able to use a "feature flag"
* which allows us to strip this without needing to call it twice.
*
* if (isDebugBuild()) {
* // Do the useful debug thing, probably including try/catch.
* } else {
* // Do the performant thing.
* }
*/
try {
return routing.generateURL(route, models, query);
} catch (e) {
// tslint:disable-next-line:max-line-length
e.message = `While generating link to route "${this.route}": ${e.message}`;
throw e;
}
} else {
return routing.generateURL(route, models, query);
}
}
),
loading: computed(
'_route',
'_modelsAreLoaded',
'loadingClass',
function computeLinkToComponentLoading(this: any) {
let { _route: route, _modelsAreLoaded: loaded } = this;
if (!loaded || route === null || route === undefined) {
return this.loadingClass;
}
}
),
_modelsAreLoaded: computed('_models', function computeLinkToComponentModelsAreLoaded(this: any) {
let { _models: models } = this;
for (let i = 0; i < models.length; i++) {
let model = models[i];
if (model === null || model === undefined) {
return false;
}
}
return true;
}),
/**
The default href value to use while a link-to is loading.
Only applies when tagName is 'a'
@property loadingHref
@type String
@default #
@private
*/
loadingHref: '#',
didReceiveAttrs() {
let { disabledWhen } = this;
if (disabledWhen !== undefined) {
this.set('disabled', disabledWhen);
}
let { params } = this;
if (!params || params.length === 0) {
assert(
'You must provide at least one of the `@route`, `@model`, `@models` or `@query` argument to `<LinkTo>`.',
!(
this.route === UNDEFINED &&
this.model === UNDEFINED &&
this.models === UNDEFINED &&
this.query === UNDEFINED
)
);
let { _models: models } = this;
if (models.length > 0) {
let lastModel = models[models.length - 1];
if (typeof lastModel === 'object' && lastModel !== null && lastModel.isQueryParams) {
this.query = lastModel.values;
models.pop();
}
}
return;
}
params = params.slice();
// Process the positional arguments, in order.
// 1. Inline link title comes first, if present.
if (!this[HAS_BLOCK]) {
this.set('linkTitle', params.shift());
}
// 2. The last argument is possibly the `query` object.
let queryParams = params[params.length - 1];
if (queryParams && queryParams.isQueryParams) {
this.set('query', params.pop().values);
} else {
this.set('query', UNDEFINED);
}
// 3. If there is a `route`, it is now at index 0.
if (params.length === 0) {
this.set('route', UNDEFINED);
} else {
this.set('route', params.shift());
}
// 4. Any remaining indices (if any) are `models`.
this.set('model', UNDEFINED);
this.set('models', params);
},
});
LinkComponent.toString = () => '@ember/routing/link-component';
LinkComponent.reopenClass({
positionalParams: 'params',
});
export default LinkComponent;