forked from emberjs/ember.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
link-to.ts
864 lines (692 loc) · 23.2 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
/**
@module ember
*/
/**
The `{{link-to}}` 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 `{{link-to}}` becomes the innerHTML of the rendered
element:
```handlebars
{{#link-to 'photoGallery'}}
Great Hamster Photos
{{/link-to}}
```
You can also use an inline form of `{{link-to}}` component by
passing the link text as the first argument
to the component:
```handlebars
{{link-to 'Great Hamster Photos' 'photoGallery'}}
```
Both will result in:
```html
<a href="/hamster-photos">
Great Hamster Photos
</a>
```
### Supplying a tagName
By default `{{link-to}}` renders an `<a>` element. This can
be overridden for a single use of `{{link-to}}` by supplying
a `tagName` option:
```handlebars
{{#link-to 'photoGallery' tagName="li"}}
Great Hamster Photos
{{/link-to}}
```
```html
<li>
Great Hamster Photos
</li>
```
To override this option for your entire application, see
"Overriding Application-wide Defaults".
### Disabling the `link-to` component
By default `{{link-to}}` is enabled.
any passed value to the `disabled` component property will disable
the `link-to` component.
static use: the `disabled` option:
```handlebars
{{#link-to 'photoGallery' disabled=true}}
Great Hamster Photos
{{/link-to}}
```
dynamic use: the `disabledWhen` option:
```handlebars
{{#link-to 'photoGallery' disabledWhen=controller.someProperty}}
Great Hamster Photos
{{/link-to}}
```
any passed value to `disabled` will disable it except `undefined`.
to ensure that only `true` disable the `link-to` component you can
override the global behavior of `LinkComponent`.
```javascript
import LinkComponent from '@ember/routing/link-component';
import { computed } from '@ember/object';
LinkComponent.reopen({
disabled: computed(function(key, value) {
if (value !== undefined) {
this.set('_isDisabled', value === true);
}
return value === true ? get(this, 'disabledClass') : false;
})
});
```
see "Overriding Application-wide Defaults" for more.
### Handling `href`
`{{link-to}}` will use your application's Router to
fill the element's `href` property with a url that
matches the path to the supplied `routeName` for your
router's configured `Location` scheme, which defaults
to HashLocation.
### Handling current route
`{{link-to}}` 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' the following
use of `{{link-to}}`:
```handlebars
{{#link-to 'photoGallery.recent'}}
Great Hamster Photos
{{/link-to}}
```
will result in
```html
<a href="/hamster-photos/this-week" class="active">
Great Hamster Photos
</a>
```
The CSS class name used for active classes can be customized
for a single use of `{{link-to}}` by passing an `activeClass`
option:
```handlebars
{{#link-to 'photoGallery.recent' activeClass="current-url"}}
Great Hamster Photos
{{/link-to}}
```
```html
<a href="/hamster-photos/this-week" class="current-url">
Great Hamster Photos
</a>
```
To override this option for your entire application, see
"Overriding Application-wide Defaults".
### 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
{{#link-to 'photoGallery' current-when='photos'}}
Photo Gallery
{{/link-to}}
```
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
{{#link-to 'gallery' current-when='photos drawings paintings'}}
Art Gallery
{{/link-to}}
```
### 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
{{#link-to 'photoGallery' aPhoto}}
{{aPhoto.title}}
{{/link-to}}
```
```html
<a href="/hamster-photos/42">
Tomster
</a>
```
### Supplying multiple models
For deep-linking to route paths that contain multiple
dynamic segments, multiple model arguments 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
{{#link-to 'photoGallery.comment' aPhoto comment}}
{{comment.body}}
{{/link-to}}
```
```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 `{{link-to}}`,
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
{{#link-to 'photoGallery' aPhotoId}}
{{aPhoto.title}}
{{/link-to}}
```
```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 `{{link-to}}` component prevents the default browser action
by calling `preventDefault()` as this sort of action bubbling is normally
handled internally and we do not want to take the browser to a new URL (for
example).
If you need to override this behavior specify `preventDefault=false` in
your template:
```handlebars
{{#link-to 'photoGallery' aPhotoId preventDefault=false}}
{{aPhotoId.title}}
{{/link-to}}
```
### Overriding attributes
You can override any given property of the `LinkComponent`
that is generated by the `{{link-to}}` component by passing
key/value pairs, like so:
```handlebars
{{#link-to aPhoto tagName='li' title='Following this link will change your life' classNames='pic sweet'}}
Uh-mazing!
{{/link-to}}
```
See [LinkComponent](/api/classes/Ember.LinkComponent.html) for a
complete list of overrideable properties. Be sure to also
check out inherited properties of `LinkComponent`.
### Overriding Application-wide Defaults
``{{link-to}}`` creates an instance of `LinkComponent`
for rendering. To override options for your entire
application, reopen `LinkComponent` and supply the
desired values:
``` javascript
import LinkComponent from '@ember/routing/link-component';
LinkComponent.reopen({
activeClass: "is-active",
tagName: 'li'
})
```
It is also possible to override the default event in
this manner:
``` javascript
import LinkCompoennt from '@ember/routing/link-component';
LinkComponent.reopen({
eventName: 'customEventName'
});
```
@method link-to
@for Ember.Templates.helpers
@param {String} routeName
@param {Object} [context]*
@param [options] {Object} Handlebars key/value pairs of options, you can override any property of Ember.LinkComponent
@return {String} HTML string
@see {LinkComponent}
@public
*/
import Logger from 'ember-console';
import { assert, deprecate } from 'ember-debug';
import { DEBUG } from 'ember-env-flags';
import {
computed,
flaggedInstrument,
get,
} from 'ember-metal';
import {
ControllerMixin,
deprecatingAlias,
inject,
} from 'ember-runtime';
import { isSimpleClick } from 'ember-views';
import EmberComponent, { HAS_BLOCK } from '../component';
import layout from '../templates/link-to';
/**
@module @ember/routing
*/
/**
`LinkComponent` renders an element whose `click` event triggers a
transition of the application's instance of `Router` to
a supplied route by name.
`LinkComponent` components are invoked with {{#link-to}}. Properties
of this class can be overridden with `reopen` to customize application-wide
behavior.
@class LinkComponent
@extends Component
@see {Ember.Templates.helpers.link-to}
@public
**/
const LinkComponent = EmberComponent.extend({
layout,
tagName: 'a',
/**
@deprecated Use current-when instead.
@property currentWhen
@private
*/
currentWhen: deprecatingAlias('current-when', { id: 'ember-routing-view.deprecated-current-when', until: '3.0.0' }),
/**
Used to determine when this `LinkComponent` is active.
@property currentWhen
@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 the `{{link-to}}` component will bind to the `href` and
`title` attributes. It's discouraged that you override these defaults,
however you can push onto the array if needed.
@property attributeBindings
@type Array | String
@default ['title', 'rel', 'tabindex', 'target']
@public
*/
attributeBindings: ['href', 'title', 'rel', 'tabindex', 'target'],
/**
By default the `{{link-to}}` component will bind to the `active`, `loading`,
and `disabled` classes. It is discouraged to override these directly.
@property classNameBindings
@type Array
@default ['active', 'loading', 'disabled', 'ember-transitioning-in', 'ember-transitioning-out']
@public
*/
classNameBindings: ['active', 'loading', 'disabled', 'transitioningIn', 'transitioningOut'],
/**
By default the `{{link-to}}` component responds to the `click` event. You
can override this globally by setting this property to your custom
event name.
This is particularly useful on mobile when one wants to avoid the 300ms
click delay using some sort of custom `tap` 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);
this._isDisabled = false;
// Map desired event name to invoke function
let eventName = get(this, 'eventName');
this.on(eventName, this, this._invoke);
},
_routing: inject.service('-routing'),
/**
Accessed as a classname binding to apply the `LinkComponent`'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) {
return false;
},
set(_key, value) {
if (value !== undefined) { this.set('_isDisabled', value); }
return value ? get(this, 'disabledClass') : false;
},
}),
_isActive(routerState) {
if (get(this, 'loading')) { return false; }
let routing = get(this, '_routing');
let models = get(this, 'models');
let resolvedQueryParams = get(this, 'resolvedQueryParams');
let currentWhen = get(this, 'current-when');
if (typeof currentWhen === 'boolean') {
return currentWhen ? get(this, 'activeClass') : false;
}
let isCurrentWhenSpecified = !!currentWhen;
currentWhen = currentWhen || get(this, 'qualifiedRouteName');
currentWhen = currentWhen.split(' ');
for (let i = 0; i < currentWhen.length; i++) {
if (routing.isActiveForRoute(models, resolvedQueryParams, currentWhen[i], routerState, isCurrentWhenSpecified)) {
return true;
}
}
return false;
},
/**
Accessed as a classname binding to apply the `LinkComponent`'s `activeClass`
CSS `class` to the element when the link is active.
A `LinkComponent` is considered active when its `currentWhen` property is `true`
or the application's current route is the route the `LinkComponent` 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.get('_active') ? get(this, 'activeClass') : false;
}),
_active: computed('_routing.currentState', function computeLinkToComponentActive(this: any) {
let currentState = get(this, '_routing.currentState');
if (!currentState) { return false; }
return this._isActive(currentState);
}),
willBeActive: computed('_routing.targetState', function computeLinkToComponentWillBeActive(this: any) {
let routing = get(this, '_routing');
let targetState = get(routing, 'targetState');
if (get(routing, 'currentState') === targetState) { return; }
return this._isActive(targetState);
}),
transitioningIn: computed('active', 'willBeActive', function computeLinkToComponentTransitioningIn(this: any) {
if (get(this, 'willBeActive') === true && !get(this, '_active')) {
return 'ember-transitioning-in';
} else {
return false;
}
}),
transitioningOut: computed('active', 'willBeActive', function computeLinkToComponentTransitioningOut(this: any) {
if (get(this, 'willBeActive') === false && get(this, '_active')) {
return 'ember-transitioning-out';
} else {
return false;
}
}),
/**
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 preventDefault = get(this, 'preventDefault');
let targetAttribute = get(this, 'target');
if (preventDefault !== false) {
if (!targetAttribute || targetAttribute === '_self') {
event.preventDefault();
}
}
if (get(this, 'bubbles') === false) { event.stopPropagation(); }
if (get(this, '_isDisabled')) { return false; }
if (get(this, 'loading')) {
// tslint:disable-next-line:max-line-length
Logger.warn('This link-to is in an inactive loading state because at least one of its parameters presently has a null/undefined value, or the provided route name is invalid.');
return false;
}
if (targetAttribute && targetAttribute !== '_self') {
return false;
}
let qualifiedRouteName = get(this, 'qualifiedRouteName');
let models = get(this, 'models');
let queryParams = get(this, 'queryParams.values');
let shouldReplace = get(this, 'replace');
let payload = {
queryParams,
routeName: qualifiedRouteName,
};
// tslint:disable-next-line:max-line-length
flaggedInstrument('interaction.link-to', payload, this._generateTransition(payload, qualifiedRouteName, models, queryParams, shouldReplace));
return false;
},
_generateTransition(payload, qualifiedRouteName, models, queryParams, shouldReplace) {
let routing = get(this, '_routing');
return () => {
payload.transition = routing.transitionTo(qualifiedRouteName, models, queryParams, shouldReplace);
};
},
queryParams: null,
qualifiedRouteName: computed('targetRouteName', '_routing.currentState',
function computeLinkToComponentQualifiedRouteName(this: any) {
let params = get(this, 'params');
let paramsLength = params.length;
let lastParam = params[paramsLength - 1];
if (lastParam && lastParam.isQueryParams) {
paramsLength--;
}
let onlyQueryParamsSupplied = (this[HAS_BLOCK] ? paramsLength === 0 : paramsLength === 1);
if (onlyQueryParamsSupplied) {
return get(this, '_routing.currentRouteName');
}
return get(this, 'targetRouteName');
}),
resolvedQueryParams: computed('queryParams', function computeLinkToComponentResolvedQueryParams(this: any) {
let resolvedQueryParams = {};
let queryParams = get(this, 'queryParams');
if (!queryParams) { return resolvedQueryParams; }
let values = queryParams.values;
for (let key in values) {
if (!values.hasOwnProperty(key)) { continue; }
resolvedQueryParams[key] = values[key];
}
return resolvedQueryParams;
}),
/**
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('models', 'qualifiedRouteName', function computeLinkToComponentHref(this: any) {
if (get(this, 'tagName') !== 'a') { return; }
let qualifiedRouteName = get(this, 'qualifiedRouteName');
let models = get(this, 'models');
if (get(this, 'loading')) { return get(this, 'loadingHref'); }
let routing = get(this, '_routing');
let queryParams = get(this, 'queryParams.values');
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 {
routing.generateURL(qualifiedRouteName, models, queryParams);
} catch (e) {
// tslint:disable-next-line:max-line-length
assert('You attempted to define a `{{link-to "' + qualifiedRouteName + '"}}` but did not pass the parameters required for generating its dynamic segments. ' + e.message);
}
}
return routing.generateURL(qualifiedRouteName, models, queryParams);
}),
loading: computed('_modelsAreLoaded', 'qualifiedRouteName', function computeLinkToComponentLoading(this: any) {
let qualifiedRouteName = get(this, 'qualifiedRouteName');
let modelsAreLoaded = get(this, '_modelsAreLoaded');
if (!modelsAreLoaded || qualifiedRouteName == null) {
return get(this, 'loadingClass');
}
}),
_modelsAreLoaded: computed('models', function computeLinkToComponentModelsAreLoaded(this: any) {
let models = get(this, 'models');
for (let i = 0; i < models.length; i++) {
if (models[i] == null) { return false; }
}
return true;
}),
_getModels(params) {
let modelCount = params.length - 1;
let models = new Array(modelCount);
for (let i = 0; i < modelCount; i++) {
let value = params[i + 1];
while (ControllerMixin.detect(value)) {
deprecate(
'Providing `{{link-to}}` with a param that is wrapped in a controller is deprecated. ' +
(this.parentView ? 'Please update `' + this.parentView +
'` to use `{{link-to "post" someController.model}}` instead.' : ''),
false,
{ id: 'ember-routing-views.controller-wrapped-param', until: '3.0.0' },
);
value = value.get('model');
}
models[i] = value;
}
return models;
},
/**
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 queryParams;
let params = get(this, 'params');
if (params) {
// Do not mutate params in place
params = params.slice();
}
assert('You must provide one or more parameters to the link-to component.', params && params.length);
let disabledWhen = get(this, 'disabledWhen');
if (disabledWhen !== undefined) {
this.set('disabled', disabledWhen);
}
// Process the positional arguments, in order.
// 1. Inline link title comes first, if present.
if (!this[HAS_BLOCK]) {
this.set('linkTitle', params.shift());
}
// 2. `targetRouteName` is now always at index 0.
this.set('targetRouteName', params[0]);
// 3. The last argument (if still remaining) is the `queryParams` object.
let lastParam = params[params.length - 1];
if (lastParam && lastParam.isQueryParams) {
queryParams = params.pop();
} else {
queryParams = { values: {} };
}
this.set('queryParams', queryParams);
// 4. Any remaining indices (excepting `targetRouteName` at 0) are `models`.
if (params.length > 1) {
this.set('models', this._getModels(params));
} else {
this.set('models', []);
}
},
});
LinkComponent.toString = () => 'LinkComponent';
LinkComponent.reopenClass({
positionalParams: 'params',
});
export default LinkComponent;