forked from flobacher/SVGInjector2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsvg-injector.js
More file actions
1050 lines (879 loc) · 36.2 KB
/
svg-injector.js
File metadata and controls
1050 lines (879 loc) · 36.2 KB
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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* SVGInjector v2.0.0 - Fast, caching, dynamic inline SVG DOM injection library
* https://github.com/flobacher/SVGInjector2
* forked from:
* https://github.com/iconic/SVGInjector
*
* Copyright (c) 2015 flobacher <flo@digital-fuse.net>
* @license MIT
*
* original Copyright (c) 2014 Waybury <hello@waybury.com>
* @license MIT
*/
(function(window, document) {
'use strict';
/**
* SVGInjector
*
* Replace the given elements with their full inline SVG DOM elements.
*
* :NOTE: We are using get/setAttribute with SVG because the SVG DOM spec differs from HTML DOM and
* can return other unexpected object types when trying to directly access svg properties.
* ex: "className" returns a SVGAnimatedString with the class value found in the "baseVal" property,
* instead of simple string like with HTML Elements.
*/
var SVGInjector = (function () {
/**
* Constructor Function
* @param {object} options
*/
function SVGInjector (options) {
SVGInjector.instanceCounter++;
if(typeof options !== 'undefined') {
this.init(options);
}
}
// - private constants -----------------------------------------
var SVG_NS = 'http://www.w3.org/2000/svg';
var XLINK_NS = 'http://www.w3.org/1999/xlink';
var DEFAULT_SPRITE_CLASS_NAME = 'sprite';
var DEFAULT_SPRITE_CLASS_ID_NAME = DEFAULT_SPRITE_CLASS_NAME + '--';
var DEFAULT_FALLBACK_CLASS_NAMES = [DEFAULT_SPRITE_CLASS_NAME];
var DEFAULT_REMOVESTYLES_CLASS_NAME = 'icon';
// - private member vars ---------------------------------------
var svgCache;
var injections;
var requestQueue;
var ranScripts;
var config;
var env;
requestQueue = [];
// - static vars ---------------------------------------------------
SVGInjector.instanceCounter = 0;
// - public member vars ----------------------------------------
//SVGInjector.prototype.varName = {};
// - public member functions ---------------------------------------
/**
* @param {object} options
*/
SVGInjector.prototype.init = function(options) {
options = options || {};
svgCache = {};
env = {};
env.isLocal = window.location.protocol === 'file:';
env.hasSvgSupport = document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1');
injections = {
count: 0,
elements: []
};
ranScripts = {};
config = {};
// Should we run the scripts blocks found in the SVG
// 'always' - Run them every time
// 'once' - Only run scripts once for each SVG
// [false|'never'] - Ignore scripts
config.evalScripts = options.evalScripts || 'always';
// Location of fallback pngs, if desired
config.pngFallback = options.pngFallback || false;
// Only inject the part of the svg, that is specified
// as visible through the id of an SVGViewElement
// is default mode
config.onlyInjectVisiblePart = options.onlyInjectVisiblePart || true;
config.keepStylesClass = (typeof options.keepStylesClass === 'undefined') ?
'' : options.keepStylesClass;
config.spriteClassName = (typeof options.spriteClassName === 'undefined') ?
DEFAULT_SPRITE_CLASS_NAME : options.spriteClassName;
config.spriteClassIdName = (typeof options.spriteClassIdName === 'undefined') ?
DEFAULT_SPRITE_CLASS_ID_NAME : options.spriteClassIdName;
config.removeStylesClass = (typeof options.removeStylesClass === 'undefined') ?
DEFAULT_REMOVESTYLES_CLASS_NAME : options.removeStylesClass;
config.removeAllStyles = (typeof options.removeAllStyles === 'undefined') ?
false : options.removeAllStyles;
config.fallbackClassName = (typeof options.fallbackClassName === 'undefined') ?
DEFAULT_FALLBACK_CLASS_NAMES : options.fallbackClassName;
config.prefixStyleTags = (typeof options.prefixStyleTags === 'undefined') ?
true : options.prefixStyleTags;
config.spritesheetURL = (typeof options.spritesheetURL === 'undefined' || options.spritesheetURL === '') ?
false : options.spritesheetURL;
config.prefixFragIdClass = config.spriteClassIdName;
config.forceFallbacks = (typeof options.forceFallbacks === 'undefined') ?
false : options.forceFallbacks;
if(config.forceFallbacks){
env.hasSvgSupport = false;
}
replaceNoSVGClass(document.querySelector('html'), 'no-svg', env.hasSvgSupport);
if(env.hasSvgSupport && typeof options.removeStylesClass === 'undefined' ){ // user does not want to use his own custom class -> write this style tag
writeDefaultClass(config.removeStylesClass);
}
};
/**
* Inject 1+ elements
* @param {elements} Array of or single DOM element
* @param {function} onDoneCallback
* @param {function} eachCallback
*/
SVGInjector.prototype.inject = function(elements, onDoneCallback, eachCallback) {
if (elements.length !== undefined) {
var elementsLoaded = 0;
var ctx = this;
forEach.call(elements, function (element) {
ctx.injectElement(element, function (svg) {
if (eachCallback && typeof eachCallback === 'function') eachCallback(svg);
if (onDoneCallback && elements.length === ++elementsLoaded) onDoneCallback(elementsLoaded);
});
});
}
else {
if (elements) {
this.injectElement(elements, function (svg) {
if (eachCallback && typeof eachCallback === 'function') eachCallback(svg);
if (onDoneCallback) onDoneCallback(1);
elements = null;
});
}
else {
if (onDoneCallback) onDoneCallback(0);
}
}
};
/**
* Inject a single element
* @param {elements} Array of or single DOM element
* @param {function} onDoneCallback
* @param {function} eachCallback
*/
SVGInjector.prototype.injectElement = function (el, onElementInjectedCallback) {
var imgUrl, spriteId;
// console.log('inject element', el);
if (config.spritesheetURL === false || el.getAttribute('data-src') || el.getAttribute('src') ) {
// Grab the src or data-src attribute
imgUrl = el.getAttribute('data-src') || el.getAttribute('src');
}
else {
spriteId = getSpriteIdFromClass(el);
if (spriteId === '') {
console.warn('neither data-src nor spriteId class found! Nothing to inject here!');
return;
}
imgUrl = config.spritesheetURL + '#' + spriteId;
// console.log('imgURL: ' + imgUrl);
el.setAttribute('data-src', imgUrl);
}
var imgUrlSplitByFId = imgUrl.split('#');
if (imgUrlSplitByFId.length === 1) {
imgUrlSplitByFId.push('');
}
var fallbackUrl;
// We can only inject SVG
if (!(/\.svg/i).test(imgUrl)) {
onElementInjectedCallback('Attempted to inject a file with a non-svg extension: ' + imgUrl);
return;
}
if (env.hasSvgSupport) {
if (isArray(config.fallbackClassName)) {
removeFallbackClassNames(el, imgUrlSplitByFId[1], config.fallbackClassName);
}
}
else {
// If we don't have SVG support try to fall back to a png,
// either defined per-element via data-fallback or data-png,
// or globally via the pngFallback directory setting
var perElementFallback = el.getAttribute('data-fallback') || el.getAttribute('data-png');
// Per-element specific PNG fallback defined, so use that
if (perElementFallback) {
el.setAttribute('src', perElementFallback);
onElementInjectedCallback(null);
}
// Global PNG fallback directory defined, use the same-named PNG
else if (config.pngFallback) {
if (imgUrlSplitByFId.length > 1) {
fallbackUrl = imgUrlSplitByFId[1] + '.png';
}
else {
fallbackUrl = imgUrl.split('/').pop().replace('.svg', '.png');
}
if (isArray(config.fallbackClassName)) {
setFallbackClassNames(el, imgUrlSplitByFId[1], config.fallbackClassName);
}
else if (isFunction(config.fallbackClassName)) {
console.info('custom function to create fallbackClassName');
config.fallbackClassName(el, imgUrlSplitByFId[1]);
}
else if (typeof config.fallbackClassName === 'string') {
svgElemSetClassName(el, config.fallbackClassName);
}
else {
el.setAttribute('src', config.pngFallback + '/' + fallbackUrl);
}
onElementInjectedCallback(null);
}
// um...
else {
onElementInjectedCallback('This browser does not support SVG and no PNG fallback was defined.');
}
return;
}
// Make sure we aren't already in the process of injecting this element to
// avoid a race condition if multiple injections for the same element are run.
// :NOTE: Using indexOf() only _after_ we check for SVG support and bail,
// so no need for IE8 indexOf() polyfill
if (injections.elements.indexOf(el) !== -1) {
console.warn('race', el);
return;
}
// Remember the request to inject this element, in case other injection
// calls are also trying to replace this element before we finish
injections.elements.push(el);
// Try to avoid loading the orginal image src if possible.
el.setAttribute('src', '');
// Load it up
loadSvg(onElementInjectedCallback, imgUrl, el);
};
SVGInjector.prototype.getEnv = function() {
return env;
};
// - private member functions -----------------------------------------------
var setFallbackClassNames = function (element, symbolId, classNames) {
var className = (typeof classNames === 'undefined') ? DEFAULT_FALLBACK_CLASS_NAMES : classNames.slice(0);
// replace %s by symbolId
forEach.call(
className,
function(curClassName, idx) {
className[idx] = curClassName.replace('%s', symbolId);
}
);
svgElemSetClassName(element, className);
};
var removeFallbackClassNames = function (element, symbolId, fallbackClassNames) {
fallbackClassNames = (typeof fallbackClassNames === 'undefined') ? DEFAULT_FALLBACK_CLASS_NAMES.slice(0) : fallbackClassNames.slice(0);
var idxOfCurClass,
curClassNames,
classAttribute = element.getAttribute('class');
if (typeof classAttribute === 'undefined' || classAttribute === null) {
return;
}
curClassNames = classAttribute.split(' ');
if (curClassNames) {
// replace %s by symbolId
forEach.call(
fallbackClassNames,
function(curFallbackClassName) {
curFallbackClassName = curFallbackClassName.replace('%s', symbolId);
idxOfCurClass = curClassNames.indexOf(curFallbackClassName);
if( idxOfCurClass >= 0 ){
// console.log('remove class ' + curClassName);
curClassNames[idxOfCurClass] = '';
}
}
);
element.setAttribute('class', uniqueClasses(curClassNames.join(' ')));
}
};
var suffixIdReferences = function (svg, suffix) {
var defs = [
{def:'linearGradient', attrs: ['fill', 'stroke']},
{def:'radialGradient', attrs: ['fill', 'stroke']},
{def:'clipPath', attrs: ['clip-path']},
{def:'mask', attrs: ['mask']},
{def:'filter', attrs: ['filter']},
{def:'color-profile', attrs: ['color-profile']},
{def:'cursor', attrs: ['cursor']},
{def:'marker', attrs: ['marker', 'marker-start', 'marker-mid', 'marker-end']}
];
var newName,
definitions,
defLen,
defIdx,
refrences,
refLen,
refIdx,
attrs,
attrLen,
attrIdx,
allLinks,
allLinksLen,
allLinksIdx,
links,
linkLen,
linkIdx
;
forEach.call(defs, function(elem) {
definitions = svg.querySelectorAll(elem.def + '[id]');
for (defIdx = 0, defLen = definitions.length; defIdx < defLen; defIdx++) {
newName = definitions[defIdx].id + '-' + suffix;
attrs = elem.attrs;
for (attrIdx = 0, attrLen = attrs.length; attrIdx < attrLen; attrIdx++) {
// console.log('suffixxed ' + attribute + ': ' + newName);
// :NOTE: using a substring match attr selector here to deal with IE "adding extra quotes in url() attrs"
refrences = svg.querySelectorAll('[' + attrs[attrIdx] + '="url(#' + definitions[defIdx].id + ')"]');
for (refIdx = 0, refLen = refrences.length; refIdx < refLen; refIdx++) {
// console.log('set url', newName);
refrences[refIdx].setAttribute(attrs[attrIdx], 'url(#' + newName + ')');
}
}
// handle xlink:refrences
// :NOTE: IE does not like the easy way: links = svg.querySelectorAll('[*|href="#' + definitions[defIdx].id + '"]');
allLinks = svg.querySelectorAll('[*|href]');
links = [];
for (allLinksIdx = 0, allLinksLen = allLinks.length; allLinksIdx < allLinksLen; allLinksIdx++) {
if (allLinks[allLinksIdx].getAttributeNS(XLINK_NS, 'href').toString() === '#' + definitions[defIdx].id ) {
links.push(allLinks[allLinksIdx]);
}
}
for (linkIdx = 0, linkLen = links.length; linkIdx < linkLen; linkIdx++) {
links[linkIdx].setAttributeNS(XLINK_NS, 'href', '#' + newName);
// console.log('set link', newName, links[linkIdx]);
}
definitions[defIdx].id = newName;
}
});
};
var copyAttributes = function (svgElemSource, svgElemTarget, attributesToIgnore) {
var curAttr;
if (typeof attributesToIgnore === 'undefined') { attributesToIgnore = ['id', 'viewBox']; }
for(var i=0; i<svgElemSource.attributes.length; i++) {
curAttr = svgElemSource.attributes.item(i);
if (attributesToIgnore.indexOf(curAttr.name) < 0) {
svgElemTarget.setAttribute(curAttr.name, curAttr.value);
}
}
};
var cloneSymbolAsSVG = function (svgSymbol) {
var svg = document.createElementNS(SVG_NS, 'svg');
forEach.call(svgSymbol.childNodes, function(child){
svg.appendChild(child.cloneNode(true));
});
copyAttributes(svgSymbol, svg);
return svg;
};
var doPrefixStyleTags = function (styleTag, injectCount, svg){
var srcArr = svg.getAttribute('data-src').split('#');
var regex,
origPrefixClassName,
newPrefixClassName,
srcFileNameArr,
regexSearchResult,
styleTagContent = styleTag.textContent,
newContent = '',
selectorArr,
prefixSelector = function(elem, idx, arr){
arr[idx] = '.' + newPrefixClassName + ' ' + elem;
};
if(srcArr.length > 1) {
origPrefixClassName = srcArr[1];
newPrefixClassName = origPrefixClassName + '-' + injectCount;
regex = new RegExp('\\.' + origPrefixClassName + ' ', 'g');
styleTag.textContent = styleTagContent.replace(regex, '.' + newPrefixClassName + ' ');
}
else { //inject a single element.. this has most probaly not gone through preprocessing
srcFileNameArr = srcArr[0].split('/');
newPrefixClassName = srcFileNameArr[srcFileNameArr.length-1].replace('.svg', '') + '-' + injectCount;
console.info('inject complete file: ' + srcArr[0]);
//https://medium.com/jotform-form-builder/writing-a-css-parser-in-javascript-3ecaa1719a43
regex = new RegExp('([\\s\\S]*?){([\\s\\S]*?)}', 'g');
while ((regexSearchResult = regex.exec(styleTagContent)) !== null) {
selectorArr = regexSearchResult[1].trim().split(', ');
selectorArr.forEach(prefixSelector);
var tmp = selectorArr.join(', ') + '{' + regexSearchResult[2] + '}';
// console.log(tmp);
newContent += tmp;
}
styleTag.textContent = newContent;
}
svg.setAttribute('class', (svg.getAttribute('class') + ' ' + newPrefixClassName));
};
var getClassList = function (svgToCheck) {
var curClassAttr = svgToCheck.getAttribute('class');
return (curClassAttr) ? curClassAttr.trim().split(' ') : [];
};
var getSpriteIdFromClass = function (element) {
var classes = getClassList(element);
var id = '';
forEach.call(classes, function (curClass) {
if(curClass.indexOf(config.spriteClassIdName) >= 0) {
id = curClass.replace(config.spriteClassIdName, '');
// console.log('class with prefix ' + config.spriteClassIdName + ' found. id: ' + id);
}
});
return id;
};
var cloneSvg = function (config, sourceSvg, fragId) {
var svgElem,
newSVG,
viewBox,
viewBoxAttr,
symbolAttributesToFind,
curClassList,
setViewboxOnNewSVG = false,
symbolElem = null;
if(fragId === undefined){
return sourceSvg.cloneNode(true);
}
else {
svgElem = sourceSvg.getElementById(fragId);
if(!svgElem){
console.warn(fragId + ' not found in svg', sourceSvg);
return;
}
viewBoxAttr = svgElem.getAttribute('viewBox');
viewBox = viewBoxAttr.split(' ');
if (svgElem instanceof SVGSymbolElement) {
newSVG = cloneSymbolAsSVG(svgElem);
setViewboxOnNewSVG = true;
}
else if (svgElem instanceof SVGViewElement) {
symbolElem = null;
if (config.onlyInjectVisiblePart) {
var selector = '*[width="' + viewBox[2] + '"][height="'+viewBox[3]+'"]';
symbolAttributesToFind = {};
if (Math.abs(parseInt(viewBox[0])) === 0) {
selector += ':not([x])';
}
else {
symbolAttributesToFind.x = viewBox[0];
selector += '[x="' + viewBox[0] + '"]';
}
if (Math.abs(parseInt(viewBox[1])) === 0) {
selector += ':not([y])';
}
else {
symbolAttributesToFind.y = viewBox[1];
selector += '[y="' + viewBox[1] + '"]';
}
var symobolList = sourceSvg.querySelectorAll(selector);
if (symobolList.length > 1) {
console.warn('more than one item, with the matching viewbox found!', symobolList);
}
symbolElem = symobolList[0];
}
if (symbolElem && (symbolElem instanceof SVGSVGElement)) {
newSVG = symbolElem.cloneNode(true);
for (var prop in symbolAttributesToFind) {
if (prop !== 'width' && prop !== 'height') {
newSVG.removeAttribute(prop);
}
}
}
else if(symbolElem && (symbolElem instanceof SVGUseElement)) {
// console.log('referenced view shows a SVGUseElement');
var referencedSymbol = sourceSvg.getElementById(
symbolElem.getAttributeNS(XLINK_NS, 'href').substr(1)
);
newSVG = cloneSymbolAsSVG(referencedSymbol);
viewBoxAttr = referencedSymbol.getAttribute('viewBox');
viewBox = viewBoxAttr.split(' ');
setViewboxOnNewSVG = true;
}
else {
console.info(
((config.onlyInjectVisiblePart) ? 'symbol referenced via view' + fragId + ' not found' : 'option.onlyInjectVisiblePart: false') + ' -> clone complete svg!'
);
setViewboxOnNewSVG = true;
newSVG = sourceSvg.cloneNode(true);
}
}
if (setViewboxOnNewSVG) {
newSVG.setAttribute('viewBox', viewBox.join(' '));
newSVG.setAttribute('width', viewBox[2]+'px');
newSVG.setAttribute('height', viewBox[3]+'px');
}
newSVG.setAttribute('xmlns', SVG_NS);
newSVG.setAttribute('xmlns:xlink', XLINK_NS);
//curClassAttr = newSVG.getAttribute('class');
curClassList = getClassList(newSVG);
var fragIdClassName = config.prefixFragIdClass + fragId;
if (curClassList.indexOf(fragIdClassName)<0) {
curClassList.push(fragIdClassName);
newSVG.setAttribute('class', curClassList.join(' '));
}
return newSVG;
}
};
//queueRequest(requestQueue, fileName, fragId, onElementInjectedCallback, el);
var queueRequest = function (fileName, fragId, callback, el) {
requestQueue[fileName] = requestQueue[fileName] || [];
requestQueue[fileName].push({callback:callback, fragmentId:fragId, element:el});
};
var processRequestQueue = function (url) {
var requestQueueElem;
for (var i = 0, len = requestQueue[url].length; i < len; i++) {
// Make these calls async so we avoid blocking the page/renderer
/* jshint loopfunc: true */
(function (index) {
setTimeout(function () {
requestQueueElem = requestQueue[url][index];
onLoadSVG(url, requestQueueElem.fragmentId, requestQueueElem.callback, requestQueueElem.element);
}, 0);
})(i);
/* jshint loopfunc: false */
}
};
var loadSvg = function (onElementInjectedCallback, url, el) {
var urlArr, fileName, fragId;
//var state = {onElementInjectedCallback:onElementInjectedCallback, injections:injections, config:config, url:url, el:el, ranScripts:ranScripts};
// console.log('loadSvg', url);
urlArr = url.split('#');
fileName = urlArr[0];
fragId = (urlArr.length === 2) ? urlArr[1] : undefined;
if (svgCache[fileName] !== undefined) {
if (svgCache[fileName] instanceof SVGSVGElement) {
// We already have it in cache, so use it
// console.log('We already have it in cache, so use it', fileName, fragId);
onLoadSVG(fileName, fragId, onElementInjectedCallback, el);
}
else {
// console.log('We don\'t have it in cache yet, but we are loading it, so queue this request', fileName, fragId);
// We don't have it in cache yet, but we are loading it, so queue this request
queueRequest(fileName, fragId, onElementInjectedCallback, el);
}
}
else {
if (!window.XMLHttpRequest) {
onElementInjectedCallback('Browser does not support XMLHttpRequest');
return false;
}
// Seed the cache to indicate we are loading this URL already
svgCache[fileName] = {};
queueRequest(fileName, fragId, onElementInjectedCallback, el);
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function () {
// readyState 4 = complete
if (httpRequest.readyState === 4) {
// Handle status
if (httpRequest.status === 404 || httpRequest.responseXML === null) {
onElementInjectedCallback('Unable to load SVG file: ' + fileName);
// @check this!
//if (env.isLocal) {
// onLoadCompleteCb('Note: SVG injection ajax calls do not work locally without adjusting security setting in your browser. Or consider using a local webserver.');
//}
//
//onLoadCompleteCb();
return false;
}
// 200 success from server, or 0 when using file:// protocol locally
if (httpRequest.status === 200 || (env.isLocal && httpRequest.status === 0)) {
if (httpRequest.responseXML instanceof Document) {
// Cache it
svgCache[fileName] = httpRequest.responseXML.documentElement;
}
// IE9 doesn't create a responseXML Document object from loaded SVG,
// and throws a "DOM Exception: HIERARCHY_REQUEST_ERR (3)" error when injected.
//
// So, we'll just create our own manually via the DOMParser using
// the the raw XML responseText.
//
// :NOTE: IE8 and older doesn't have DOMParser, but they can't do SVG either, so...
else if (DOMParser && (DOMParser instanceof Function)) {
var xmlDoc;
try {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(httpRequest.responseText, 'text/xml');
}
catch (e) {
xmlDoc = undefined;
}
if (!xmlDoc || xmlDoc.getElementsByTagName('parsererror').length) {
onElementInjectedCallback('Unable to parse SVG file: ' + url);
return false;
}
else {
// Cache it
svgCache[fileName] = xmlDoc.documentElement;
}
}
// We've loaded a new asset, so process any requests waiting for it
processRequestQueue(fileName);
}
else {
onElementInjectedCallback('There was a problem injecting the SVG: ' + httpRequest.status + ' ' + httpRequest.statusText);
return false;
}
}
};
httpRequest.open('GET', fileName);
// Treat and parse the response as XML, even if the
// server sends us a different mimetype>
if (httpRequest.overrideMimeType) httpRequest.overrideMimeType('text/xml');
httpRequest.send();
}
};
var writeDefaultClass = function(removeStylesClass) {
var css = 'svg.' + removeStylesClass + ' {fill: currentColor;}',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
}
else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
console.info( 'default class written: ', css );
};
var replaceNoSVGClass = function(element, noSVGClassName, hasSvgSupport) {
if(hasSvgSupport) {
element.className.replace(noSVGClassName, '');
}
else{
element.className += ' ' + noSVGClassName;
}
};
var onLoadSVG = function(url, fragmentId, onElementInjectedCallback, el){
// console.log('onLoadSVG', url, fragmentId, onElementInjectedCallback, el);
var svg,
imgId,
titleId,
descId
;
svg = cloneSvg(config, svgCache[url], fragmentId);
if (typeof svg === 'undefined' || typeof svg === 'string') {
onElementInjectedCallback(svg);
return false;
}
imgId = el.getAttribute('id');
if (imgId) {
svg.setAttribute('id', imgId);
}
// take care of accessibility
svg.setAttribute('role', 'img');
forEach.call(svg.children, function (curChildElem) {
if (!(curChildElem instanceof SVGDefsElement)) {
curChildElem.setAttribute('role', 'presentation');
}
});
// set desc + title
descId = setRootLevelElem('desc', svg, el, fragmentId);
titleId = setRootLevelElem('title', svg, el, fragmentId);
svg.setAttribute('aria-labelledby', titleId + ' ' + descId);
// Concat the SVG classes + 'injected-svg' + the img classes
var classMerge = [].concat(svg.getAttribute('class') || [], 'injected-svg', el.getAttribute('class') || []).join(' ');
svg.setAttribute('class', uniqueClasses(classMerge));
var imgStyle = el.getAttribute('style');
if (imgStyle) {
svg.setAttribute('style', imgStyle);
}
// Copy all the data elements to the svg
var imgData = [].filter.call(el.attributes, function (at) {
return (/^data-\w[\w\-]*$/).test(at.name);
});
forEach.call(imgData, function (dataAttr) {
if (dataAttr.name && dataAttr.value) {
svg.setAttribute(dataAttr.name, dataAttr.value);
}
});
// Copy preserveAspectRatio of elem if exists
var presARAttr = el.getAttribute('preserveAspectRatio');
if(presARAttr){
svg.setAttribute('preserveAspectRatio', presARAttr);
}
// Make sure any internally referenced ids and their
// references are unique.
//
// This addresses the issue of having multiple instances of the
// same SVG on a page and only the first clipPath, gradient, mask or filter id is referenced.
suffixIdReferences(svg, injections.count);
// Remove any unwanted/invalid namespaces that might have been added by SVG editing tools
svg.removeAttribute('xmlns:a');
// Post page load injected SVGs don't automatically have their script
// elements run, so we'll need to make that happen, if requested
// Find then prune the scripts
var scripts = svg.querySelectorAll('script');
var scriptsToEval = [];
var script, scriptType;
for (var k = 0, scriptsLen = scripts.length; k < scriptsLen; k++) {
scriptType = scripts[k].getAttribute('type');
// Only process javascript types.
// SVG defaults to 'application/ecmascript' for unset types
if (!scriptType || scriptType === 'application/ecmascript' || scriptType === 'application/javascript') {
// innerText for IE, textContent for other browsers
script = scripts[k].innerText || scripts[k].textContent;
// Stash
scriptsToEval.push(script);
// Tidy up and remove the script element since we don't need it anymore
svg.removeChild(scripts[k]);
}
}
// Run/Eval the scripts if needed
if (scriptsToEval.length > 0 && (config.evalScripts === 'always' || (config.evalScripts === 'once' && ! ranScripts[url]))) {
for (var l = 0, scriptsToEvalLen = scriptsToEval.length; l < scriptsToEvalLen; l++) {
// :NOTE: Yup, this is a form of eval, but it is being used to eval code
// the caller has explictely asked to be loaded, and the code is in a caller
// defined SVG file... not raw user input.
//
// Also, the code is evaluated in a closure and not in the global scope.
// If you need to put something in global scope, use 'window'
new Function(scriptsToEval[l])(window); // jshint ignore:line
}
// Remember we already ran scripts for this svg
ranScripts[url] = true;
}
// :NOTE: handle styles in style-tags
var styleTags = svg.querySelectorAll('style');
forEach.call(styleTags, function (styleTag) {
var svgClassList = getClassList(svg);
if ((svgClassList.indexOf(config.removeStylesClass)>=0 || config.removeAllStyles) && (svgClassList.indexOf(config.keepStylesClass)<0) ) {
// remove the styletag if the removeStylesClass is applied to the SVG
// console.log('remove styleTag', styleTag);
styleTag.parentNode.removeChild(styleTag);
}
else {
if(config.prefixStyleTags){
doPrefixStyleTags(styleTag, injections.count, svg);
}
else{
// :WORKAROUND:
// IE doesn't evaluate <style> tags in SVGs that are dynamically added to the page.
// This trick will trigger IE to read and use any existing SVG <style> tags.
//
// Reference: https://github.com/iconic/SVGInjector/issues/23
styleTag.textContent += '';
}
}
});
// Replace the image with the svg
el.parentNode.replaceChild(svg, el);
// Now that we no longer need it, drop references
// to the original element so it can be GC'd
delete injections.elements[injections.elements.indexOf(el)];
//el = null;
// Increment the injected count
injections.count++;
onElementInjectedCallback(svg);
};
//- general helper functions ------------------------------------------------
//var toCamelCase = function(str) {
// return str.replace(/^([A-Z])|[-_](\w)/g, function(match, p1, p2, offset) {
// if (p2) return p2.toUpperCase();
// return p1.toLowerCase();
// });
//}
var uniqueClasses = function(list) {
list = list.split(' ');
var hash = {};
var i = list.length;
var out = [];
while (i--) {
if (!hash.hasOwnProperty(list[i])) {
hash[list[i]] = 1;
out.unshift(list[i]);
}
}
return out.join(' ');
};
var isFunction = function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
var isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
var svgElemSetClassName = function(el, newClassNames){
var curClasses = el.getAttribute('class');
curClasses = curClasses ? curClasses : '';
if(isArray(newClassNames)) {
newClassNames = newClassNames.join(' ');
}
newClassNames = curClasses + ' ' + newClassNames;
el.setAttribute('class', uniqueClasses(newClassNames));
};
/**
* cache (or polyfill for <= IE8) Array.forEach()
* source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
*/
var forEach = Array.prototype.forEach || function (fn, scope) {
if (this === void 0 || this === null || typeof fn !== 'function') {
throw new TypeError();
}
/* jshint bitwise: false */
var i, len = this.length >>> 0;
/* jshint bitwise: true */
for (i = 0; i < len; ++i) {
if (i in this) {
fn.call(scope, this[i], i, this);
}
}
};
var setRootLevelElem = function (type, svg, el, fragmentId) {
var
titleId = fragmentId + '-' + type + '-' + injections.count,
titleCandidate
;
titleCandidate = el.querySelector(type);
if (titleCandidate) {
addRootLevelElem(type, svg, titleCandidate.textContent, titleId, svg.firstChild);
} else {
titleCandidate = svg.querySelector(type);
if (titleCandidate) {
titleCandidate.setAttribute('id', titleId);
} else {
addRootLevelElem(type, svg, fragmentId, titleId, svg.firstChild);
}
}
return titleId;
};
var addRootLevelElem = function (type, svg, text, id, insertBefore) {
var existingElem = svg.querySelector(type);
if (existingElem) {
existingElem.parentNode.removeChild(existingElem);
}
var newElem = document.createElementNS(SVG_NS, type);
newElem.appendChild(document.createTextNode(text));
newElem.setAttributeNS(SVG_NS,'id', id);
svg.insertBefore(newElem, insertBefore);
return newElem;
};
return SVGInjector;
})();
if (typeof angular === 'object') {
// use with angular
angular
.module('svginjector', [])
.provider('svgInjectorOptions', function() {