UNPKG

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