Implemented URL query parsing for initial token /opa/?token=abcde
[src/app-framework-demo.git] / afb-client / bower_components / angular-ui-router / src / stateDirectives.js
1 function parseStateRef(ref, current) {
2   var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
3   if (preparsed) ref = current + '(' + preparsed[1] + ')';
4   parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
5   if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'");
6   return { state: parsed[1], paramExpr: parsed[3] || null };
7 }
8
9 function stateContext(el) {
10   var stateData = el.parent().inheritedData('$uiView');
11
12   if (stateData && stateData.state && stateData.state.name) {
13     return stateData.state;
14   }
15 }
16
17 function getTypeInfo(el) {
18   // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
19   var isSvg = Object.prototype.toString.call(el.prop('href')) === '[object SVGAnimatedString]';
20   var isForm = el[0].nodeName === "FORM";
21
22   return {
23     attr: isForm ? "action" : (isSvg ? 'xlink:href' : 'href'),
24     isAnchor: el.prop("tagName").toUpperCase() === "A",
25     clickable: !isForm
26   };
27 }
28
29 function clickHook(el, $state, $timeout, type, current) {
30   return function(e) {
31     var button = e.which || e.button, target = current();
32
33     if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || el.attr('target'))) {
34       // HACK: This is to allow ng-clicks to be processed before the transition is initiated:
35       var transition = $timeout(function() {
36         $state.go(target.state, target.params, target.options);
37       });
38       e.preventDefault();
39
40       // if the state has no URL, ignore one preventDefault from the <a> directive.
41       var ignorePreventDefaultCount = type.isAnchor && !target.href ? 1: 0;
42
43       e.preventDefault = function() {
44         if (ignorePreventDefaultCount-- <= 0) $timeout.cancel(transition);
45       };
46     }
47   };
48 }
49
50 function defaultOpts(el, $state) {
51   return { relative: stateContext(el) || $state.$current, inherit: true };
52 }
53
54 /**
55  * @ngdoc directive
56  * @name ui.router.state.directive:ui-sref
57  *
58  * @requires ui.router.state.$state
59  * @requires $timeout
60  *
61  * @restrict A
62  *
63  * @description
64  * A directive that binds a link (`<a>` tag) to a state. If the state has an associated
65  * URL, the directive will automatically generate & update the `href` attribute via
66  * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking
67  * the link will trigger a state transition with optional parameters.
68  *
69  * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be
70  * handled natively by the browser.
71  *
72  * You can also use relative state paths within ui-sref, just like the relative
73  * paths passed to `$state.go()`. You just need to be aware that the path is relative
74  * to the state that the link lives in, in other words the state that loaded the
75  * template containing the link.
76  *
77  * You can specify options to pass to {@link ui.router.state.$state#go $state.go()}
78  * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,
79  * and `reload`.
80  *
81  * @example
82  * Here's an example of how you'd use ui-sref and how it would compile. If you have the
83  * following template:
84  * <pre>
85  * <a ui-sref="home">Home</a> | <a ui-sref="about">About</a> | <a ui-sref="{page: 2}">Next page</a>
86  *
87  * <ul>
88  *     <li ng-repeat="contact in contacts">
89  *         <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
90  *     </li>
91  * </ul>
92  * </pre>
93  *
94  * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):
95  * <pre>
96  * <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>
97  *
98  * <ul>
99  *     <li ng-repeat="contact in contacts">
100  *         <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
101  *     </li>
102  *     <li ng-repeat="contact in contacts">
103  *         <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
104  *     </li>
105  *     <li ng-repeat="contact in contacts">
106  *         <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
107  *     </li>
108  * </ul>
109  *
110  * <a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
111  * </pre>
112  *
113  * @param {string} ui-sref 'stateName' can be any valid absolute or relative state
114  * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}
115  */
116 $StateRefDirective.$inject = ['$state', '$timeout'];
117 function $StateRefDirective($state, $timeout) {
118   return {
119     restrict: 'A',
120     require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
121     link: function(scope, element, attrs, uiSrefActive) {
122       var ref    = parseStateRef(attrs.uiSref, $state.current.name);
123       var def    = { state: ref.state, href: null, params: null };
124       var type   = getTypeInfo(element);
125       var active = uiSrefActive[1] || uiSrefActive[0];
126
127       def.options = extend(defaultOpts(element, $state), attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {});
128
129       var update = function(val) {
130         if (val) def.params = angular.copy(val);
131         def.href = $state.href(ref.state, def.params, def.options);
132
133         if (active) active.$$addStateInfo(ref.state, def.params);
134         if (def.href !== null) attrs.$set(type.attr, def.href);
135       };
136
137       if (ref.paramExpr) {
138         scope.$watch(ref.paramExpr, function(val) { if (val !== def.params) update(val); }, true);
139         def.params = angular.copy(scope.$eval(ref.paramExpr));
140       }
141       update();
142
143       if (!type.clickable) return;
144       element.bind("click", clickHook(element, $state, $timeout, type, function() { return def; }));
145     }
146   };
147 }
148
149 /**
150  * @ngdoc directive
151  * @name ui.router.state.directive:ui-state
152  *
153  * @requires ui.router.state.uiSref
154  *
155  * @restrict A
156  *
157  * @description
158  * Much like ui-sref, but will accept named $scope properties to evaluate for a state definition,
159  * params and override options.
160  *
161  * @param {string} ui-state 'stateName' can be any valid absolute or relative state
162  * @param {Object} ui-state-params params to pass to {@link ui.router.state.$state#href $state.href()}
163  * @param {Object} ui-state-opts options to pass to {@link ui.router.state.$state#go $state.go()}
164  */
165 $StateRefDynamicDirective.$inject = ['$state', '$timeout'];
166 function $StateRefDynamicDirective($state, $timeout) {
167   return {
168     restrict: 'A',
169     require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
170     link: function(scope, element, attrs, uiSrefActive) {
171       var type   = getTypeInfo(element);
172       var active = uiSrefActive[1] || uiSrefActive[0];
173       var group  = [attrs.uiState, attrs.uiStateParams || null, attrs.uiStateOpts || null];
174       var watch  = '[' + group.map(function(val) { return val || 'null'; }).join(', ') + ']';
175       var def    = { state: null, params: null, options: null, href: null };
176
177       function runStateRefLink (group) {
178         def.state = group[0]; def.params = group[1]; def.options = group[2];
179         def.href = $state.href(def.state, def.params, def.options);
180
181         if (active) active.$$addStateInfo(def.state, def.params);
182         if (def.href) attrs.$set(type.attr, def.href);
183       }
184
185       scope.$watch(watch, runStateRefLink, true);
186       runStateRefLink(scope.$eval(watch));
187
188       if (!type.clickable) return;
189       element.bind("click", clickHook(element, $state, $timeout, type, function() { return def; }));
190     }
191   };
192 }
193
194
195 /**
196  * @ngdoc directive
197  * @name ui.router.state.directive:ui-sref-active
198  *
199  * @requires ui.router.state.$state
200  * @requires ui.router.state.$stateParams
201  * @requires $interpolate
202  *
203  * @restrict A
204  *
205  * @description
206  * A directive working alongside ui-sref to add classes to an element when the
207  * related ui-sref directive's state is active, and removing them when it is inactive.
208  * The primary use-case is to simplify the special appearance of navigation menus
209  * relying on `ui-sref`, by having the "active" state's menu button appear different,
210  * distinguishing it from the inactive menu items.
211  *
212  * ui-sref-active can live on the same element as ui-sref or on a parent element. The first
213  * ui-sref-active found at the same level or above the ui-sref will be used.
214  *
215  * Will activate when the ui-sref's target state or any child state is active. If you
216  * need to activate only when the ui-sref target state is active and *not* any of
217  * it's children, then you will use
218  * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}
219  *
220  * @example
221  * Given the following template:
222  * <pre>
223  * <ul>
224  *   <li ui-sref-active="active" class="item">
225  *     <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
226  *   </li>
227  * </ul>
228  * </pre>
229  *
230  *
231  * When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins",
232  * the resulting HTML will appear as (note the 'active' class):
233  * <pre>
234  * <ul>
235  *   <li ui-sref-active="active" class="item active">
236  *     <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
237  *   </li>
238  * </ul>
239  * </pre>
240  *
241  * The class name is interpolated **once** during the directives link time (any further changes to the
242  * interpolated value are ignored).
243  *
244  * Multiple classes may be specified in a space-separated format:
245  * <pre>
246  * <ul>
247  *   <li ui-sref-active='class1 class2 class3'>
248  *     <a ui-sref="app.user">link</a>
249  *   </li>
250  * </ul>
251  * </pre>
252  *
253  * It is also possible to pass ui-sref-active an expression that evaluates
254  * to an object hash, whose keys represent active class names and whose
255  * values represent the respective state names/globs.
256  * ui-sref-active will match if the current active state **includes** any of
257  * the specified state names/globs, even the abstract ones.
258  *
259  * @Example
260  * Given the following template, with "admin" being an abstract state:
261  * <pre>
262  * <div ui-sref-active="{'active': 'admin.*'}">
263  *   <a ui-sref-active="active" ui-sref="admin.roles">Roles</a>
264  * </div>
265  * </pre>
266  *
267  * When the current state is "admin.roles" the "active" class will be applied
268  * to both the <div> and <a> elements. It is important to note that the state
269  * names/globs passed to ui-sref-active shadow the state provided by ui-sref.
270  */
271
272 /**
273  * @ngdoc directive
274  * @name ui.router.state.directive:ui-sref-active-eq
275  *
276  * @requires ui.router.state.$state
277  * @requires ui.router.state.$stateParams
278  * @requires $interpolate
279  *
280  * @restrict A
281  *
282  * @description
283  * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate
284  * when the exact target state used in the `ui-sref` is active; no child states.
285  *
286  */
287 $StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];
288 function $StateRefActiveDirective($state, $stateParams, $interpolate) {
289   return  {
290     restrict: "A",
291     controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) {
292       var states = [], activeClasses = {}, activeEqClass, uiSrefActive;
293
294       // There probably isn't much point in $observing this
295       // uiSrefActive and uiSrefActiveEq share the same directive object with some
296       // slight difference in logic routing
297       activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope);
298
299       try {
300         uiSrefActive = $scope.$eval($attrs.uiSrefActive);
301       } catch (e) {
302         // Do nothing. uiSrefActive is not a valid expression.
303         // Fall back to using $interpolate below
304       }
305       uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope);
306       if (isObject(uiSrefActive)) {
307         forEach(uiSrefActive, function(stateOrName, activeClass) {
308           if (isString(stateOrName)) {
309             var ref = parseStateRef(stateOrName, $state.current.name);
310             addState(ref.state, $scope.$eval(ref.paramExpr), activeClass);
311           }
312         });
313       }
314
315       // Allow uiSref to communicate with uiSrefActive[Equals]
316       this.$$addStateInfo = function (newState, newParams) {
317         // we already got an explicit state provided by ui-sref-active, so we
318         // shadow the one that comes from ui-sref
319         if (isObject(uiSrefActive) && states.length > 0) {
320           return;
321         }
322         addState(newState, newParams, uiSrefActive);
323         update();
324       };
325
326       $scope.$on('$stateChangeSuccess', update);
327
328       function addState(stateName, stateParams, activeClass) {
329         var state = $state.get(stateName, stateContext($element));
330         var stateHash = createStateHash(stateName, stateParams);
331
332         states.push({
333           state: state || { name: stateName },
334           params: stateParams,
335           hash: stateHash
336         });
337
338         activeClasses[stateHash] = activeClass;
339       }
340
341       /**
342        * @param {string} state
343        * @param {Object|string} [params]
344        * @return {string}
345        */
346       function createStateHash(state, params) {
347         if (!isString(state)) {
348           throw new Error('state should be a string');
349         }
350         if (isObject(params)) {
351           return state + toJson(params);
352         }
353         params = $scope.$eval(params);
354         if (isObject(params)) {
355           return state + toJson(params);
356         }
357         return state;
358       }
359
360       // Update route state
361       function update() {
362         for (var i = 0; i < states.length; i++) {
363           if (anyMatch(states[i].state, states[i].params)) {
364             addClass($element, activeClasses[states[i].hash]);
365           } else {
366             removeClass($element, activeClasses[states[i].hash]);
367           }
368
369           if (exactMatch(states[i].state, states[i].params)) {
370             addClass($element, activeEqClass);
371           } else {
372             removeClass($element, activeEqClass);
373           }
374         }
375       }
376
377       function addClass(el, className) { $timeout(function () { el.addClass(className); }); }
378       function removeClass(el, className) { el.removeClass(className); }
379       function anyMatch(state, params) { return $state.includes(state.name, params); }
380       function exactMatch(state, params) { return $state.is(state.name, params); }
381
382       update();
383     }]
384   };
385 }
386
387 angular.module('ui.router.state')
388   .directive('uiSref', $StateRefDirective)
389   .directive('uiSrefActive', $StateRefActiveDirective)
390   .directive('uiSrefActiveEq', $StateRefActiveDirective)
391   .directive('uiState', $StateRefDynamicDirective);