UNPKG

27.3 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('prop-types'), require('react')) :
3 typeof define === 'function' && define.amd ? define(['exports', 'prop-types', 'react'], factory) :
4 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactSVG = {}, global.PropTypes, global.React));
5})(this, (function (exports, PropTypes, React) { 'use strict';
6
7 function _interopNamespace(e) {
8 if (e && e.__esModule) return e;
9 var n = Object.create(null);
10 if (e) {
11 Object.keys(e).forEach(function (k) {
12 if (k !== 'default') {
13 var d = Object.getOwnPropertyDescriptor(e, k);
14 Object.defineProperty(n, k, d.get ? d : {
15 enumerable: true,
16 get: function () { return e[k]; }
17 });
18 }
19 });
20 }
21 n["default"] = e;
22 return Object.freeze(n);
23 }
24
25 var PropTypes__namespace = /*#__PURE__*/_interopNamespace(PropTypes);
26 var React__namespace = /*#__PURE__*/_interopNamespace(React);
27
28 function unwrapExports (x) {
29 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
30 }
31
32 function createCommonjsModule(fn, module) {
33 return module = { exports: {} }, fn(module, module.exports), module.exports;
34 }
35
36 var _extends_1 = createCommonjsModule(function (module) {
37 function _extends() {
38 module.exports = _extends = Object.assign || function (target) {
39 for (var i = 1; i < arguments.length; i++) {
40 var source = arguments[i];
41
42 for (var key in source) {
43 if (Object.prototype.hasOwnProperty.call(source, key)) {
44 target[key] = source[key];
45 }
46 }
47 }
48
49 return target;
50 }, module.exports.__esModule = true, module.exports["default"] = module.exports;
51 return _extends.apply(this, arguments);
52 }
53
54 module.exports = _extends, module.exports.__esModule = true, module.exports["default"] = module.exports;
55 });
56
57 var _extends = unwrapExports(_extends_1);
58
59 var objectWithoutPropertiesLoose = createCommonjsModule(function (module) {
60 function _objectWithoutPropertiesLoose(source, excluded) {
61 if (source == null) return {};
62 var target = {};
63 var sourceKeys = Object.keys(source);
64 var key, i;
65
66 for (i = 0; i < sourceKeys.length; i++) {
67 key = sourceKeys[i];
68 if (excluded.indexOf(key) >= 0) continue;
69 target[key] = source[key];
70 }
71
72 return target;
73 }
74
75 module.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
76 });
77
78 var _objectWithoutPropertiesLoose = unwrapExports(objectWithoutPropertiesLoose);
79
80 var setPrototypeOf = createCommonjsModule(function (module) {
81 function _setPrototypeOf(o, p) {
82 module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
83 o.__proto__ = p;
84 return o;
85 }, module.exports.__esModule = true, module.exports["default"] = module.exports;
86 return _setPrototypeOf(o, p);
87 }
88
89 module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
90 });
91
92 unwrapExports(setPrototypeOf);
93
94 var inheritsLoose = createCommonjsModule(function (module) {
95 function _inheritsLoose(subClass, superClass) {
96 subClass.prototype = Object.create(superClass.prototype);
97 subClass.prototype.constructor = subClass;
98 setPrototypeOf(subClass, superClass);
99 }
100
101 module.exports = _inheritsLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
102 });
103
104 var _inheritsLoose = unwrapExports(inheritsLoose);
105
106 /*! *****************************************************************************
107 Copyright (c) Microsoft Corporation.
108
109 Permission to use, copy, modify, and/or distribute this software for any
110 purpose with or without fee is hereby granted.
111
112 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
113 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
114 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
115 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
116 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
117 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
118 PERFORMANCE OF THIS SOFTWARE.
119 ***************************************************************************** */
120
121 function __spreadArray(to, from, pack) {
122 if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
123 if (ar || !(i in from)) {
124 if (!ar) ar = Array.prototype.slice.call(from, 0, i);
125 ar[i] = from[i];
126 }
127 }
128 return to.concat(ar || Array.prototype.slice.call(from));
129 }
130
131 /*!
132 * content-type
133 * Copyright(c) 2015 Douglas Christopher Wilson
134 * MIT Licensed
135 */
136
137 /**
138 * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
139 *
140 * parameter = token "=" ( token / quoted-string )
141 * token = 1*tchar
142 * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
143 * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
144 * / DIGIT / ALPHA
145 * ; any VCHAR, except delimiters
146 * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
147 * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
148 * obs-text = %x80-FF
149 * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
150 */
151 var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g;
152
153 /**
154 * RegExp to match quoted-pair in RFC 7230 sec 3.2.6
155 *
156 * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
157 * obs-text = %x80-FF
158 */
159 var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g;
160
161 /**
162 * RegExp to match type in RFC 7231 sec 3.1.1.1
163 *
164 * media-type = type "/" subtype
165 * type = token
166 * subtype = token
167 */
168 var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
169 var parse_1 = parse;
170
171 /**
172 * Parse media type to object.
173 *
174 * @param {string|object} string
175 * @return {Object}
176 * @public
177 */
178
179 function parse (string) {
180 if (!string) {
181 throw new TypeError('argument string is required')
182 }
183
184 // support req/res-like objects as argument
185 var header = typeof string === 'object'
186 ? getcontenttype(string)
187 : string;
188
189 if (typeof header !== 'string') {
190 throw new TypeError('argument string is required to be a string')
191 }
192
193 var index = header.indexOf(';');
194 var type = index !== -1
195 ? header.substr(0, index).trim()
196 : header.trim();
197
198 if (!TYPE_REGEXP.test(type)) {
199 throw new TypeError('invalid media type')
200 }
201
202 var obj = new ContentType(type.toLowerCase());
203
204 // parse parameters
205 if (index !== -1) {
206 var key;
207 var match;
208 var value;
209
210 PARAM_REGEXP.lastIndex = index;
211
212 while ((match = PARAM_REGEXP.exec(header))) {
213 if (match.index !== index) {
214 throw new TypeError('invalid parameter format')
215 }
216
217 index += match[0].length;
218 key = match[1].toLowerCase();
219 value = match[2];
220
221 if (value[0] === '"') {
222 // remove quotes and escapes
223 value = value
224 .substr(1, value.length - 2)
225 .replace(QESC_REGEXP, '$1');
226 }
227
228 obj.parameters[key] = value;
229 }
230
231 if (index !== header.length) {
232 throw new TypeError('invalid parameter format')
233 }
234 }
235
236 return obj
237 }
238
239 /**
240 * Get content-type from req/res objects.
241 *
242 * @param {object}
243 * @return {Object}
244 * @private
245 */
246
247 function getcontenttype (obj) {
248 var header;
249
250 if (typeof obj.getHeader === 'function') {
251 // res-like
252 header = obj.getHeader('content-type');
253 } else if (typeof obj.headers === 'object') {
254 // req-like
255 header = obj.headers && obj.headers['content-type'];
256 }
257
258 if (typeof header !== 'string') {
259 throw new TypeError('content-type header is missing from object')
260 }
261
262 return header
263 }
264
265 /**
266 * Class to represent a content type.
267 * @private
268 */
269 function ContentType (type) {
270 this.parameters = Object.create(null);
271 this.type = type;
272 }
273
274 var cache = new Map();
275
276 var cloneSvg = function cloneSvg(sourceSvg) {
277 return sourceSvg.cloneNode(true);
278 };
279
280 var isLocal = function isLocal() {
281 return window.location.protocol === 'file:';
282 };
283
284 var makeAjaxRequest = function makeAjaxRequest(url, httpRequestWithCredentials, callback) {
285 var httpRequest = new XMLHttpRequest();
286
287 httpRequest.onreadystatechange = function () {
288 try {
289 if (!/\.svg/i.test(url) && httpRequest.readyState === 2) {
290 var contentType = httpRequest.getResponseHeader('Content-Type');
291
292 if (!contentType) {
293 throw new Error('Content type not found');
294 }
295
296 var type = parse_1(contentType).type;
297
298 if (!(type === 'image/svg+xml' || type === 'text/plain')) {
299 throw new Error("Invalid content type: ".concat(type));
300 }
301 }
302
303 if (httpRequest.readyState === 4) {
304 if (httpRequest.status === 404 || httpRequest.responseXML === null) {
305 throw new Error(isLocal() ? 'Note: SVG injection ajax calls do not work locally without ' + 'adjusting security settings in your browser. Or consider ' + 'using a local webserver.' : 'Unable to load SVG file: ' + url);
306 }
307
308 if (httpRequest.status === 200 || isLocal() && httpRequest.status === 0) {
309 callback(null, httpRequest);
310 } else {
311 throw new Error('There was a problem injecting the SVG: ' + httpRequest.status + ' ' + httpRequest.statusText);
312 }
313 }
314 } catch (error) {
315 httpRequest.abort();
316
317 if (error instanceof Error) {
318 callback(error, httpRequest);
319 } else {
320 throw error;
321 }
322 }
323 };
324
325 httpRequest.open('GET', url);
326 httpRequest.withCredentials = httpRequestWithCredentials;
327
328 if (httpRequest.overrideMimeType) {
329 httpRequest.overrideMimeType('text/xml');
330 }
331
332 httpRequest.send();
333 };
334
335 var requestQueue = {};
336 var queueRequest = function queueRequest(url, callback) {
337 requestQueue[url] = requestQueue[url] || [];
338 requestQueue[url].push(callback);
339 };
340 var processRequestQueue = function processRequestQueue(url) {
341 var _loop_1 = function _loop_1(i, len) {
342 setTimeout(function () {
343 if (Array.isArray(requestQueue[url])) {
344 var cacheValue = cache.get(url);
345 var callback = requestQueue[url][i];
346
347 if (cacheValue instanceof SVGSVGElement) {
348 callback(null, cloneSvg(cacheValue));
349 }
350
351 if (cacheValue instanceof Error) {
352 callback(cacheValue);
353 }
354
355 if (i === requestQueue[url].length - 1) {
356 delete requestQueue[url];
357 }
358 }
359 }, 0);
360 };
361
362 for (var i = 0, len = requestQueue[url].length; i < len; i++) {
363 _loop_1(i);
364 }
365 };
366
367 var loadSvgCached = function loadSvgCached(url, httpRequestWithCredentials, callback) {
368 if (cache.has(url)) {
369 var cacheValue = cache.get(url);
370
371 if (cacheValue === undefined) {
372 queueRequest(url, callback);
373 return;
374 }
375
376 if (cacheValue instanceof SVGSVGElement) {
377 callback(null, cloneSvg(cacheValue));
378 return;
379 }
380 }
381
382 cache.set(url, undefined);
383 queueRequest(url, callback);
384 makeAjaxRequest(url, httpRequestWithCredentials, function (error, httpRequest) {
385 if (error) {
386 cache.set(url, error);
387 } else if (httpRequest.responseXML instanceof Document && httpRequest.responseXML.documentElement && httpRequest.responseXML.documentElement instanceof SVGSVGElement) {
388 cache.set(url, httpRequest.responseXML.documentElement);
389 }
390
391 processRequestQueue(url);
392 });
393 };
394
395 var loadSvgUncached = function loadSvgUncached(url, httpRequestWithCredentials, callback) {
396 makeAjaxRequest(url, httpRequestWithCredentials, function (error, httpRequest) {
397 if (error) {
398 callback(error);
399 } else if (httpRequest.responseXML instanceof Document && httpRequest.responseXML.documentElement && httpRequest.responseXML.documentElement instanceof SVGSVGElement) {
400 callback(null, httpRequest.responseXML.documentElement);
401 }
402 });
403 };
404
405 var idCounter = 0;
406
407 var uniqueId = function uniqueId() {
408 return ++idCounter;
409 };
410
411 var injectedElements = [];
412 var ranScripts = {};
413 var svgNamespace$1 = 'http://www.w3.org/2000/svg';
414 var xlinkNamespace$1 = 'http://www.w3.org/1999/xlink';
415
416 var injectElement = function injectElement(el, evalScripts, renumerateIRIElements, cacheRequests, httpRequestWithCredentials, beforeEach, callback) {
417 var elUrl = el.getAttribute('data-src') || el.getAttribute('src');
418
419 if (!elUrl) {
420 callback(new Error('Invalid data-src or src attribute'));
421 return;
422 }
423
424 if (injectedElements.indexOf(el) !== -1) {
425 injectedElements.splice(injectedElements.indexOf(el), 1);
426 el = null;
427 return;
428 }
429
430 injectedElements.push(el);
431 el.setAttribute('src', '');
432 var loadSvg = cacheRequests ? loadSvgCached : loadSvgUncached;
433 loadSvg(elUrl, httpRequestWithCredentials, function (error, svg) {
434 if (!svg) {
435 injectedElements.splice(injectedElements.indexOf(el), 1);
436 el = null;
437 callback(error);
438 return;
439 }
440
441 var elId = el.getAttribute('id');
442
443 if (elId) {
444 svg.setAttribute('id', elId);
445 }
446
447 var elTitle = el.getAttribute('title');
448
449 if (elTitle) {
450 svg.setAttribute('title', elTitle);
451 }
452
453 var elWidth = el.getAttribute('width');
454
455 if (elWidth) {
456 svg.setAttribute('width', elWidth);
457 }
458
459 var elHeight = el.getAttribute('height');
460
461 if (elHeight) {
462 svg.setAttribute('height', elHeight);
463 }
464
465 var mergedClasses = Array.from(new Set(__spreadArray(__spreadArray(__spreadArray([], (svg.getAttribute('class') || '').split(' '), true), ['injected-svg'], false), (el.getAttribute('class') || '').split(' '), true))).join(' ').trim();
466 svg.setAttribute('class', mergedClasses);
467 var elStyle = el.getAttribute('style');
468
469 if (elStyle) {
470 svg.setAttribute('style', elStyle);
471 }
472
473 svg.setAttribute('data-src', elUrl);
474 var elData = [].filter.call(el.attributes, function (at) {
475 return /^data-\w[\w-]*$/.test(at.name);
476 });
477 Array.prototype.forEach.call(elData, function (dataAttr) {
478 if (dataAttr.name && dataAttr.value) {
479 svg.setAttribute(dataAttr.name, dataAttr.value);
480 }
481 });
482
483 if (renumerateIRIElements) {
484 var iriElementsAndProperties_1 = {
485 clipPath: ['clip-path'],
486 'color-profile': ['color-profile'],
487 cursor: ['cursor'],
488 filter: ['filter'],
489 linearGradient: ['fill', 'stroke'],
490 marker: ['marker', 'marker-start', 'marker-mid', 'marker-end'],
491 mask: ['mask'],
492 path: [],
493 pattern: ['fill', 'stroke'],
494 radialGradient: ['fill', 'stroke']
495 };
496 var element_1;
497 var elements_1;
498 var properties_1;
499 var currentId_1;
500 var newId_1;
501 Object.keys(iriElementsAndProperties_1).forEach(function (key) {
502 element_1 = key;
503 properties_1 = iriElementsAndProperties_1[key];
504 elements_1 = svg.querySelectorAll(element_1 + '[id]');
505
506 var _loop_1 = function _loop_1(a, elementsLen) {
507 currentId_1 = elements_1[a].id;
508 newId_1 = currentId_1 + '-' + uniqueId();
509 var referencingElements;
510 Array.prototype.forEach.call(properties_1, function (property) {
511 referencingElements = svg.querySelectorAll('[' + property + '*="' + currentId_1 + '"]');
512
513 for (var b = 0, referencingElementLen = referencingElements.length; b < referencingElementLen; b++) {
514 var attrValue = referencingElements[b].getAttribute(property);
515
516 if (attrValue && !attrValue.match(new RegExp('url\\("?#' + currentId_1 + '"?\\)'))) {
517 continue;
518 }
519
520 referencingElements[b].setAttribute(property, 'url(#' + newId_1 + ')');
521 }
522 });
523 var allLinks = svg.querySelectorAll('[*|href]');
524 var links = [];
525
526 for (var c = 0, allLinksLen = allLinks.length; c < allLinksLen; c++) {
527 var href = allLinks[c].getAttributeNS(xlinkNamespace$1, 'href');
528
529 if (href && href.toString() === '#' + elements_1[a].id) {
530 links.push(allLinks[c]);
531 }
532 }
533
534 for (var d = 0, linksLen = links.length; d < linksLen; d++) {
535 links[d].setAttributeNS(xlinkNamespace$1, 'href', '#' + newId_1);
536 }
537
538 elements_1[a].id = newId_1;
539 };
540
541 for (var a = 0, elementsLen = elements_1.length; a < elementsLen; a++) {
542 _loop_1(a);
543 }
544 });
545 }
546
547 svg.removeAttribute('xmlns:a');
548 var scripts = svg.querySelectorAll('script');
549 var scriptsToEval = [];
550 var script;
551 var scriptType;
552
553 for (var i = 0, scriptsLen = scripts.length; i < scriptsLen; i++) {
554 scriptType = scripts[i].getAttribute('type');
555
556 if (!scriptType || scriptType === 'application/ecmascript' || scriptType === 'application/javascript' || scriptType === 'text/javascript') {
557 script = scripts[i].innerText || scripts[i].textContent;
558
559 if (script) {
560 scriptsToEval.push(script);
561 }
562
563 svg.removeChild(scripts[i]);
564 }
565 }
566
567 if (scriptsToEval.length > 0 && (evalScripts === 'always' || evalScripts === 'once' && !ranScripts[elUrl])) {
568 for (var l = 0, scriptsToEvalLen = scriptsToEval.length; l < scriptsToEvalLen; l++) {
569 new Function(scriptsToEval[l])(window);
570 }
571
572 ranScripts[elUrl] = true;
573 }
574
575 var styleTags = svg.querySelectorAll('style');
576 Array.prototype.forEach.call(styleTags, function (styleTag) {
577 styleTag.textContent += '';
578 });
579 svg.setAttribute('xmlns', svgNamespace$1);
580 svg.setAttribute('xmlns:xlink', xlinkNamespace$1);
581 beforeEach(svg);
582
583 if (!el.parentNode) {
584 injectedElements.splice(injectedElements.indexOf(el), 1);
585 el = null;
586 callback(new Error('Parent node is null'));
587 return;
588 }
589
590 el.parentNode.replaceChild(svg, el);
591 injectedElements.splice(injectedElements.indexOf(el), 1);
592 el = null;
593 callback(null, svg);
594 });
595 };
596
597 var SVGInjector = function SVGInjector(elements, _a) {
598 var _b = _a === void 0 ? {} : _a,
599 _c = _b.afterAll,
600 afterAll = _c === void 0 ? function () {
601 return undefined;
602 } : _c,
603 _d = _b.afterEach,
604 afterEach = _d === void 0 ? function () {
605 return undefined;
606 } : _d,
607 _e = _b.beforeEach,
608 beforeEach = _e === void 0 ? function () {
609 return undefined;
610 } : _e,
611 _f = _b.cacheRequests,
612 cacheRequests = _f === void 0 ? true : _f,
613 _g = _b.evalScripts,
614 evalScripts = _g === void 0 ? 'never' : _g,
615 _h = _b.httpRequestWithCredentials,
616 httpRequestWithCredentials = _h === void 0 ? false : _h,
617 _j = _b.renumerateIRIElements,
618 renumerateIRIElements = _j === void 0 ? true : _j;
619
620 if (elements && 'length' in elements) {
621 var elementsLoaded_1 = 0;
622
623 for (var i = 0, j = elements.length; i < j; i++) {
624 injectElement(elements[i], evalScripts, renumerateIRIElements, cacheRequests, httpRequestWithCredentials, beforeEach, function (error, svg) {
625 afterEach(error, svg);
626
627 if (elements && 'length' in elements && elements.length === ++elementsLoaded_1) {
628 afterAll(elementsLoaded_1);
629 }
630 });
631 }
632 } else if (elements) {
633 injectElement(elements, evalScripts, renumerateIRIElements, cacheRequests, httpRequestWithCredentials, beforeEach, function (error, svg) {
634 afterEach(error, svg);
635 afterAll(1);
636 elements = null;
637 });
638 } else {
639 afterAll(0);
640 }
641 };
642
643 // Hat-tip: https://github.com/developit/preact-compat/blob/master/src/index.js#L402.
644 var shallowDiffers = function shallowDiffers(a, b) {
645 for (var i in a) {
646 if (!(i in b)) {
647 return true;
648 }
649 }
650
651 for (var _i in b) {
652 if (a[_i] !== b[_i]) {
653 return true;
654 }
655 }
656
657 return false;
658 };
659
660 var _excluded = ["afterInjection", "beforeInjection", "evalScripts", "fallback", "httpRequestWithCredentials", "loading", "renumerateIRIElements", "src", "useRequestCache", "wrapper"];
661 var svgNamespace = 'http://www.w3.org/2000/svg';
662 var xlinkNamespace = 'http://www.w3.org/1999/xlink';
663 var ReactSVG = /*#__PURE__*/function (_React$Component) {
664 _inheritsLoose(ReactSVG, _React$Component);
665
666 function ReactSVG() {
667 var _this;
668
669 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
670 args[_key] = arguments[_key];
671 }
672
673 _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
674 _this.initialState = {
675 hasError: false,
676 isLoading: true
677 };
678 _this.state = _this.initialState;
679 _this._isMounted = false;
680 _this.reactWrapper = void 0;
681 _this.nonReactWrapper = void 0;
682
683 _this.refCallback = function (reactWrapper) {
684 _this.reactWrapper = reactWrapper;
685 };
686
687 return _this;
688 }
689
690 var _proto = ReactSVG.prototype;
691
692 _proto.renderSVG = function renderSVG() {
693 var _this2 = this;
694
695 /* istanbul ignore else */
696 if (this.reactWrapper instanceof Node) {
697 var _this$props = this.props,
698 beforeInjection = _this$props.beforeInjection,
699 evalScripts = _this$props.evalScripts,
700 httpRequestWithCredentials = _this$props.httpRequestWithCredentials,
701 renumerateIRIElements = _this$props.renumerateIRIElements,
702 src = _this$props.src,
703 useRequestCache = _this$props.useRequestCache;
704 /* eslint-disable @typescript-eslint/no-non-null-assertion */
705
706 var afterInjection = this.props.afterInjection;
707 var wrapper = this.props.wrapper;
708 /* eslint-enable @typescript-eslint/no-non-null-assertion */
709
710 var nonReactWrapper;
711 var nonReactTarget;
712
713 if (wrapper === 'svg') {
714 nonReactWrapper = document.createElementNS(svgNamespace, wrapper);
715 nonReactWrapper.setAttribute('xmlns', svgNamespace);
716 nonReactWrapper.setAttribute('xmlns:xlink', xlinkNamespace);
717 nonReactTarget = document.createElementNS(svgNamespace, wrapper);
718 } else {
719 nonReactWrapper = document.createElement(wrapper);
720 nonReactTarget = document.createElement(wrapper);
721 }
722
723 nonReactWrapper.appendChild(nonReactTarget);
724 nonReactTarget.dataset.src = src;
725 this.nonReactWrapper = this.reactWrapper.appendChild(nonReactWrapper);
726
727 var afterEach = function afterEach(error, svg) {
728 if (error) {
729 _this2.removeSVG();
730
731 if (!_this2._isMounted) {
732 afterInjection(error);
733 return;
734 }
735 } // TODO (Tane): It'd be better to cleanly unsubscribe from SVGInjector
736 // callbacks instead of tracking a property like this.
737
738
739 if (_this2._isMounted) {
740 _this2.setState(function () {
741 return {
742 hasError: !!error,
743 isLoading: false
744 };
745 }, function () {
746 afterInjection(error, svg);
747 });
748 }
749 };
750
751 SVGInjector(nonReactTarget, {
752 afterEach: afterEach,
753 beforeEach: beforeInjection,
754 cacheRequests: useRequestCache,
755 evalScripts: evalScripts,
756 httpRequestWithCredentials: httpRequestWithCredentials,
757 renumerateIRIElements: renumerateIRIElements
758 });
759 }
760 };
761
762 _proto.removeSVG = function removeSVG() {
763 var _this$nonReactWrapper;
764
765 if ((_this$nonReactWrapper = this.nonReactWrapper) != null && _this$nonReactWrapper.parentNode) {
766 this.nonReactWrapper.parentNode.removeChild(this.nonReactWrapper);
767 this.nonReactWrapper = null;
768 }
769 };
770
771 _proto.componentDidMount = function componentDidMount() {
772 this._isMounted = true;
773 this.renderSVG();
774 };
775
776 _proto.componentDidUpdate = function componentDidUpdate(prevProps) {
777 var _this3 = this;
778
779 if (shallowDiffers(prevProps, this.props)) {
780 this.setState(function () {
781 return _this3.initialState;
782 }, function () {
783 _this3.removeSVG();
784
785 _this3.renderSVG();
786 });
787 }
788 };
789
790 _proto.componentWillUnmount = function componentWillUnmount() {
791 this._isMounted = false;
792 this.removeSVG();
793 };
794
795 _proto.render = function render() {
796 /* eslint-disable @typescript-eslint/no-unused-vars */
797 var _this$props2 = this.props;
798 _this$props2.afterInjection;
799 _this$props2.beforeInjection;
800 _this$props2.evalScripts;
801 var Fallback = _this$props2.fallback;
802 _this$props2.httpRequestWithCredentials;
803 var Loading = _this$props2.loading;
804 _this$props2.renumerateIRIElements;
805 _this$props2.src;
806 _this$props2.useRequestCache;
807 var wrapper = _this$props2.wrapper,
808 rest = _objectWithoutPropertiesLoose(_this$props2, _excluded);
809 /* eslint-enable @typescript-eslint/no-unused-vars */
810 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
811
812
813 var Wrapper = wrapper;
814 return /*#__PURE__*/React__namespace.createElement(Wrapper, _extends({}, rest, {
815 ref: this.refCallback
816 }, wrapper === 'svg' ? {
817 xmlns: svgNamespace,
818 xmlnsXlink: xlinkNamespace
819 } : {}), this.state.isLoading && Loading && /*#__PURE__*/React__namespace.createElement(Loading, null), this.state.hasError && Fallback && /*#__PURE__*/React__namespace.createElement(Fallback, null));
820 };
821
822 return ReactSVG;
823 }(React__namespace.Component);
824 ReactSVG.defaultProps = {
825 afterInjection: function afterInjection() {
826 return undefined;
827 },
828 beforeInjection: function beforeInjection() {
829 return undefined;
830 },
831 evalScripts: 'never',
832 fallback: null,
833 httpRequestWithCredentials: false,
834 loading: null,
835 renumerateIRIElements: true,
836 useRequestCache: true,
837 wrapper: 'div'
838 };
839 ReactSVG.propTypes = {
840 afterInjection: PropTypes__namespace.func,
841 beforeInjection: PropTypes__namespace.func,
842 evalScripts: PropTypes__namespace.oneOf(['always', 'once', 'never']),
843 fallback: PropTypes__namespace.oneOfType([PropTypes__namespace.func, PropTypes__namespace.object, PropTypes__namespace.string]),
844 httpRequestWithCredentials: PropTypes__namespace.bool,
845 loading: PropTypes__namespace.oneOfType([PropTypes__namespace.func, PropTypes__namespace.object, PropTypes__namespace.string]),
846 renumerateIRIElements: PropTypes__namespace.bool,
847 src: PropTypes__namespace.string.isRequired,
848 useRequestCache: PropTypes__namespace.bool,
849 wrapper: PropTypes__namespace.oneOf(['div', 'span', 'svg'])
850 };
851
852 exports.ReactSVG = ReactSVG;
853
854 Object.defineProperty(exports, '__esModule', { value: true });
855
856}));
857//# sourceMappingURL=react-svg.umd.development.js.map