-
Notifications
You must be signed in to change notification settings - Fork 3k
/
stateDirectives.ts
732 lines (674 loc) · 25.2 KB
/
stateDirectives.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
/* eslint-disable @typescript-eslint/no-empty-interface */
/* eslint-disable prefer-const */
/**
* # Angular 1 Directives
*
* These are the directives included in UI-Router for Angular 1.
* These directives are used in templates to create viewports and link/navigate to states.
*
* @preferred @publicapi @module directives
*/ /** */
import { ng as angular } from '../angular';
import { IAugmentedJQuery, ITimeoutService, IScope, IInterpolateService } from 'angular';
import {
Obj,
extend,
forEach,
tail,
isString,
isObject,
isArray,
parse,
noop,
unnestR,
identity,
uniqR,
inArray,
removeFrom,
RawParams,
PathNode,
StateOrName,
StateService,
StateDeclaration,
UIRouter,
} from '@uirouter/core';
import { UIViewData } from './viewDirective';
/** @hidden Used for typedoc */
export interface ng1_directive {}
/** @hidden */
function parseStateRef(ref: string) {
const paramsOnly = ref.match(/^\s*({[^}]*})\s*$/);
if (paramsOnly) ref = '(' + paramsOnly[1] + ')';
const parsed = ref.replace(/\n/g, ' ').match(/^\s*([^(]*?)\s*(\((.*)\))?\s*$/);
if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'");
return { state: parsed[1] || null, paramExpr: parsed[3] || null };
}
/** @hidden */
function stateContext(el: IAugmentedJQuery) {
const $uiView: UIViewData = (el.parent() as IAugmentedJQuery).inheritedData('$uiView');
const path: PathNode[] = parse('$cfg.path')($uiView);
return path ? tail(path).state.name : undefined;
}
/** @hidden */
function processedDef($state: StateService, $element: IAugmentedJQuery, def: Def): Def {
const uiState = def.uiState || $state.current.name;
const uiStateOpts = extend(defaultOpts($element, $state), def.uiStateOpts || {});
const href = $state.href(uiState, def.uiStateParams, uiStateOpts);
return { uiState, uiStateParams: def.uiStateParams, uiStateOpts, href };
}
/** @hidden */
interface TypeInfo {
attr: string;
isAnchor: boolean;
clickable: boolean;
}
/** @hidden */
function getTypeInfo(el: IAugmentedJQuery): TypeInfo {
// SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
const isSvg = Object.prototype.toString.call(el.prop('href')) === '[object SVGAnimatedString]';
const isForm = el[0].nodeName === 'FORM';
return {
attr: isForm ? 'action' : isSvg ? 'xlink:href' : 'href',
isAnchor: el.prop('tagName').toUpperCase() === 'A',
clickable: !isForm,
};
}
/** @hidden */
function clickHook(
el: IAugmentedJQuery,
$state: StateService,
$timeout: ITimeoutService,
type: TypeInfo,
getDef: () => Def
) {
return function (e: JQueryMouseEventObject) {
const button = e.which || e.button,
target = getDef();
if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey || el.attr('target'))) {
// HACK: This is to allow ng-clicks to be processed before the transition is initiated:
const transition = $timeout(function () {
if (!el.attr('disabled')) {
$state.go(target.uiState, target.uiStateParams, target.uiStateOpts);
}
});
e.preventDefault();
// if the state has no URL, ignore one preventDefault from the <a> directive.
let ignorePreventDefaultCount = type.isAnchor && !target.href ? 1 : 0;
e.preventDefault = function () {
if (ignorePreventDefaultCount-- <= 0) $timeout.cancel(transition);
};
}
};
}
/** @hidden */
function defaultOpts(el: IAugmentedJQuery, $state: StateService) {
return {
relative: stateContext(el) || $state.$current,
inherit: true,
source: 'sref',
};
}
/** @hidden */
function bindEvents(element: IAugmentedJQuery, scope: IScope, hookFn: EventListener, uiStateOpts: any): void {
let events;
if (uiStateOpts) {
events = uiStateOpts.events;
}
if (!isArray(events)) {
events = ['click'];
}
const on = element.on ? 'on' : 'bind';
for (const event of events) {
element[on](event, hookFn);
}
scope.$on('$destroy', function () {
const off = element.off ? 'off' : 'unbind';
for (const event of events) {
element[off](event, hookFn as any);
}
});
}
/**
* `ui-sref`: A directive for linking to a state
*
* A directive which links to a state (and optionally, parameters).
* When clicked, this directive activates the linked state with the supplied parameter values.
*
* ### Linked State
* The attribute value of the `ui-sref` is the name of the state to link to.
*
* #### Example:
* This will activate the `home` state when the link is clicked.
* ```html
* <a ui-sref="home">Home</a>
* ```
*
* ### Relative Links
* You can also use relative state paths within `ui-sref`, just like a relative path passed to `$state.go()` ([[StateService.go]]).
* You just need to be aware that the path is relative to the state that *created* the link.
* This allows a state to create a relative `ui-sref` which always targets the same destination.
*
* #### Example:
* Both these links are relative to the parent state, even when a child state is currently active.
* ```html
* <a ui-sref=".child1">child 1 state</a>
* <a ui-sref=".child2">child 2 state</a>
* ```
*
* This link activates the parent state.
* ```html
* <a ui-sref="^">Return</a>
* ```
*
* ### hrefs
* If the linked state has a URL, the directive will automatically generate and
* update the `href` attribute (using the [[StateService.href]] method).
*
* #### Example:
* Assuming the `users` state has a url of `/users/`
* ```html
* <a ui-sref="users" href="/users/">Users</a>
* ```
*
* ### Parameter Values
* In addition to the state name, a `ui-sref` can include parameter values which are applied when activating the state.
* Param values can be provided in the `ui-sref` value after the state name, enclosed by parentheses.
* The content inside the parentheses is an expression, evaluated to the parameter values.
*
* #### Example:
* This example renders a list of links to users.
* The state's `userId` parameter value comes from each user's `user.id` property.
* ```html
* <li ng-repeat="user in users">
* <a ui-sref="users.detail({ userId: user.id })">{{ user.displayName }}</a>
* </li>
* ```
*
* Note:
* The parameter values expression is `$watch`ed for updates.
*
* ### Transition Options
* You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-sref-opts` attribute.
* Options are restricted to `location`, `inherit`, and `reload`.
*
* #### Example:
* ```html
* <a ui-sref="home" ui-sref-opts="{ reload: true }">Home</a>
* ```
*
* ### Other DOM Events
*
* You can also customize which DOM events to respond to (instead of `click`) by
* providing an `events` array in the `ui-sref-opts` attribute.
*
* #### Example:
* ```html
* <input type="text" ui-sref="contacts" ui-sref-opts="{ events: ['change', 'blur'] }">
* ```
*
* ### Highlighting the active link
* This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link.
*
* ### Examples
* If you have the following template:
*
* ```html
* <a ui-sref="home">Home</a>
* <a ui-sref="about">About</a>
* <a ui-sref="{page: 2}">Next page</a>
*
* <ul>
* <li ng-repeat="contact in contacts">
* <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
* </li>
* </ul>
* ```
*
* Then (assuming the current state is `contacts`) the rendered html including hrefs would be:
*
* ```html
* <a href="#/home" ui-sref="home">Home</a>
* <a href="#/about" ui-sref="about">About</a>
* <a href="#/contacts?page=2" ui-sref="{page: 2}">Next page</a>
*
* <ul>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
* </li>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
* </li>
* <li ng-repeat="contact in contacts">
* <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
* </li>
* </ul>
*
* <a href="#/home" ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
* ```
*
* ### Notes
*
* - You can use `ui-sref` to change **only the parameter values** by omitting the state name and parentheses.
* #### Example:
* Sets the `lang` parameter to `en` and remains on the same state.
*
* ```html
* <a ui-sref="{ lang: 'en' }">English</a>
* ```
*
* - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example.
*
* - Unlike the parameter values expression, the state name is not `$watch`ed (for performance reasons).
* If you need to dynamically update the state being linked to, use the fully dynamic [[uiState]] directive.
*/
let uiSrefDirective: ng1_directive;
uiSrefDirective = [
'$uiRouter',
'$timeout',
function $StateRefDirective($uiRouter: UIRouter, $timeout: ITimeoutService) {
const $state = $uiRouter.stateService;
return {
restrict: 'A',
require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
link: function (scope: IScope, element: IAugmentedJQuery, attrs: any, uiSrefActive: any) {
const type = getTypeInfo(element);
const active = uiSrefActive[1] || uiSrefActive[0];
let unlinkInfoFn: Function = null;
const rawDef = {} as Def;
const getDef = () => processedDef($state, element, rawDef);
const ref = parseStateRef(attrs.uiSref);
rawDef.uiState = ref.state;
rawDef.uiStateOpts = attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {};
function update() {
const def = getDef();
if (unlinkInfoFn) unlinkInfoFn();
if (active) unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams);
if (def.href != null) attrs.$set(type.attr, def.href);
}
if (ref.paramExpr) {
scope.$watch(
ref.paramExpr,
function (val) {
rawDef.uiStateParams = extend({}, val);
update();
},
true
);
rawDef.uiStateParams = extend({}, scope.$eval(ref.paramExpr));
}
update();
scope.$on('$destroy', <any>$uiRouter.stateRegistry.onStatesChanged(update));
scope.$on('$destroy', <any>$uiRouter.transitionService.onSuccess({}, update));
if (!type.clickable) return;
const hookFn = clickHook(element, $state, $timeout, type, getDef);
bindEvents(element, scope, hookFn, rawDef.uiStateOpts);
},
};
},
];
/**
* `ui-state`: A fully dynamic directive for linking to a state
*
* A directive which links to a state (and optionally, parameters).
* When clicked, this directive activates the linked state with the supplied parameter values.
*
* **This directive is very similar to [[uiSref]], but it `$observe`s and `$watch`es/evaluates all its inputs.**
*
* A directive which links to a state (and optionally, parameters).
* When clicked, this directive activates the linked state with the supplied parameter values.
*
* ### Linked State
* The attribute value of `ui-state` is an expression which is `$watch`ed and evaluated as the state to link to.
* **This is in contrast with `ui-sref`, which takes a state name as a string literal.**
*
* #### Example:
* Create a list of links.
* ```html
* <li ng-repeat="link in navlinks">
* <a ui-state="link.state">{{ link.displayName }}</a>
* </li>
* ```
*
* ### Relative Links
* If the expression evaluates to a relative path, it is processed like [[uiSref]].
* You just need to be aware that the path is relative to the state that *created* the link.
* This allows a state to create relative `ui-state` which always targets the same destination.
*
* ### hrefs
* If the linked state has a URL, the directive will automatically generate and
* update the `href` attribute (using the [[StateService.href]] method).
*
* ### Parameter Values
* In addition to the state name expression, a `ui-state` can include parameter values which are applied when activating the state.
* Param values should be provided using the `ui-state-params` attribute.
* The `ui-state-params` attribute value is `$watch`ed and evaluated as an expression.
*
* #### Example:
* This example renders a list of links with param values.
* The state's `userId` parameter value comes from each user's `user.id` property.
* ```html
* <li ng-repeat="link in navlinks">
* <a ui-state="link.state" ui-state-params="link.params">{{ link.displayName }}</a>
* </li>
* ```
*
* ### Transition Options
* You can specify [[TransitionOptions]] to pass to [[StateService.go]] by using the `ui-state-opts` attribute.
* Options are restricted to `location`, `inherit`, and `reload`.
* The value of the `ui-state-opts` is `$watch`ed and evaluated as an expression.
*
* #### Example:
* ```html
* <a ui-state="returnto.state" ui-state-opts="{ reload: true }">Home</a>
* ```
*
* ### Other DOM Events
*
* You can also customize which DOM events to respond to (instead of `click`) by
* providing an `events` array in the `ui-state-opts` attribute.
*
* #### Example:
* ```html
* <input type="text" ui-state="contacts" ui-state-opts="{ events: ['change', 'blur'] }">
* ```
*
* ### Highlighting the active link
* This directive can be used in conjunction with [[uiSrefActive]] to highlight the active link.
*
* ### Notes
*
* - You can use `ui-params` to change **only the parameter values** by omitting the state name and supplying only `ui-state-params`.
* However, it might be simpler to use [[uiSref]] parameter-only links.
*
* #### Example:
* Sets the `lang` parameter to `en` and remains on the same state.
*
* ```html
* <a ui-state="" ui-state-params="{ lang: 'en' }">English</a>
* ```
*
* - A middle-click, right-click, or ctrl-click is handled (natively) by the browser to open the href in a new window, for example.
* ```
*/
let uiStateDirective: ng1_directive;
uiStateDirective = [
'$uiRouter',
'$timeout',
function $StateRefDynamicDirective($uiRouter: UIRouter, $timeout: ITimeoutService) {
const $state = $uiRouter.stateService;
return {
restrict: 'A',
require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
link: function (scope: IScope, element: IAugmentedJQuery, attrs: any, uiSrefActive: any) {
const type = getTypeInfo(element);
const active = uiSrefActive[1] || uiSrefActive[0];
let unlinkInfoFn: Function = null;
let hookFn;
const rawDef = {} as Def;
const getDef = () => processedDef($state, element, rawDef);
const inputAttrs = ['uiState', 'uiStateParams', 'uiStateOpts'];
const watchDeregFns = inputAttrs.reduce((acc, attr) => ((acc[attr] = noop), acc), {});
function update() {
const def = getDef();
if (unlinkInfoFn) unlinkInfoFn();
if (active) unlinkInfoFn = active.$$addStateInfo(def.uiState, def.uiStateParams);
if (def.href != null) attrs.$set(type.attr, def.href);
}
inputAttrs.forEach((field) => {
rawDef[field] = attrs[field] ? scope.$eval(attrs[field]) : null;
attrs.$observe(field, (expr) => {
watchDeregFns[field]();
watchDeregFns[field] = scope.$watch(
expr,
(newval) => {
rawDef[field] = newval;
update();
},
true
);
});
});
update();
scope.$on('$destroy', <any>$uiRouter.stateRegistry.onStatesChanged(update));
scope.$on('$destroy', <any>$uiRouter.transitionService.onSuccess({}, update));
if (!type.clickable) return;
hookFn = clickHook(element, $state, $timeout, type, getDef);
bindEvents(element, scope, hookFn, rawDef.uiStateOpts);
},
};
},
];
/**
* `ui-sref-active` and `ui-sref-active-eq`: A directive that adds a CSS class when a `ui-sref` is active
*
* A directive working alongside [[uiSref]] and [[uiState]] to add classes to an element when the
* related directive's state is active (and remove them when it is inactive).
*
* The primary use-case is to highlight the active link in navigation menus,
* distinguishing it from the inactive menu items.
*
* ### Linking to a `ui-sref` or `ui-state`
* `ui-sref-active` can live on the same element as `ui-sref`/`ui-state`, or it can be on a parent element.
* If a `ui-sref-active` is a parent to more than one `ui-sref`/`ui-state`, it will apply the CSS class when **any of the links are active**.
*
* ### Matching
*
* The `ui-sref-active` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state **or any child state is active**.
* This is a "fuzzy match" which uses [[StateService.includes]].
*
* The `ui-sref-active-eq` directive applies the CSS class when the `ui-sref`/`ui-state`'s target state is directly active (not when child states are active).
* This is an "exact match" which uses [[StateService.is]].
*
* ### Parameter values
* If the `ui-sref`/`ui-state` includes parameter values, the current parameter values must match the link's values for the link to be highlighted.
* This allows a list of links to the same state with different parameters to be rendered, and the correct one highlighted.
*
* #### Example:
* ```html
* <li ng-repeat="user in users" ui-sref-active="active">
* <a ui-sref="user.details({ userId: user.id })">{{ user.lastName }}</a>
* </li>
* ```
*
* ### Examples
*
* Given the following template:
* #### Example:
* ```html
* <ul>
* <li ui-sref-active="active" class="item">
* <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
* </li>
* </ul>
* ```
*
* When the app state is `app.user` (or any child state),
* and contains the state parameter "user" with value "bilbobaggins",
* the resulting HTML will appear as (note the 'active' class):
*
* ```html
* <ul>
* <li ui-sref-active="active" class="item active">
* <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
* </li>
* </ul>
* ```
*
* ### Glob mode
*
* It is possible to pass `ui-sref-active` an expression that evaluates to an object.
* The objects keys represent active class names and values represent the respective state names/globs.
* `ui-sref-active` will match if the current active state **includes** any of
* the specified state names/globs, even the abstract ones.
*
* #### Example:
* Given the following template, with "admin" being an abstract state:
* ```html
* <div ui-sref-active="{'active': 'admin.**'}">
* <a ui-sref-active="active" ui-sref="admin.roles">Roles</a>
* </div>
* ```
*
* Arrays are also supported as values in the `ngClass`-like interface.
* This allows multiple states to add `active` class.
*
* #### Example:
* Given the following template, with "admin.roles" being the current state, the class will be added too:
* ```html
* <div ui-sref-active="{'active': ['owner.**', 'admin.**']}">
* <a ui-sref-active="active" ui-sref="admin.roles">Roles</a>
* </div>
* ```
*
* When the current state is "admin.roles" the "active" class will be applied to both the `<div>` and `<a>` elements.
* It is important to note that the state names/globs passed to `ui-sref-active` override any state provided by a linked `ui-sref`.
*
* ### Notes:
*
* - The class name is interpolated **once** during the directives link time (any further changes to the
* interpolated value are ignored).
*
* - Multiple classes may be specified in a space-separated format: `ui-sref-active='class1 class2 class3'`
*/
let uiSrefActiveDirective: ng1_directive;
uiSrefActiveDirective = [
'$state',
'$stateParams',
'$interpolate',
'$uiRouter',
function $StateRefActiveDirective(
$state: StateService,
$stateParams: Obj,
$interpolate: IInterpolateService,
$uiRouter: UIRouter
) {
return {
restrict: 'A',
controller: [
'$scope',
'$element',
'$attrs',
function ($scope: IScope, $element: IAugmentedJQuery, $attrs: any) {
let states: StateData[] = [];
let activeEqClass: string;
let uiSrefActive: any;
// There probably isn't much point in $observing this
// uiSrefActive and uiSrefActiveEq share the same directive object with some
// slight difference in logic routing
activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope);
try {
uiSrefActive = $scope.$eval($attrs.uiSrefActive);
} catch (e) {
// Do nothing. uiSrefActive is not a valid expression.
// Fall back to using $interpolate below
}
uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope);
setStatesFromDefinitionObject(uiSrefActive);
// Allow uiSref to communicate with uiSrefActive[Equals]
this.$$addStateInfo = function (newState: string, newParams: Obj) {
// we already got an explicit state provided by ui-sref-active, so we
// shadow the one that comes from ui-sref
if (isObject(uiSrefActive) && states.length > 0) {
return;
}
const deregister = addState(newState, newParams, uiSrefActive);
update();
return deregister;
};
function updateAfterTransition(trans) {
trans.promise.then(update, noop);
}
$scope.$on('$destroy', setupEventListeners());
if ($uiRouter.globals.transition) {
updateAfterTransition($uiRouter.globals.transition);
}
function setupEventListeners() {
const deregisterStatesChangedListener = $uiRouter.stateRegistry.onStatesChanged(handleStatesChanged);
const deregisterOnStartListener = $uiRouter.transitionService.onStart({}, updateAfterTransition);
const deregisterStateChangeSuccessListener = $scope.$on('$stateChangeSuccess', update);
return function cleanUp() {
deregisterStatesChangedListener();
deregisterOnStartListener();
deregisterStateChangeSuccessListener();
};
}
function handleStatesChanged() {
setStatesFromDefinitionObject(uiSrefActive);
}
function setStatesFromDefinitionObject(statesDefinition: Obj) {
if (isObject(statesDefinition)) {
states = [];
forEach(statesDefinition, function (stateOrName: StateOrName | Array<StateOrName>, activeClass: string) {
// Helper function to abstract adding state.
const addStateForClass = function (stateOrName: string, activeClass: string) {
const ref = parseStateRef(stateOrName);
addState(ref.state, $scope.$eval(ref.paramExpr), activeClass);
};
if (isString(stateOrName)) {
// If state is string, just add it.
addStateForClass(stateOrName as string, activeClass);
} else if (isArray(stateOrName)) {
// If state is an array, iterate over it and add each array item individually.
forEach(stateOrName, function (stateOrName: string) {
addStateForClass(stateOrName, activeClass);
});
}
});
}
}
function addState(stateName: string, stateParams: Obj, activeClass: string) {
const state = $state.get(stateName, stateContext($element));
const stateInfo = {
state: state || { name: stateName },
params: stateParams,
activeClass: activeClass,
};
states.push(stateInfo);
return function removeState() {
removeFrom(states)(stateInfo);
};
}
// Update route state
function update() {
const splitClasses = (str) => str.split(/\s/).filter(identity);
const getClasses = (stateList: StateData[]) =>
stateList
.map((x) => x.activeClass)
.map(splitClasses)
.reduce(unnestR, []);
const allClasses = getClasses(states).concat(splitClasses(activeEqClass)).reduce(uniqR, []);
const fuzzyClasses = getClasses(states.filter((x) => $state.includes(x.state.name, x.params)));
const exactlyMatchesAny = !!states.filter((x) => $state.is(x.state.name, x.params)).length;
const exactClasses = exactlyMatchesAny ? splitClasses(activeEqClass) : [];
const addClasses = fuzzyClasses.concat(exactClasses).reduce(uniqR, []);
const removeClasses = allClasses.filter((cls) => !inArray(addClasses, cls));
$scope.$evalAsync(() => {
addClasses.forEach((className) => $element.addClass(className));
removeClasses.forEach((className) => $element.removeClass(className));
});
}
update();
},
],
};
},
];
/** @hidden */
interface Def {
uiState: string;
href: string;
uiStateParams: Obj;
uiStateOpts: any;
}
/** @hidden */
interface StateData {
state: StateDeclaration;
params: RawParams;
activeClass: string;
}
angular
.module('ui.router.state')
.directive('uiSref', uiSrefDirective)
.directive('uiSrefActive', uiSrefActiveDirective)
.directive('uiSrefActiveEq', uiSrefActiveDirective)
.directive('uiState', uiStateDirective);