react-inlinesvg 4.0.0 → 4.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1321 +1,512 @@
1
1
  "use strict";
2
- function _array_like_to_array(arr, len) {
3
- if (len == null || len > arr.length) len = arr.length;
4
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
- return arr2;
6
- }
7
- function _array_with_holes(arr) {
8
- if (Array.isArray(arr)) return arr;
9
- }
10
- function _array_without_holes(arr) {
11
- if (Array.isArray(arr)) return _array_like_to_array(arr);
12
- }
13
- function _assert_this_initialized(self) {
14
- if (self === void 0) {
15
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
16
- }
17
- return self;
18
- }
19
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
20
- try {
21
- var info = gen[key](arg);
22
- var value = info.value;
23
- } catch (error) {
24
- reject(error);
25
- return;
26
- }
27
- if (info.done) {
28
- resolve(value);
29
- } else {
30
- Promise.resolve(value).then(_next, _throw);
31
- }
32
- }
33
- function _async_to_generator(fn) {
34
- return function() {
35
- var self = this, args = arguments;
36
- return new Promise(function(resolve, reject) {
37
- var gen = fn.apply(self, args);
38
- function _next(value) {
39
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
40
- }
41
- function _throw(err) {
42
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
43
- }
44
- _next(undefined);
45
- });
46
- };
47
- }
48
- function _class_call_check(instance, Constructor) {
49
- if (!(instance instanceof Constructor)) {
50
- throw new TypeError("Cannot call a class as a function");
51
- }
52
- }
53
- function _defineProperties(target, props) {
54
- for(var i = 0; i < props.length; i++){
55
- var descriptor = props[i];
56
- descriptor.enumerable = descriptor.enumerable || false;
57
- descriptor.configurable = true;
58
- if ("value" in descriptor) descriptor.writable = true;
59
- Object.defineProperty(target, descriptor.key, descriptor);
60
- }
61
- }
62
- function _create_class(Constructor, protoProps, staticProps) {
63
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
64
- if (staticProps) _defineProperties(Constructor, staticProps);
65
- return Constructor;
66
- }
67
- function _define_property(obj, key, value) {
68
- if (key in obj) {
69
- Object.defineProperty(obj, key, {
70
- value: value,
71
- enumerable: true,
72
- configurable: true,
73
- writable: true
74
- });
75
- } else {
76
- obj[key] = value;
77
- }
78
- return obj;
79
- }
80
- function _get_prototype_of(o) {
81
- _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
82
- return o.__proto__ || Object.getPrototypeOf(o);
83
- };
84
- return _get_prototype_of(o);
85
- }
86
- function _inherits(subClass, superClass) {
87
- if (typeof superClass !== "function" && superClass !== null) {
88
- throw new TypeError("Super expression must either be null or a function");
89
- }
90
- subClass.prototype = Object.create(superClass && superClass.prototype, {
91
- constructor: {
92
- value: subClass,
93
- writable: true,
94
- configurable: true
95
- }
96
- });
97
- if (superClass) _set_prototype_of(subClass, superClass);
98
- }
99
- function _instanceof(left, right) {
100
- if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
101
- return !!right[Symbol.hasInstance](left);
102
- } else {
103
- return left instanceof right;
104
- }
105
- }
106
- function _iterable_to_array(iter) {
107
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
108
- }
109
- function _iterable_to_array_limit(arr, i) {
110
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
111
- if (_i == null) return;
112
- var _arr = [];
113
- var _n = true;
114
- var _d = false;
115
- var _s, _e;
116
- try {
117
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
118
- _arr.push(_s.value);
119
- if (i && _arr.length === i) break;
120
- }
121
- } catch (err) {
122
- _d = true;
123
- _e = err;
124
- } finally{
125
- try {
126
- if (!_n && _i["return"] != null) _i["return"]();
127
- } finally{
128
- if (_d) throw _e;
129
- }
130
- }
131
- return _arr;
132
- }
133
- function _non_iterable_rest() {
134
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
135
- }
136
- function _non_iterable_spread() {
137
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
138
- }
139
- function _object_spread(target) {
140
- for(var i = 1; i < arguments.length; i++){
141
- var source = arguments[i] != null ? arguments[i] : {};
142
- var ownKeys = Object.keys(source);
143
- if (typeof Object.getOwnPropertySymbols === "function") {
144
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
145
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
146
- }));
147
- }
148
- ownKeys.forEach(function(key) {
149
- _define_property(target, key, source[key]);
150
- });
151
- }
152
- return target;
153
- }
154
- function _possible_constructor_return(self, call) {
155
- if (call && (_type_of(call) === "object" || typeof call === "function")) {
156
- return call;
157
- }
158
- return _assert_this_initialized(self);
159
- }
160
- function _set_prototype_of(o, p) {
161
- _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
162
- o.__proto__ = p;
163
- return o;
164
- };
165
- return _set_prototype_of(o, p);
166
- }
167
- function _sliced_to_array(arr, i) {
168
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
169
- }
170
- function _to_consumable_array(arr) {
171
- return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
172
- }
173
- function _type_of(obj) {
174
- "@swc/helpers - typeof";
175
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
176
- }
177
- function _unsupported_iterable_to_array(o, minLen) {
178
- if (!o) return;
179
- if (typeof o === "string") return _array_like_to_array(o, minLen);
180
- var n = Object.prototype.toString.call(o).slice(8, -1);
181
- if (n === "Object" && o.constructor) n = o.constructor.name;
182
- if (n === "Map" || n === "Set") return Array.from(n);
183
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
184
- }
185
- function _is_native_reflect_construct() {
186
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
187
- if (Reflect.construct.sham) return false;
188
- if (typeof Proxy === "function") return true;
189
- try {
190
- Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
191
- return true;
192
- } catch (e) {
193
- return false;
194
- }
195
- }
196
- function _create_super(Derived) {
197
- var hasNativeReflectConstruct = _is_native_reflect_construct();
198
- return function _createSuperInternal() {
199
- var Super = _get_prototype_of(Derived), result;
200
- if (hasNativeReflectConstruct) {
201
- var NewTarget = _get_prototype_of(this).constructor;
202
- result = Reflect.construct(Super, arguments, NewTarget);
203
- } else {
204
- result = Super.apply(this, arguments);
205
- }
206
- return _possible_constructor_return(this, result);
207
- };
208
- }
209
- function _ts_generator(thisArg, body) {
210
- var f, y, t, g, _ = {
211
- label: 0,
212
- sent: function() {
213
- if (t[0] & 1) throw t[1];
214
- return t[1];
215
- },
216
- trys: [],
217
- ops: []
218
- };
219
- return g = {
220
- next: verb(0),
221
- "throw": verb(1),
222
- "return": verb(2)
223
- }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
224
- return this;
225
- }), g;
226
- function verb(n) {
227
- return function(v) {
228
- return step([
229
- n,
230
- v
231
- ]);
232
- };
233
- }
234
- function step(op) {
235
- if (f) throw new TypeError("Generator is already executing.");
236
- while(_)try {
237
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
238
- if (y = 0, t) op = [
239
- op[0] & 2,
240
- t.value
241
- ];
242
- switch(op[0]){
243
- case 0:
244
- case 1:
245
- t = op;
246
- break;
247
- case 4:
248
- _.label++;
249
- return {
250
- value: op[1],
251
- done: false
252
- };
253
- case 5:
254
- _.label++;
255
- y = op[1];
256
- op = [
257
- 0
258
- ];
259
- continue;
260
- case 7:
261
- op = _.ops.pop();
262
- _.trys.pop();
263
- continue;
264
- default:
265
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
266
- _ = 0;
267
- continue;
268
- }
269
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
270
- _.label = op[1];
271
- break;
272
- }
273
- if (op[0] === 6 && _.label < t[1]) {
274
- _.label = t[1];
275
- t = op;
276
- break;
277
- }
278
- if (t && _.label < t[2]) {
279
- _.label = t[2];
280
- _.ops.push(op);
281
- break;
282
- }
283
- if (t[2]) _.ops.pop();
284
- _.trys.pop();
285
- continue;
286
- }
287
- op = body.call(thisArg, _);
288
- } catch (e) {
289
- op = [
290
- 6,
291
- e
292
- ];
293
- y = 0;
294
- } finally{
295
- f = t = 0;
296
- }
297
- if (op[0] & 5) throw op[1];
298
- return {
299
- value: op[0] ? op[1] : void 0,
300
- done: true
301
- };
302
- }
303
- }
304
2
  var __create = Object.create;
305
3
  var __defProp = Object.defineProperty;
306
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
307
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
308
6
  var __getProtoOf = Object.getPrototypeOf;
309
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
310
- var __defNormalProp = function(obj, key, value) {
311
- return key in obj ? __defProp(obj, key, {
312
- enumerable: true,
313
- configurable: true,
314
- writable: true,
315
- value: value
316
- }) : obj[key] = value;
317
- };
318
- var __export = function(target, all) {
319
- for(var name in all)__defProp(target, name, {
320
- get: all[name],
321
- enumerable: true
322
- });
323
- };
324
- var __copyProps = function(to, from, except, desc) {
325
- if (from && typeof from === "object" || typeof from === "function") {
326
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
327
- try {
328
- var _loop = function() {
329
- var key = _step.value;
330
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
331
- get: function() {
332
- return from[key];
333
- },
334
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
335
- });
336
- };
337
- for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
338
- } catch (err) {
339
- _didIteratorError = true;
340
- _iteratorError = err;
341
- } finally{
342
- try {
343
- if (!_iteratorNormalCompletion && _iterator.return != null) {
344
- _iterator.return();
345
- }
346
- } finally{
347
- if (_didIteratorError) {
348
- throw _iteratorError;
349
- }
350
- }
351
- }
352
- }
353
- return to;
354
- };
355
- var __toESM = function(mod, isNodeMode, target) {
356
- return target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(// If the importer is in node compatibility mode or this is not an ESM
357
- // file that has been converted to a CommonJS file using a Babel-
358
- // compatible transform (i.e. "__esModule" has not been set), then set
359
- // "default" to the CommonJS "module.exports" for node compatibility.
360
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
361
- value: mod,
362
- enumerable: true
363
- }) : target, mod);
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
364
12
  };
365
- var __toCommonJS = function(mod) {
366
- return __copyProps(__defProp({}, "__esModule", {
367
- value: true
368
- }), mod);
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
369
20
  };
370
- var __publicField = function(obj, key, value) {
371
- __defNormalProp(obj, (typeof key === "undefined" ? "undefined" : _type_of(key)) !== "symbol" ? key + "" : key, value);
372
- return value;
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+ var __publicField = (obj, key, value) => {
31
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
32
+ return value;
373
33
  };
34
+
374
35
  // src/index.tsx
375
36
  var src_exports = {};
376
37
  __export(src_exports, {
377
- cacheStore: function() {
378
- return cacheStore;
379
- },
380
- default: function() {
381
- return InlineSVG;
382
- }
38
+ cacheStore: () => cacheStore,
39
+ default: () => InlineSVG
383
40
  });
384
41
  module.exports = __toCommonJS(src_exports);
385
42
  var React = __toESM(require("react"));
386
43
  var import_react_from_dom = __toESM(require("react-from-dom"));
44
+
387
45
  // src/config.ts
388
46
  var CACHE_NAME = "react-inlinesvg";
389
47
  var CACHE_MAX_RETRIES = 10;
390
48
  var STATUS = {
391
- IDLE: "idle",
392
- LOADING: "loading",
393
- LOADED: "loaded",
394
- FAILED: "failed",
395
- READY: "ready",
396
- UNSUPPORTED: "unsupported"
49
+ IDLE: "idle",
50
+ LOADING: "loading",
51
+ LOADED: "loaded",
52
+ FAILED: "failed",
53
+ READY: "ready",
54
+ UNSUPPORTED: "unsupported"
397
55
  };
56
+
398
57
  // src/helpers.ts
399
- var import_exenv = require("exenv");
400
58
  function canUseDOM() {
401
- return import_exenv.canUseDOM;
59
+ return !!(typeof window !== "undefined" && window.document && window.document.createElement);
402
60
  }
403
61
  function isSupportedEnvironment() {
404
- return supportsInlineSVG() && typeof window !== "undefined" && window !== null;
405
- }
406
- function request(url, options) {
407
- return _request.apply(this, arguments);
408
- }
409
- function _request() {
410
- _request = _async_to_generator(function(url, options) {
411
- var response, contentType, _split, fileType;
412
- return _ts_generator(this, function(_state) {
413
- switch(_state.label){
414
- case 0:
415
- return [
416
- 4,
417
- fetch(url, options)
418
- ];
419
- case 1:
420
- response = _state.sent();
421
- contentType = response.headers.get("content-type");
422
- _split = _sliced_to_array((contentType || "").split(/ ?; ?/), 1), fileType = _split[0];
423
- if (response.status > 299) {
424
- throw new Error("Not found");
425
- }
426
- if (![
427
- "image/svg+xml",
428
- "text/plain"
429
- ].some(function(d) {
430
- return fileType.includes(d);
431
- })) {
432
- throw new Error("Content type isn't valid: ".concat(fileType));
433
- }
434
- return [
435
- 2,
436
- response.text()
437
- ];
438
- }
439
- });
440
- });
441
- return _request.apply(this, arguments);
442
- }
443
- function sleep() {
444
- var seconds = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 1;
445
- return new Promise(function(resolve) {
446
- setTimeout(resolve, seconds * 1e3);
447
- });
62
+ return supportsInlineSVG() && typeof window !== "undefined" && window !== null;
63
+ }
64
+ async function request(url, options) {
65
+ const response = await fetch(url, options);
66
+ const contentType = response.headers.get("content-type");
67
+ const [fileType] = (contentType || "").split(/ ?; ?/);
68
+ if (response.status > 299) {
69
+ throw new Error("Not found");
70
+ }
71
+ if (!["image/svg+xml", "text/plain"].some((d) => fileType.includes(d))) {
72
+ throw new Error(`Content type isn't valid: ${fileType}`);
73
+ }
74
+ return response.text();
75
+ }
76
+ function sleep(seconds = 1) {
77
+ return new Promise((resolve) => {
78
+ setTimeout(resolve, seconds * 1e3);
79
+ });
448
80
  }
449
81
  function supportsInlineSVG() {
450
- if (!document) {
451
- return false;
452
- }
453
- var div = document.createElement("div");
454
- div.innerHTML = "<svg />";
455
- var svg = div.firstChild;
456
- return !!svg && svg.namespaceURI === "http://www.w3.org/2000/svg";
82
+ if (!document) {
83
+ return false;
84
+ }
85
+ const div = document.createElement("div");
86
+ div.innerHTML = "<svg />";
87
+ const svg = div.firstChild;
88
+ return !!svg && svg.namespaceURI === "http://www.w3.org/2000/svg";
457
89
  }
458
90
  function randomCharacter(character) {
459
- return character[Math.floor(Math.random() * character.length)];
91
+ return character[Math.floor(Math.random() * character.length)];
460
92
  }
461
93
  function randomString(length) {
462
- var letters = "abcdefghijklmnopqrstuvwxyz";
463
- var numbers = "1234567890";
464
- var charset = "".concat(letters).concat(letters.toUpperCase()).concat(numbers);
465
- var R = "";
466
- for(var index = 0; index < length; index++){
467
- R += randomCharacter(charset);
94
+ const letters = "abcdefghijklmnopqrstuvwxyz";
95
+ const numbers = "1234567890";
96
+ const charset = `${letters}${letters.toUpperCase()}${numbers}`;
97
+ let R = "";
98
+ for (let index = 0; index < length; index++) {
99
+ R += randomCharacter(charset);
100
+ }
101
+ return R;
102
+ }
103
+ function omit(input, ...filter) {
104
+ const output = {};
105
+ for (const key in input) {
106
+ if ({}.hasOwnProperty.call(input, key)) {
107
+ if (!filter.includes(key)) {
108
+ output[key] = input[key];
109
+ }
468
110
  }
469
- return R;
111
+ }
112
+ return output;
470
113
  }
471
- function omit(input) {
472
- for(var _len = arguments.length, filter = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
473
- filter[_key - 1] = arguments[_key];
114
+
115
+ // src/cache.ts
116
+ var CacheStore = class {
117
+ constructor() {
118
+ __publicField(this, "cacheApi");
119
+ __publicField(this, "cacheStore");
120
+ __publicField(this, "subscribers", []);
121
+ __publicField(this, "isReady", false);
122
+ this.cacheStore = /* @__PURE__ */ new Map();
123
+ let cacheName = CACHE_NAME;
124
+ let usePersistentCache = false;
125
+ if (canUseDOM()) {
126
+ cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;
127
+ usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE;
474
128
  }
475
- var output = {};
476
- for(var key in input){
477
- if (({}).hasOwnProperty.call(input, key)) {
478
- if (!filter.includes(key)) {
479
- output[key] = input[key];
480
- }
481
- }
129
+ if (usePersistentCache) {
130
+ caches.open(cacheName).then((cache) => {
131
+ this.cacheApi = cache;
132
+ this.isReady = true;
133
+ this.subscribers.forEach((callback) => callback());
134
+ });
135
+ } else {
136
+ this.isReady = true;
482
137
  }
483
- return output;
484
- }
485
- // src/cache.ts
486
- var CacheStore = /*#__PURE__*/ function() {
487
- function CacheStore() {
488
- var _this = this;
489
- _class_call_check(this, CacheStore);
490
- __publicField(this, "cacheApi");
491
- __publicField(this, "cacheStore");
492
- __publicField(this, "subscribers", []);
493
- __publicField(this, "usePersistentCache");
494
- __publicField(this, "isReady", false);
495
- this.cacheStore = /* @__PURE__ */ new Map();
496
- this.usePersistentCache = "REACT_INLINESVG_PERSISTENT_CACHE" in window && !!window.REACT_INLINESVG_PERSISTENT_CACHE;
497
- if (this.usePersistentCache) {
498
- caches.open(CACHE_NAME).then(function(cache) {
499
- _this.cacheApi = cache;
500
- _this.isReady = true;
501
- _this.subscribers.forEach(function(callback) {
502
- return callback();
503
- });
504
- });
505
- } else {
506
- this.isReady = true;
507
- }
138
+ }
139
+ onReady(callback) {
140
+ if (this.isReady) {
141
+ callback();
142
+ } else {
143
+ this.subscribers.push(callback);
508
144
  }
509
- _create_class(CacheStore, [
510
- {
511
- key: "onReady",
512
- value: function onReady(callback) {
513
- if (this.isReady) {
514
- callback();
515
- } else {
516
- this.subscribers.push(callback);
517
- }
518
- }
519
- },
520
- {
521
- key: "get",
522
- value: function get(url, fetchOptions) {
523
- var _this = this;
524
- return _async_to_generator(function() {
525
- var _this_cacheStore_get, _this_cacheStore_get_content;
526
- return _ts_generator(this, function(_state) {
527
- switch(_state.label){
528
- case 0:
529
- return [
530
- 4,
531
- _this.usePersistentCache ? _this.fetchAndAddToPersistentCache(url, fetchOptions) : _this.fetchAndAddToInternalCache(url, fetchOptions)
532
- ];
533
- case 1:
534
- _state.sent();
535
- return [
536
- 2,
537
- (_this_cacheStore_get_content = (_this_cacheStore_get = _this.cacheStore.get(url)) === null || _this_cacheStore_get === void 0 ? void 0 : _this_cacheStore_get.content) !== null && _this_cacheStore_get_content !== void 0 ? _this_cacheStore_get_content : ""
538
- ];
539
- }
540
- });
541
- })();
542
- }
543
- },
544
- {
545
- key: "set",
546
- value: function set(url, data) {
547
- this.cacheStore.set(url, data);
548
- }
549
- },
550
- {
551
- key: "isCached",
552
- value: function isCached(url) {
553
- var _this_cacheStore_get;
554
- return ((_this_cacheStore_get = this.cacheStore.get(url)) === null || _this_cacheStore_get === void 0 ? void 0 : _this_cacheStore_get.status) === STATUS.LOADED;
555
- }
556
- },
557
- {
558
- key: "fetchAndAddToInternalCache",
559
- value: function fetchAndAddToInternalCache(url, fetchOptions) {
560
- var _this = this;
561
- return _async_to_generator(function() {
562
- var _cache, _cache1, cache, content, error;
563
- return _ts_generator(this, function(_state) {
564
- switch(_state.label){
565
- case 0:
566
- cache = _this.cacheStore.get(url);
567
- if (!(((_cache = cache) === null || _cache === void 0 ? void 0 : _cache.status) === STATUS.LOADING)) return [
568
- 3,
569
- 2
570
- ];
571
- return [
572
- 4,
573
- _this.handleLoading(url, /*#__PURE__*/ _async_to_generator(function() {
574
- return _ts_generator(this, function(_state) {
575
- switch(_state.label){
576
- case 0:
577
- _this.cacheStore.set(url, {
578
- content: "",
579
- status: STATUS.IDLE
580
- });
581
- return [
582
- 4,
583
- _this.fetchAndAddToInternalCache(url, fetchOptions)
584
- ];
585
- case 1:
586
- _state.sent();
587
- return [
588
- 2
589
- ];
590
- }
591
- });
592
- }))
593
- ];
594
- case 1:
595
- _state.sent();
596
- return [
597
- 2
598
- ];
599
- case 2:
600
- if (!!((_cache1 = cache) === null || _cache1 === void 0 ? void 0 : _cache1.content)) return [
601
- 3,
602
- 6
603
- ];
604
- _this.cacheStore.set(url, {
605
- content: "",
606
- status: STATUS.LOADING
607
- });
608
- _state.label = 3;
609
- case 3:
610
- _state.trys.push([
611
- 3,
612
- 5,
613
- ,
614
- 6
615
- ]);
616
- return [
617
- 4,
618
- request(url, fetchOptions)
619
- ];
620
- case 4:
621
- content = _state.sent();
622
- _this.cacheStore.set(url, {
623
- content: content,
624
- status: STATUS.LOADED
625
- });
626
- return [
627
- 3,
628
- 6
629
- ];
630
- case 5:
631
- error = _state.sent();
632
- _this.cacheStore.set(url, {
633
- content: "",
634
- status: STATUS.FAILED
635
- });
636
- throw error;
637
- case 6:
638
- return [
639
- 2
640
- ];
641
- }
642
- });
643
- })();
644
- }
645
- },
646
- {
647
- key: "fetchAndAddToPersistentCache",
648
- value: function fetchAndAddToPersistentCache(url, fetchOptions) {
649
- var _this = this;
650
- return _async_to_generator(function() {
651
- var _cache, _cache1, _this_cacheApi, cache, data, content, _this_cacheApi1, _this_cacheApi2, _response, response, _ref, content1, error;
652
- return _ts_generator(this, function(_state) {
653
- switch(_state.label){
654
- case 0:
655
- cache = _this.cacheStore.get(url);
656
- if (((_cache = cache) === null || _cache === void 0 ? void 0 : _cache.status) === STATUS.LOADED) {
657
- return [
658
- 2
659
- ];
660
- }
661
- if (!(((_cache1 = cache) === null || _cache1 === void 0 ? void 0 : _cache1.status) === STATUS.LOADING)) return [
662
- 3,
663
- 2
664
- ];
665
- return [
666
- 4,
667
- _this.handleLoading(url, /*#__PURE__*/ _async_to_generator(function() {
668
- return _ts_generator(this, function(_state) {
669
- switch(_state.label){
670
- case 0:
671
- _this.cacheStore.set(url, {
672
- content: "",
673
- status: STATUS.IDLE
674
- });
675
- return [
676
- 4,
677
- _this.fetchAndAddToPersistentCache(url, fetchOptions)
678
- ];
679
- case 1:
680
- _state.sent();
681
- return [
682
- 2
683
- ];
684
- }
685
- });
686
- }))
687
- ];
688
- case 1:
689
- _state.sent();
690
- return [
691
- 2
692
- ];
693
- case 2:
694
- _this.cacheStore.set(url, {
695
- content: "",
696
- status: STATUS.LOADING
697
- });
698
- return [
699
- 4,
700
- (_this_cacheApi = _this.cacheApi) === null || _this_cacheApi === void 0 ? void 0 : _this_cacheApi.match(url)
701
- ];
702
- case 3:
703
- data = _state.sent();
704
- if (!data) return [
705
- 3,
706
- 5
707
- ];
708
- return [
709
- 4,
710
- data.text()
711
- ];
712
- case 4:
713
- content = _state.sent();
714
- _this.cacheStore.set(url, {
715
- content: content,
716
- status: STATUS.LOADED
717
- });
718
- return [
719
- 2
720
- ];
721
- case 5:
722
- _state.trys.push([
723
- 5,
724
- 9,
725
- ,
726
- 10
727
- ]);
728
- return [
729
- 4,
730
- (_this_cacheApi1 = _this.cacheApi) === null || _this_cacheApi1 === void 0 ? void 0 : _this_cacheApi1.add(new Request(url, fetchOptions))
731
- ];
732
- case 6:
733
- _state.sent();
734
- return [
735
- 4,
736
- (_this_cacheApi2 = _this.cacheApi) === null || _this_cacheApi2 === void 0 ? void 0 : _this_cacheApi2.match(url)
737
- ];
738
- case 7:
739
- response = _state.sent();
740
- return [
741
- 4,
742
- (_response = response) === null || _response === void 0 ? void 0 : _response.text()
743
- ];
744
- case 8:
745
- content1 = (_ref = _state.sent()) !== null && _ref !== void 0 ? _ref : "";
746
- _this.cacheStore.set(url, {
747
- content: content1,
748
- status: STATUS.LOADED
749
- });
750
- return [
751
- 3,
752
- 10
753
- ];
754
- case 9:
755
- error = _state.sent();
756
- _this.cacheStore.set(url, {
757
- content: "",
758
- status: STATUS.FAILED
759
- });
760
- throw error;
761
- case 10:
762
- return [
763
- 2
764
- ];
765
- }
766
- });
767
- })();
768
- }
769
- },
770
- {
771
- key: "handleLoading",
772
- value: function handleLoading(url, callback) {
773
- var _this = this;
774
- return _async_to_generator(function() {
775
- var _this_cacheStore_get, retryCount;
776
- return _ts_generator(this, function(_state) {
777
- switch(_state.label){
778
- case 0:
779
- retryCount = 0;
780
- _state.label = 1;
781
- case 1:
782
- if (!(((_this_cacheStore_get = _this.cacheStore.get(url)) === null || _this_cacheStore_get === void 0 ? void 0 : _this_cacheStore_get.status) === STATUS.LOADING && retryCount < CACHE_MAX_RETRIES)) return [
783
- 3,
784
- 3
785
- ];
786
- return [
787
- 4,
788
- sleep(0.1)
789
- ];
790
- case 2:
791
- _state.sent();
792
- retryCount += 1;
793
- return [
794
- 3,
795
- 1
796
- ];
797
- case 3:
798
- if (!(retryCount >= CACHE_MAX_RETRIES)) return [
799
- 3,
800
- 5
801
- ];
802
- return [
803
- 4,
804
- callback()
805
- ];
806
- case 4:
807
- _state.sent();
808
- _state.label = 5;
809
- case 5:
810
- return [
811
- 2
812
- ];
813
- }
814
- });
815
- })();
816
- }
817
- },
818
- {
819
- key: "keys",
820
- value: function keys() {
821
- return _to_consumable_array(this.cacheStore.keys());
822
- }
823
- },
824
- {
825
- key: "data",
826
- value: function data() {
827
- return _to_consumable_array(this.cacheStore.entries()).map(function(param) {
828
- var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1];
829
- return _define_property({}, key, value);
830
- });
831
- }
832
- },
833
- {
834
- key: "delete",
835
- value: function _delete(url) {
836
- var _this = this;
837
- return _async_to_generator(function() {
838
- return _ts_generator(this, function(_state) {
839
- switch(_state.label){
840
- case 0:
841
- if (!_this.cacheApi) return [
842
- 3,
843
- 2
844
- ];
845
- return [
846
- 4,
847
- _this.cacheApi.delete(url)
848
- ];
849
- case 1:
850
- _state.sent();
851
- _state.label = 2;
852
- case 2:
853
- _this.cacheStore.delete(url);
854
- return [
855
- 2
856
- ];
857
- }
858
- });
859
- })();
860
- }
861
- },
862
- {
863
- key: "clear",
864
- value: function clear() {
865
- var _this = this;
866
- return _async_to_generator(function() {
867
- var keys, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, key, err;
868
- return _ts_generator(this, function(_state) {
869
- switch(_state.label){
870
- case 0:
871
- if (!_this.cacheApi) return [
872
- 3,
873
- 9
874
- ];
875
- return [
876
- 4,
877
- _this.cacheApi.keys()
878
- ];
879
- case 1:
880
- keys = _state.sent();
881
- _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
882
- _state.label = 2;
883
- case 2:
884
- _state.trys.push([
885
- 2,
886
- 7,
887
- 8,
888
- 9
889
- ]);
890
- _iterator = keys[Symbol.iterator]();
891
- _state.label = 3;
892
- case 3:
893
- if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
894
- 3,
895
- 6
896
- ];
897
- key = _step.value;
898
- return [
899
- 4,
900
- _this.cacheApi.delete(key)
901
- ];
902
- case 4:
903
- _state.sent();
904
- _state.label = 5;
905
- case 5:
906
- _iteratorNormalCompletion = true;
907
- return [
908
- 3,
909
- 3
910
- ];
911
- case 6:
912
- return [
913
- 3,
914
- 9
915
- ];
916
- case 7:
917
- err = _state.sent();
918
- _didIteratorError = true;
919
- _iteratorError = err;
920
- return [
921
- 3,
922
- 9
923
- ];
924
- case 8:
925
- try {
926
- if (!_iteratorNormalCompletion && _iterator.return != null) {
927
- _iterator.return();
928
- }
929
- } finally{
930
- if (_didIteratorError) {
931
- throw _iteratorError;
932
- }
933
- }
934
- return [
935
- 7
936
- ];
937
- case 9:
938
- _this.cacheStore.clear();
939
- return [
940
- 2
941
- ];
942
- }
943
- });
944
- })();
945
- }
946
- }
947
- ]);
948
- return CacheStore;
949
- }();
145
+ }
146
+ async get(url, fetchOptions) {
147
+ await (this.cacheApi ? this.fetchAndAddToPersistentCache(url, fetchOptions) : this.fetchAndAddToInternalCache(url, fetchOptions));
148
+ return this.cacheStore.get(url)?.content ?? "";
149
+ }
150
+ set(url, data) {
151
+ this.cacheStore.set(url, data);
152
+ }
153
+ isCached(url) {
154
+ return this.cacheStore.get(url)?.status === STATUS.LOADED;
155
+ }
156
+ async fetchAndAddToInternalCache(url, fetchOptions) {
157
+ const cache = this.cacheStore.get(url);
158
+ if (cache?.status === STATUS.LOADING) {
159
+ await this.handleLoading(url, async () => {
160
+ this.cacheStore.set(url, { content: "", status: STATUS.IDLE });
161
+ await this.fetchAndAddToInternalCache(url, fetchOptions);
162
+ });
163
+ return;
164
+ }
165
+ if (!cache?.content) {
166
+ this.cacheStore.set(url, { content: "", status: STATUS.LOADING });
167
+ try {
168
+ const content = await request(url, fetchOptions);
169
+ this.cacheStore.set(url, { content, status: STATUS.LOADED });
170
+ } catch (error) {
171
+ this.cacheStore.set(url, { content: "", status: STATUS.FAILED });
172
+ throw error;
173
+ }
174
+ }
175
+ }
176
+ async fetchAndAddToPersistentCache(url, fetchOptions) {
177
+ const cache = this.cacheStore.get(url);
178
+ if (cache?.status === STATUS.LOADED) {
179
+ return;
180
+ }
181
+ if (cache?.status === STATUS.LOADING) {
182
+ await this.handleLoading(url, async () => {
183
+ this.cacheStore.set(url, { content: "", status: STATUS.IDLE });
184
+ await this.fetchAndAddToPersistentCache(url, fetchOptions);
185
+ });
186
+ return;
187
+ }
188
+ this.cacheStore.set(url, { content: "", status: STATUS.LOADING });
189
+ const data = await this.cacheApi?.match(url);
190
+ if (data) {
191
+ const content = await data.text();
192
+ this.cacheStore.set(url, { content, status: STATUS.LOADED });
193
+ return;
194
+ }
195
+ try {
196
+ await this.cacheApi?.add(new Request(url, fetchOptions));
197
+ const response = await this.cacheApi?.match(url);
198
+ const content = await response?.text() ?? "";
199
+ this.cacheStore.set(url, { content, status: STATUS.LOADED });
200
+ } catch (error) {
201
+ this.cacheStore.set(url, { content: "", status: STATUS.FAILED });
202
+ throw error;
203
+ }
204
+ }
205
+ async handleLoading(url, callback) {
206
+ let retryCount = 0;
207
+ while (this.cacheStore.get(url)?.status === STATUS.LOADING && retryCount < CACHE_MAX_RETRIES) {
208
+ await sleep(0.1);
209
+ retryCount += 1;
210
+ }
211
+ if (retryCount >= CACHE_MAX_RETRIES) {
212
+ await callback();
213
+ }
214
+ }
215
+ keys() {
216
+ return [...this.cacheStore.keys()];
217
+ }
218
+ data() {
219
+ return [...this.cacheStore.entries()].map(([key, value]) => ({ [key]: value }));
220
+ }
221
+ async delete(url) {
222
+ if (this.cacheApi) {
223
+ await this.cacheApi.delete(url);
224
+ }
225
+ this.cacheStore.delete(url);
226
+ }
227
+ async clear() {
228
+ if (this.cacheApi) {
229
+ const keys = await this.cacheApi.keys();
230
+ for (const key of keys) {
231
+ await this.cacheApi.delete(key);
232
+ }
233
+ }
234
+ this.cacheStore.clear();
235
+ }
236
+ };
237
+
950
238
  // src/index.tsx
951
239
  var import_jsx_runtime = require("react/jsx-runtime");
952
240
  var cacheStore;
953
- var ReactInlineSVG = /*#__PURE__*/ function(_React_PureComponent) {
954
- _inherits(ReactInlineSVG, _React_PureComponent);
955
- var _super = _create_super(ReactInlineSVG);
956
- function ReactInlineSVG(props) {
957
- _class_call_check(this, ReactInlineSVG);
958
- var _this;
959
- _this = _super.call(this, props);
960
- __publicField(_assert_this_initialized(_this), "hash");
961
- __publicField(_assert_this_initialized(_this), "isActive", false);
962
- __publicField(_assert_this_initialized(_this), "isInitialized", false);
963
- var _this1 = _assert_this_initialized(_this);
964
- __publicField(_assert_this_initialized(_this), "fetchContent", /*#__PURE__*/ _async_to_generator(function() {
965
- var _this_props, fetchOptions, src, content;
966
- return _ts_generator(this, function(_state) {
967
- switch(_state.label){
968
- case 0:
969
- _this_props = _this1.props, fetchOptions = _this_props.fetchOptions, src = _this_props.src;
970
- return [
971
- 4,
972
- request(src, fetchOptions)
973
- ];
974
- case 1:
975
- content = _state.sent();
976
- _this1.handleLoad(content);
977
- return [
978
- 2
979
- ];
980
- }
981
- });
982
- }));
983
- __publicField(_assert_this_initialized(_this), "handleError", function(error) {
984
- var onError = _this.props.onError;
985
- var status = error.message === "Browser does not support SVG" ? STATUS.UNSUPPORTED : STATUS.FAILED;
986
- if (_this.isActive) {
987
- _this.setState({
988
- status: status
989
- }, function() {
990
- if (typeof onError === "function") {
991
- onError(error);
992
- }
993
- });
994
- }
995
- });
996
- __publicField(_assert_this_initialized(_this), "handleLoad", function(content) {
997
- var hasCache = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
998
- if (_this.isActive) {
999
- _this.setState({
1000
- content: content,
1001
- isCached: hasCache,
1002
- status: STATUS.LOADED
1003
- }, _this.getElement);
1004
- }
241
+ var ReactInlineSVG = class extends React.PureComponent {
242
+ constructor(props) {
243
+ super(props);
244
+ __publicField(this, "hash");
245
+ __publicField(this, "isActive", false);
246
+ __publicField(this, "isInitialized", false);
247
+ __publicField(this, "fetchContent", async () => {
248
+ const { fetchOptions, src } = this.props;
249
+ const content = await request(src, fetchOptions);
250
+ this.handleLoad(content);
251
+ });
252
+ __publicField(this, "handleError", (error) => {
253
+ const { onError } = this.props;
254
+ const status = error.message === "Browser does not support SVG" ? STATUS.UNSUPPORTED : STATUS.FAILED;
255
+ if (this.isActive) {
256
+ this.setState({ status }, () => {
257
+ if (typeof onError === "function") {
258
+ onError(error);
259
+ }
1005
260
  });
1006
- _this.state = {
1007
- content: "",
1008
- element: null,
1009
- isCached: !!props.cacheRequests && cacheStore.isCached(props.src),
1010
- status: STATUS.IDLE
1011
- };
1012
- _this.hash = props.uniqueHash || randomString(8);
1013
- return _this;
261
+ }
262
+ });
263
+ __publicField(this, "handleLoad", (content, hasCache = false) => {
264
+ if (this.isActive) {
265
+ this.setState(
266
+ {
267
+ content,
268
+ isCached: hasCache,
269
+ status: STATUS.LOADED
270
+ },
271
+ this.getElement
272
+ );
273
+ }
274
+ });
275
+ this.state = {
276
+ content: "",
277
+ element: null,
278
+ isCached: !!props.cacheRequests && cacheStore.isCached(props.src),
279
+ status: STATUS.IDLE
280
+ };
281
+ this.hash = props.uniqueHash || randomString(8);
282
+ }
283
+ componentDidMount() {
284
+ this.isActive = true;
285
+ if (!canUseDOM() || this.isInitialized) {
286
+ return;
1014
287
  }
1015
- _create_class(ReactInlineSVG, [
1016
- {
1017
- key: "componentDidMount",
1018
- value: function componentDidMount() {
1019
- this.isActive = true;
1020
- if (!canUseDOM() || this.isInitialized) {
1021
- return;
1022
- }
1023
- var status = this.state.status;
1024
- var src = this.props.src;
1025
- try {
1026
- if (status === STATUS.IDLE) {
1027
- if (!isSupportedEnvironment()) {
1028
- throw new Error("Browser does not support SVG");
1029
- }
1030
- if (!src) {
1031
- throw new Error("Missing src");
1032
- }
1033
- this.load();
1034
- }
1035
- } catch (error) {
1036
- this.handleError(error);
1037
- }
1038
- this.isInitialized = true;
1039
- }
1040
- },
1041
- {
1042
- key: "componentDidUpdate",
1043
- value: function componentDidUpdate(previousProps, previousState) {
1044
- if (!canUseDOM()) {
1045
- return;
1046
- }
1047
- var _this_state = this.state, isCached = _this_state.isCached, status = _this_state.status;
1048
- var _this_props = this.props, onLoad = _this_props.onLoad, src = _this_props.src;
1049
- if (previousState.status !== STATUS.READY && status === STATUS.READY) {
1050
- if (onLoad) {
1051
- onLoad(src, isCached);
1052
- }
1053
- }
1054
- if (previousProps.src !== src) {
1055
- if (!src) {
1056
- this.handleError(new Error("Missing src"));
1057
- return;
1058
- }
1059
- this.load();
1060
- }
1061
- }
1062
- },
1063
- {
1064
- key: "componentWillUnmount",
1065
- value: function componentWillUnmount() {
1066
- this.isActive = false;
1067
- }
1068
- },
1069
- {
1070
- key: "getElement",
1071
- value: function getElement() {
1072
- try {
1073
- var node = this.getNode();
1074
- var element = (0, import_react_from_dom.default)(node);
1075
- if (!element || !React.isValidElement(element)) {
1076
- throw new Error("Could not convert the src to a React element");
1077
- }
1078
- this.setState({
1079
- element: element,
1080
- status: STATUS.READY
1081
- });
1082
- } catch (error) {
1083
- this.handleError(new Error(error.message));
1084
- }
1085
- }
1086
- },
1087
- {
1088
- key: "getNode",
1089
- value: function getNode() {
1090
- var _this_props = this.props, description = _this_props.description, title = _this_props.title;
1091
- try {
1092
- var svgText = this.processSVG();
1093
- var node = (0, import_react_from_dom.default)(svgText, {
1094
- nodeOnly: true
1095
- });
1096
- if (!node || !_instanceof(node, SVGSVGElement)) {
1097
- throw new Error("Could not convert the src to a DOM Node");
1098
- }
1099
- var svg = this.updateSVGAttributes(node);
1100
- if (description) {
1101
- var originalDesc = svg.querySelector("desc");
1102
- if (originalDesc && originalDesc.parentNode) {
1103
- originalDesc.parentNode.removeChild(originalDesc);
1104
- }
1105
- var descElement = document.createElementNS("http://www.w3.org/2000/svg", "desc");
1106
- descElement.innerHTML = description;
1107
- svg.prepend(descElement);
1108
- }
1109
- if (typeof title !== "undefined") {
1110
- var originalTitle = svg.querySelector("title");
1111
- if (originalTitle && originalTitle.parentNode) {
1112
- originalTitle.parentNode.removeChild(originalTitle);
1113
- }
1114
- if (title) {
1115
- var titleElement = document.createElementNS("http://www.w3.org/2000/svg", "title");
1116
- titleElement.innerHTML = title;
1117
- svg.prepend(titleElement);
1118
- }
1119
- }
1120
- return svg;
1121
- } catch (error) {
1122
- return this.handleError(error);
1123
- }
1124
- }
1125
- },
1126
- {
1127
- key: "load",
1128
- value: function load() {
1129
- if (this.isActive) {
1130
- var _this = this;
1131
- this.setState({
1132
- content: "",
1133
- element: null,
1134
- isCached: false,
1135
- status: STATUS.LOADING
1136
- }, /*#__PURE__*/ _async_to_generator(function() {
1137
- var _this_props, cacheRequests, fetchOptions, src, dataURI, inlineSrc, content, error;
1138
- return _ts_generator(this, function(_state) {
1139
- switch(_state.label){
1140
- case 0:
1141
- _this_props = _this.props, cacheRequests = _this_props.cacheRequests, fetchOptions = _this_props.fetchOptions, src = _this_props.src;
1142
- dataURI = src.match(RegExp("^data:image\\/svg[^,]*?(;base64)?,(.*)", "u"));
1143
- if (dataURI) {
1144
- inlineSrc = dataURI[1] ? window.atob(dataURI[2]) : decodeURIComponent(dataURI[2]);
1145
- } else if (src.includes("<svg")) {
1146
- inlineSrc = src;
1147
- }
1148
- if (inlineSrc) {
1149
- _this.handleLoad(inlineSrc);
1150
- return [
1151
- 2
1152
- ];
1153
- }
1154
- _state.label = 1;
1155
- case 1:
1156
- _state.trys.push([
1157
- 1,
1158
- 6,
1159
- ,
1160
- 7
1161
- ]);
1162
- if (!cacheRequests) return [
1163
- 3,
1164
- 3
1165
- ];
1166
- return [
1167
- 4,
1168
- cacheStore.get(src, fetchOptions)
1169
- ];
1170
- case 2:
1171
- content = _state.sent();
1172
- _this.handleLoad(content, true);
1173
- return [
1174
- 3,
1175
- 5
1176
- ];
1177
- case 3:
1178
- return [
1179
- 4,
1180
- _this.fetchContent()
1181
- ];
1182
- case 4:
1183
- _state.sent();
1184
- _state.label = 5;
1185
- case 5:
1186
- return [
1187
- 3,
1188
- 7
1189
- ];
1190
- case 6:
1191
- error = _state.sent();
1192
- _this.handleError(error);
1193
- return [
1194
- 3,
1195
- 7
1196
- ];
1197
- case 7:
1198
- return [
1199
- 2
1200
- ];
1201
- }
1202
- });
1203
- }));
1204
- }
1205
- }
1206
- },
1207
- {
1208
- key: "processSVG",
1209
- value: function processSVG() {
1210
- var content = this.state.content;
1211
- var preProcessor = this.props.preProcessor;
1212
- if (preProcessor) {
1213
- return preProcessor(content);
1214
- }
1215
- return content;
1216
- }
1217
- },
288
+ const { status } = this.state;
289
+ const { src } = this.props;
290
+ try {
291
+ if (status === STATUS.IDLE) {
292
+ if (!isSupportedEnvironment()) {
293
+ throw new Error("Browser does not support SVG");
294
+ }
295
+ if (!src) {
296
+ throw new Error("Missing src");
297
+ }
298
+ this.load();
299
+ }
300
+ } catch (error) {
301
+ this.handleError(error);
302
+ }
303
+ this.isInitialized = true;
304
+ }
305
+ componentDidUpdate(previousProps, previousState) {
306
+ if (!canUseDOM()) {
307
+ return;
308
+ }
309
+ const { isCached, status } = this.state;
310
+ const { onLoad, src } = this.props;
311
+ if (previousState.status !== STATUS.READY && status === STATUS.READY) {
312
+ if (onLoad) {
313
+ onLoad(src, isCached);
314
+ }
315
+ }
316
+ if (previousProps.src !== src) {
317
+ if (!src) {
318
+ this.handleError(new Error("Missing src"));
319
+ return;
320
+ }
321
+ this.load();
322
+ }
323
+ }
324
+ componentWillUnmount() {
325
+ this.isActive = false;
326
+ }
327
+ getElement() {
328
+ try {
329
+ const node = this.getNode();
330
+ const element = (0, import_react_from_dom.default)(node);
331
+ if (!element || !React.isValidElement(element)) {
332
+ throw new Error("Could not convert the src to a React element");
333
+ }
334
+ this.setState({
335
+ element,
336
+ status: STATUS.READY
337
+ });
338
+ } catch (error) {
339
+ this.handleError(new Error(error.message));
340
+ }
341
+ }
342
+ getNode() {
343
+ const { description, title } = this.props;
344
+ try {
345
+ const svgText = this.processSVG();
346
+ const node = (0, import_react_from_dom.default)(svgText, { nodeOnly: true });
347
+ if (!node || !(node instanceof SVGSVGElement)) {
348
+ throw new Error("Could not convert the src to a DOM Node");
349
+ }
350
+ const svg = this.updateSVGAttributes(node);
351
+ if (description) {
352
+ const originalDesc = svg.querySelector("desc");
353
+ if (originalDesc && originalDesc.parentNode) {
354
+ originalDesc.parentNode.removeChild(originalDesc);
355
+ }
356
+ const descElement = document.createElementNS("http://www.w3.org/2000/svg", "desc");
357
+ descElement.innerHTML = description;
358
+ svg.prepend(descElement);
359
+ }
360
+ if (typeof title !== "undefined") {
361
+ const originalTitle = svg.querySelector("title");
362
+ if (originalTitle && originalTitle.parentNode) {
363
+ originalTitle.parentNode.removeChild(originalTitle);
364
+ }
365
+ if (title) {
366
+ const titleElement = document.createElementNS("http://www.w3.org/2000/svg", "title");
367
+ titleElement.innerHTML = title;
368
+ svg.prepend(titleElement);
369
+ }
370
+ }
371
+ return svg;
372
+ } catch (error) {
373
+ return this.handleError(error);
374
+ }
375
+ }
376
+ load() {
377
+ if (this.isActive) {
378
+ this.setState(
1218
379
  {
1219
- key: "updateSVGAttributes",
1220
- value: function updateSVGAttributes(node) {
1221
- var _this = this;
1222
- var _this_props = this.props, _this_props_baseURL = _this_props.baseURL, baseURL = _this_props_baseURL === void 0 ? "" : _this_props_baseURL, uniquifyIDs = _this_props.uniquifyIDs;
1223
- var replaceableAttributes = [
1224
- "id",
1225
- "href",
1226
- "xlink:href",
1227
- "xlink:role",
1228
- "xlink:arcrole"
1229
- ];
1230
- var linkAttributes = [
1231
- "href",
1232
- "xlink:href"
1233
- ];
1234
- var isDataValue = function(name, value) {
1235
- return linkAttributes.includes(name) && (value ? !value.includes("#") : false);
1236
- };
1237
- if (!uniquifyIDs) {
1238
- return node;
1239
- }
1240
- _to_consumable_array(node.children).forEach(function(d) {
1241
- if (d.attributes && d.attributes.length) {
1242
- var attributes = Object.values(d.attributes).map(function(a) {
1243
- var attribute = a;
1244
- var match = a.value.match(/url\((.*?)\)/);
1245
- if (match && match[1]) {
1246
- attribute.value = a.value.replace(match[0], "url(".concat(baseURL).concat(match[1], "__").concat(_this.hash, ")"));
1247
- }
1248
- return attribute;
1249
- });
1250
- replaceableAttributes.forEach(function(r) {
1251
- var attribute = attributes.find(function(a) {
1252
- return a.name === r;
1253
- });
1254
- if (attribute && !isDataValue(r, attribute.value)) {
1255
- attribute.value = "".concat(attribute.value, "__").concat(_this.hash);
1256
- }
1257
- });
1258
- }
1259
- if (d.children.length) {
1260
- return _this.updateSVGAttributes(d);
1261
- }
1262
- return d;
1263
- });
1264
- return node;
1265
- }
380
+ content: "",
381
+ element: null,
382
+ isCached: false,
383
+ status: STATUS.LOADING
1266
384
  },
1267
- {
1268
- key: "render",
1269
- value: function render() {
1270
- var _this_state = this.state, element = _this_state.element, status = _this_state.status;
1271
- var _this_props = this.props, _this_props_children = _this_props.children, children = _this_props_children === void 0 ? null : _this_props_children, innerRef = _this_props.innerRef, _this_props_loader = _this_props.loader, loader = _this_props_loader === void 0 ? null : _this_props_loader;
1272
- var elementProps = omit(this.props, "baseURL", "cacheRequests", "children", "description", "fetchOptions", "innerRef", "loader", "onError", "onLoad", "preProcessor", "src", "title", "uniqueHash", "uniquifyIDs");
1273
- if (!canUseDOM()) {
1274
- return loader;
1275
- }
1276
- if (element) {
1277
- return React.cloneElement(element, _object_spread({
1278
- ref: innerRef
1279
- }, elementProps));
1280
- }
1281
- if ([
1282
- STATUS.UNSUPPORTED,
1283
- STATUS.FAILED
1284
- ].includes(status)) {
1285
- return children;
1286
- }
1287
- return loader;
385
+ async () => {
386
+ const { cacheRequests, fetchOptions, src } = this.props;
387
+ const dataURI = src.match(/^data:image\/svg[^,]*?(;base64)?,(.*)/u);
388
+ let inlineSrc;
389
+ if (dataURI) {
390
+ inlineSrc = dataURI[1] ? window.atob(dataURI[2]) : decodeURIComponent(dataURI[2]);
391
+ } else if (src.includes("<svg")) {
392
+ inlineSrc = src;
393
+ }
394
+ if (inlineSrc) {
395
+ this.handleLoad(inlineSrc);
396
+ return;
397
+ }
398
+ try {
399
+ if (cacheRequests) {
400
+ const content = await cacheStore.get(src, fetchOptions);
401
+ this.handleLoad(content, true);
402
+ } else {
403
+ await this.fetchContent();
1288
404
  }
405
+ } catch (error) {
406
+ this.handleError(error);
407
+ }
1289
408
  }
1290
- ]);
1291
- return ReactInlineSVG;
1292
- }(React.PureComponent);
409
+ );
410
+ }
411
+ }
412
+ processSVG() {
413
+ const { content } = this.state;
414
+ const { preProcessor } = this.props;
415
+ if (preProcessor) {
416
+ return preProcessor(content);
417
+ }
418
+ return content;
419
+ }
420
+ updateSVGAttributes(node) {
421
+ const { baseURL = "", uniquifyIDs } = this.props;
422
+ const replaceableAttributes = ["id", "href", "xlink:href", "xlink:role", "xlink:arcrole"];
423
+ const linkAttributes = ["href", "xlink:href"];
424
+ const isDataValue = (name, value) => linkAttributes.includes(name) && (value ? !value.includes("#") : false);
425
+ if (!uniquifyIDs) {
426
+ return node;
427
+ }
428
+ [...node.children].forEach((d) => {
429
+ if (d.attributes && d.attributes.length) {
430
+ const attributes = Object.values(d.attributes).map((a) => {
431
+ const attribute = a;
432
+ const match = a.value.match(/url\((.*?)\)/);
433
+ if (match && match[1]) {
434
+ attribute.value = a.value.replace(match[0], `url(${baseURL}${match[1]}__${this.hash})`);
435
+ }
436
+ return attribute;
437
+ });
438
+ replaceableAttributes.forEach((r) => {
439
+ const attribute = attributes.find((a) => a.name === r);
440
+ if (attribute && !isDataValue(r, attribute.value)) {
441
+ attribute.value = `${attribute.value}__${this.hash}`;
442
+ }
443
+ });
444
+ }
445
+ if (d.children.length) {
446
+ return this.updateSVGAttributes(d);
447
+ }
448
+ return d;
449
+ });
450
+ return node;
451
+ }
452
+ render() {
453
+ const { element, status } = this.state;
454
+ const { children = null, innerRef, loader = null } = this.props;
455
+ const elementProps = omit(
456
+ this.props,
457
+ "baseURL",
458
+ "cacheRequests",
459
+ "children",
460
+ "description",
461
+ "fetchOptions",
462
+ "innerRef",
463
+ "loader",
464
+ "onError",
465
+ "onLoad",
466
+ "preProcessor",
467
+ "src",
468
+ "title",
469
+ "uniqueHash",
470
+ "uniquifyIDs"
471
+ );
472
+ if (!canUseDOM()) {
473
+ return loader;
474
+ }
475
+ if (element) {
476
+ return React.cloneElement(element, { ref: innerRef, ...elementProps });
477
+ }
478
+ if ([STATUS.UNSUPPORTED, STATUS.FAILED].includes(status)) {
479
+ return children;
480
+ }
481
+ return loader;
482
+ }
483
+ };
1293
484
  __publicField(ReactInlineSVG, "defaultProps", {
1294
- cacheRequests: true,
1295
- uniquifyIDs: false
485
+ cacheRequests: true,
486
+ uniquifyIDs: false
1296
487
  });
1297
488
  function InlineSVG(props) {
1298
- if (!cacheStore) {
1299
- cacheStore = new CacheStore();
1300
- }
1301
- var loader = props.loader;
1302
- var hasCallback = React.useRef(false);
1303
- var _React_useState = _sliced_to_array(React.useState(cacheStore.isReady), 2), isReady = _React_useState[0], setReady = _React_useState[1];
1304
- React.useEffect(function() {
1305
- if (!hasCallback.current) {
1306
- cacheStore.onReady(function() {
1307
- setReady(true);
1308
- });
1309
- hasCallback.current = true;
1310
- }
1311
- }, []);
1312
- if (!isReady) {
1313
- return loader;
489
+ if (!cacheStore) {
490
+ cacheStore = new CacheStore();
491
+ }
492
+ const { loader } = props;
493
+ const hasCallback = React.useRef(false);
494
+ const [isReady, setReady] = React.useState(cacheStore.isReady);
495
+ React.useEffect(() => {
496
+ if (!hasCallback.current) {
497
+ cacheStore.onReady(() => {
498
+ setReady(true);
499
+ });
500
+ hasCallback.current = true;
1314
501
  }
1315
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ReactInlineSVG, _object_spread({}, props));
502
+ }, []);
503
+ if (!isReady) {
504
+ return loader;
505
+ }
506
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ReactInlineSVG, { ...props });
1316
507
  }
1317
508
  // Annotate the CommonJS export names for ESM import in node:
1318
509
  0 && (module.exports = {
1319
- cacheStore: cacheStore
510
+ cacheStore
1320
511
  });
1321
512
  //# sourceMappingURL=index.js.map