-
Notifications
You must be signed in to change notification settings - Fork 86
/
angular-css.js
666 lines (619 loc) · 22.1 KB
/
angular-css.js
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
/**
* AngularCSS - CSS on-demand for AngularJS
* @version v1.0.8
* @author Alex Castillo
* @link http://castillo-io.github.io/angular-css
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
'use strict';
(function (angular) {
/**
* AngularCSS Module
* Contains: config, constant, provider and run
**/
var angularCSS = angular.module('angularCSS', []);
// Old module name handler
angular.module('door3.css', [])
.run(function () {
console.error('AngularCSS: The module name "door3.css" is now deprecated. Please use "angularCSS" instead.');
});
// Provider
angularCSS.provider('$css', [function $cssProvider() {
// Defaults - default options that can be overridden from application config
var defaults = this.defaults = {
element: 'link',
rel: 'stylesheet',
type: 'text/css',
container: 'head',
method: 'append',
weight: 0
};
var DEBUG = false;
// Turn off/on in order to see console logs during dev mode
this.debugMode = function(mode) {
if (angular.isDefined(mode))
DEBUG = mode;
return DEBUG;
};
this.$get = ['$rootScope','$injector','$q','$window','$timeout','$compile','$http','$filter','$log', '$interpolate',
function $get($rootScope, $injector, $q, $window, $timeout, $compile, $http, $filter, $log, $interpolate) {
var $css = {};
var template = '<link ng-repeat="stylesheet in stylesheets | orderBy: \'weight\' track by $index " rel="{{ stylesheet.rel }}" type="{{ stylesheet.type }}" ng-href="{{ stylesheet.href }}" ng-attr-media="{{ stylesheet.media }}">';
// Using correct interpolation symbols.
template = template
.replace(/{{/g, $interpolate.startSymbol())
.replace(/}}/g, $interpolate.endSymbol());
// Variables - default options that can be overridden from application config
var mediaQuery = {}, mediaQueryListener = {}, mediaQueriesToIgnore = ['print'], options = angular.extend({}, defaults),
container = angular.element(document.querySelector ? document.querySelector(options.container) : document.getElementsByTagName(options.container)[0]),
dynamicPaths = [];
// Parse all directives
angular.forEach($directives, function (directive, key) {
if (directive.hasOwnProperty('css')) {
$directives[key] = parse(directive.css);
}
});
/**
* Listen for directive add event in order to add stylesheet(s)
**/
function $directiveAddEventListener(event, directive, scope) {
// Binds directive's css
if (scope && directive.hasOwnProperty('css')) {
$css.bind(directive.css, scope);
}
}
/**
* Listen for route change event and add/remove stylesheet(s)
**/
function $routeEventListener(event, current, prev) {
// Removes previously added css rules
if (prev) {
$css.remove($css.getFromRoute(prev).concat(dynamicPaths));
// Reset dynamic paths array
dynamicPaths.length = 0;
}
// Adds current css rules
if (current) {
$css.add($css.getFromRoute(current));
}
}
/**
* Listen for state change event and add/remove stylesheet(s)
**/
function $stateEventListener(event, current, params, prev) {
// Removes previously added css rules
if (prev) {
$css.remove($css.getFromState(prev).concat(dynamicPaths));
// Reset dynamic paths array
dynamicPaths.length = 0;
}
// Adds current css rules
if (current) {
$css.add($css.getFromState(current));
}
}
/**
* Map breakpoitns defined in defaults to stylesheet media attribute
**/
function mapBreakpointToMedia(stylesheet) {
if (angular.isDefined(options.breakpoints)) {
if (stylesheet.breakpoint in options.breakpoints) {
stylesheet.media = options.breakpoints[stylesheet.breakpoint];
}
delete stylesheet.breakpoints;
}
}
/**
* Parse: returns array with full all object based on defaults
**/
function parse(obj) {
if (!obj) {
return;
}
// Function syntax
if (angular.isFunction(obj)) {
obj = angular.copy($injector.invoke(obj));
}
// String syntax
if (angular.isString(obj)) {
obj = angular.extend({
href: obj
}, options);
}
// Array of strings syntax
if (angular.isArray(obj) && angular.isString(obj[0])) {
angular.forEach(obj, function (item) {
obj = angular.extend({
href: item
}, options);
});
}
// Object syntax
if (angular.isObject(obj) && !angular.isArray(obj)) {
obj = angular.extend({}, options, obj);
}
// Array of objects syntax
if (angular.isArray(obj) && angular.isObject(obj[0])) {
angular.forEach(obj, function (item) {
obj = angular.extend(item, options);
});
}
// Map breakpoint to media attribute
mapBreakpointToMedia(obj);
return obj;
}
// Add stylesheets to scope
$rootScope.stylesheets = [];
// Adds compiled link tags to container element
container[options.method]($compile(template)($rootScope));
// Directive event listener (emulated internally)
$rootScope.$on('$directiveAdd', $directiveAddEventListener);
// Routes event listener ($route required)
$rootScope.$on('$routeChangeSuccess', $routeEventListener);
// States event listener ($state required)
$rootScope.$on('$stateChangeSuccess', $stateEventListener);
/**
* Bust Cache
**/
function bustCache(stylesheet) {
if (!stylesheet) {
if(DEBUG) $log.error('No stylesheets provided');
return;
}
var queryString = '?cache=';
// Append query string for bust cache only once
if (stylesheet.href.indexOf(queryString) === -1) {
stylesheet.href = stylesheet.href + (stylesheet.bustCache ? queryString + (new Date().getTime()) : '');
}
}
/**
* Filter By: returns an array of routes based on a property option
**/
function filterBy(array, prop) {
if (!array || !prop) {
if(DEBUG) $log.error('filterBy: missing array or property');
return;
}
return $filter('filter')(array, function (item) {
return item[prop];
});
}
/**
* Add Media Query
**/
function addViaMediaQuery(stylesheet) {
if (!stylesheet) {
if(DEBUG) $log.error('No stylesheet provided');
return;
}
// Media query object
mediaQuery[stylesheet.href] = $window.matchMedia(stylesheet.media);
// Media Query Listener function
mediaQueryListener[stylesheet.href] = function(mediaQuery) {
// Trigger digest
$timeout(function () {
if (mediaQuery.matches) {
// Add stylesheet
$rootScope.stylesheets.push(stylesheet);
} else {
var index = $rootScope.stylesheets.indexOf($filter('filter')($rootScope.stylesheets, {
href: stylesheet.href
})[0]);
// Remove stylesheet
if (index !== -1) {
$rootScope.stylesheets.splice(index, 1);
}
}
});
};
// Listen for media query changes
mediaQuery[stylesheet.href].addListener(mediaQueryListener[stylesheet.href]);
// Invoke first media query check
mediaQueryListener[stylesheet.href](mediaQuery[stylesheet.href]);
}
/**
* Remove Media Query
**/
function removeViaMediaQuery(stylesheet) {
if (!stylesheet) {
if(DEBUG) $log.error('No stylesheet provided');
return;
}
// Remove media query listener
if ($rootScope && angular.isDefined(mediaQuery)
&& mediaQuery[stylesheet.href]
&& angular.isDefined(mediaQueryListener)) {
mediaQuery[stylesheet.href].removeListener(mediaQueryListener[stylesheet.href]);
}
}
/**
* Is Media Query: checks for media settings, media queries to be ignore and match media support
**/
function isMediaQuery(stylesheet) {
if (!stylesheet) {
if(DEBUG) $log.error('No stylesheet provided');
return;
}
return !!(
// Check for media query setting
stylesheet.media
// Check for media queries to be ignored
&& (mediaQueriesToIgnore.indexOf(stylesheet.media) === -1)
// Check for matchMedia support
&& $window.matchMedia
);
}
/**
* Get From Route: returns array of css objects from single route
**/
$css.getFromRoute = function (route) {
if (!route) {
if(DEBUG) $log.error('Get From Route: No route provided');
return;
}
var css = null, result = [];
if (route.$$route && route.$$route.css) {
css = route.$$route.css;
}
else if (route.css) {
css = route.css;
}
// Adds route css rules to array
if (css) {
if (angular.isArray(css)) {
angular.forEach(css, function (cssItem) {
if (angular.isFunction(cssItem)) {
dynamicPaths.push(parse(cssItem));
}
result.push(parse(cssItem));
});
} else {
if (angular.isFunction(css)) {
dynamicPaths.push(parse(css));
}
result.push(parse(css));
}
}
return result;
};
/**
* Get From Routes: returns array of css objects from ng routes
**/
$css.getFromRoutes = function (routes) {
if (!routes) {
if(DEBUG) $log.error('Get From Routes: No routes provided');
return;
}
var result = [];
// Make array of all routes
angular.forEach(routes, function (route) {
var css = $css.getFromRoute(route);
if (css.length) {
result.push(css[0]);
}
});
return result;
};
/**
* Get From State: returns array of css objects from single state
**/
$css.getFromState = function (state) {
if (!state) {
if(DEBUG) $log.error('Get From State: No state provided');
return;
}
var result = [];
// State "views" notation
if (angular.isDefined(state.views)) {
angular.forEach(state.views, function (item) {
if (item.css) {
if (angular.isFunction(item.css)) {
dynamicPaths.push(parse(item.css));
}
result.push(parse(item.css));
}
});
}
// State "children" notation
if (angular.isDefined(state.children)) {
angular.forEach(state.children, function (child) {
if (child.css) {
if (angular.isFunction(child.css)) {
dynamicPaths.push(parse(child.css));
}
result.push(parse(child.css));
}
if (angular.isDefined(child.children)) {
angular.forEach(child.children, function (childChild) {
if (childChild.css) {
if (angular.isFunction(childChild.css)) {
dynamicPaths.push(parse(childChild.css));
}
result.push(parse(childChild.css));
}
});
}
});
}
// State default notation
if (
angular.isDefined(state.css) ||
(angular.isDefined(state.data) && angular.isDefined(state.data.css))
) {
var css = state.css || state.data.css;
// For multiple stylesheets
if (angular.isArray(css)) {
angular.forEach(css, function (itemCss) {
if (angular.isFunction(itemCss)) {
dynamicPaths.push(parse(itemCss));
}
result.push(parse(itemCss));
});
// For single stylesheets
} else {
if (angular.isFunction(css)) {
dynamicPaths.push(parse(css));
}
result.push(parse(css));
}
}
return result;
};
/**
* Get From States: returns array of css objects from states
**/
$css.getFromStates = function (states) {
if (!states) {
if(DEBUG) $log.error('Get From States: No states provided');
return;
}
var result = [];
// Make array of all routes
angular.forEach(states, function (state) {
var css = $css.getFromState(state);
if (angular.isArray(css)) {
angular.forEach(css, function (cssItem) {
result.push(cssItem);
});
} else {
result.push(css);
}
});
return result;
};
/**
* Preload: preloads css via http request
**/
$css.preload = function (stylesheets, callback) {
// If no stylesheets provided, then preload all
if (!stylesheets) {
stylesheets = [];
// Add all stylesheets from custom directives to array
if ($directives.length) {
Array.prototype.push.apply(stylesheets, $directives);
}
// Add all stylesheets from ngRoute to array
if ($injector.has('$route')) {
Array.prototype.push.apply(stylesheets, $css.getFromRoutes($injector.get('$route').routes));
}
// Add all stylesheets from UI Router to array
if ($injector.has('$state')) {
Array.prototype.push.apply(stylesheets, $css.getFromStates($injector.get('$state').get()));
}
stylesheets = filterBy(stylesheets, 'preload');
}
if (!angular.isArray(stylesheets)) {
stylesheets = [stylesheets];
}
var stylesheetLoadPromises = [];
angular.forEach(stylesheets, function(stylesheet, key) {
stylesheet = stylesheets[key] = parse(stylesheet);
stylesheetLoadPromises.push(
// Preload via ajax request
$http.get(stylesheet.href).catch(function (response) {
if(DEBUG) $log.error('AngularCSS: Incorrect path for ' + stylesheet.href);
})
);
});
if (angular.isFunction(callback)) {
$q.all(stylesheetLoadPromises).then(function () {
callback(stylesheets);
});
}
};
/**
* Bind: binds css in scope with own scope create/destroy events
**/
$css.bind = function (css, $scope) {
if (!css || !$scope) {
if(DEBUG) $log.error('No scope or stylesheets provided');
return;
}
var result = [];
// Adds route css rules to array
if (angular.isArray(css)) {
angular.forEach(css, function (cssItem) {
result.push(parse(cssItem));
});
} else {
result.push(parse(css));
}
$css.add(result);
if(DEBUG) $log.debug('$css.bind(): Added', result);
$scope.$on('$destroy', function () {
$css.remove(result);
if(DEBUG) $log.debug('$css.bind(): Removed', result);
});
};
/**
* Add: adds stylesheets to scope
**/
$css.add = function (stylesheets, callback) {
if (!stylesheets) {
if(DEBUG) $log.error('No stylesheets provided');
return;
}
if (!angular.isArray(stylesheets)) {
stylesheets = [stylesheets];
}
angular.forEach(stylesheets, function(stylesheet) {
stylesheet = parse(stylesheet);
// Avoid adding duplicate stylesheets
if (stylesheet.href && !$filter('filter')($rootScope.stylesheets, { href: stylesheet.href }).length) {
// Bust Cache feature
bustCache(stylesheet);
// Media Query add support check
if (isMediaQuery(stylesheet)) {
addViaMediaQuery(stylesheet);
}
else {
$rootScope.stylesheets.push(stylesheet);
}
if(DEBUG) $log.debug('$css.add(): ' + stylesheet.href);
}
});
// Broadcasts custom event for css add
$rootScope.$broadcast('$cssAdd', stylesheets, $rootScope.stylesheets);
};
/**
* Remove: removes stylesheets from scope
**/
$css.remove = function (stylesheets, callback) {
if (!stylesheets) {
if(DEBUG) $log.error('No stylesheets provided');
return;
}
if (!angular.isArray(stylesheets)) {
stylesheets = [stylesheets];
}
// Only proceed based on persist setting
stylesheets = $filter('filter')(stylesheets, function (stylesheet) {
return !stylesheet.persist;
});
angular.forEach(stylesheets, function(stylesheet) {
stylesheet = parse(stylesheet);
// Get index of current item to be removed based on href
var index = $rootScope.stylesheets.indexOf($filter('filter')($rootScope.stylesheets, {
href: stylesheet.href
})[0]);
// Remove stylesheet from scope (if found)
if (index !== -1) {
$rootScope.stylesheets.splice(index, 1);
}
// Remove stylesheet via media query
removeViaMediaQuery(stylesheet);
if(DEBUG) $log.debug('$css.remove(): ' + stylesheet.href);
});
// Broadcasts custom event for css remove
$rootScope.$broadcast('$cssRemove', stylesheets, $rootScope.stylesheets);
};
/**
* Remove All: removes all style tags from the DOM
**/
$css.removeAll = function () {
// Remove all stylesheets from scope
if ($rootScope && $rootScope.hasOwnProperty('stylesheets')) {
$rootScope.stylesheets.length = 0;
}
if(DEBUG) $log.debug('all stylesheets removed');
};
// Preload all stylesheets
$css.preload();
return $css;
}];
}]);
/**
* Links filter - renders the stylesheets array in html format
**/
angularCSS.filter('$cssLinks', function () {
return function (stylesheets) {
if (!stylesheets || !angular.isArray(stylesheets)) {
return stylesheets;
}
var result = '';
angular.forEach(stylesheets, function (stylesheet) {
result += '<link rel="' + stylesheet.rel + '" type="' + stylesheet.type + '" href="' + stylesheet.href + '"';
result += (stylesheet.media ? ' media="' + stylesheet.media + '"' : '');
result += '>\n\n';
});
return result;
}
});
/**
* Run - auto instantiate the $css provider by injecting it in the run phase of this module
**/
angularCSS.run(['$css', function ($css) { } ]);
/**
* AngularJS hack - This way we can get and decorate all custom directives
* in order to broadcast a custom $directiveAdd event
**/
var $directives = [];
var originalModule = angular.module;
var arraySelect = function(array, action) {
return array.reduce(
function(previous, current) {
previous.push(action(current));
return previous;
}, []);
};
var arrayExists = function(array, value) {
return array.indexOf(value) > -1;
};
angular.module = function () {
var module = originalModule.apply(this, arguments);
var originalDirective = module.directive;
module.directive = function(directiveName, directiveFactory) {
var originalDirectiveFactory = angular.isFunction(directiveFactory) ?
directiveFactory : directiveFactory[directiveFactory ? (directiveFactory.length - 1) : 0];
try {
var directive = angular.copy(originalDirectiveFactory)();
directive.directiveName = directiveName;
if (directive.hasOwnProperty('css') && !arrayExists(arraySelect($directives, function(x) {return x.ddo.directiveName}), directiveName)) {
$directives.push({ ddo: directive, handled: false });
}
} catch (e) { }
return originalDirective.apply(this, arguments);
};
var originalComponent = module.component;
module.component = function (componentName, componentObject) {
componentObject.directiveName = componentName;
if (componentObject.hasOwnProperty('css') && !arrayExists(arraySelect($directives, function(x) {return x.ddo.directiveName}), componentName)) {
$directives.push({ ddo: componentObject, handled: false });
}
return originalComponent.apply(this, arguments);
};
module.config(['$provide','$injector', function ($provide, $injector) {
angular.forEach($directives, function ($dir) {
if (!$dir.handled) {
var $directive = $dir.ddo;
var dirProvider = $directive.directiveName + 'Directive';
if ($injector.has(dirProvider)) {
$dir.handled = true;
$provide.decorator(dirProvider, ['$delegate', '$rootScope', '$timeout', function ($delegate, $rootScope, $timeout) {
var directive = $delegate[0];
var compile = directive.compile;
if (!directive.css) {
directive.css = $directive.css;
}
directive.compile = function() {
var link = compile ? compile.apply(this, arguments): false;
return function(scope) {
var linkArgs = arguments;
$timeout(function () {
if (link) {
link.apply(this, linkArgs);
}
});
$rootScope.$broadcast('$directiveAdd', directive, scope);
};
};
return $delegate;
}]);
}
}
});
}]);
return module;
};
/* End of hack */
})(angular);