@itcase/storybook-config 1.2.38 → 1.2.39

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.
@@ -1,1430 +1,114 @@
1
1
  import { jsx, jsxs } from 'react/jsx-runtime';
2
2
  import * as React from 'react';
3
- import React__default, { useState, useEffect, useReducer, useRef, useCallback, isValidElement, cloneElement, useMemo, createContext, useContext, memo, useImperativeHandle } from 'react';
3
+ import React__default, { useEffect, useContext, useState, useRef, createContext, useReducer, useCallback, isValidElement, cloneElement, memo, useMemo, useImperativeHandle } from 'react';
4
4
  import camelCase from 'lodash/camelCase';
5
5
  import castArray from 'lodash/castArray';
6
6
  import upperFirst from 'lodash/upperFirst';
7
- import { axiosInstanceITCase, formatURL } from '@itcase/common';
7
+ import { formatURL, axiosInstanceITCase } from '@itcase/common';
8
8
  import maxBy from 'lodash/maxBy';
9
9
 
10
10
  function r(e){var t,f,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=" "),n+=f);}else for(f in e)e[f]&&(n&&(n+=" "),n+=f);return n}function clsx(){for(var e,t,f=0,n="",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=" "),n+=t);return n}
11
11
 
12
- // src/index.ts
12
+ const byteToHex = [];
13
+ for (let i = 0; i < 256; ++i) {
14
+ byteToHex.push((i + 0x100).toString(16).slice(1));
15
+ }
16
+ function unsafeStringify(arr, offset = 0) {
17
+ return (byteToHex[arr[offset + 0]] +
18
+ byteToHex[arr[offset + 1]] +
19
+ byteToHex[arr[offset + 2]] +
20
+ byteToHex[arr[offset + 3]] +
21
+ '-' +
22
+ byteToHex[arr[offset + 4]] +
23
+ byteToHex[arr[offset + 5]] +
24
+ '-' +
25
+ byteToHex[arr[offset + 6]] +
26
+ byteToHex[arr[offset + 7]] +
27
+ '-' +
28
+ byteToHex[arr[offset + 8]] +
29
+ byteToHex[arr[offset + 9]] +
30
+ '-' +
31
+ byteToHex[arr[offset + 10]] +
32
+ byteToHex[arr[offset + 11]] +
33
+ byteToHex[arr[offset + 12]] +
34
+ byteToHex[arr[offset + 13]] +
35
+ byteToHex[arr[offset + 14]] +
36
+ byteToHex[arr[offset + 15]]).toLowerCase();
37
+ }
13
38
 
14
- // src/helpers.ts
15
- var styleToObject = (input) => {
16
- if (typeof input !== "string") {
17
- return {};
18
- }
19
- return input.split(/ ?; ?/).reduce((acc, item) => {
20
- const [key, value] = item.split(/ ?: ?/).map((d, index) => index === 0 ? d.replace(/\s+/g, "") : d.trim());
21
- if (key && value) {
22
- const nextKey = key.replace(/(\w)-(\w)/g, (_$0, $1, $2) => `${$1}${$2.toUpperCase()}`);
23
- let nextValue = value.trim();
24
- if (!Number.isNaN(Number(value))) {
25
- nextValue = Number(value);
26
- }
27
- acc[key.startsWith("-") ? key : nextKey] = nextValue;
39
+ let getRandomValues;
40
+ const rnds8 = new Uint8Array(16);
41
+ function rng() {
42
+ if (!getRandomValues) {
43
+ if (typeof crypto === 'undefined' || !crypto.getRandomValues) {
44
+ throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
45
+ }
46
+ getRandomValues = crypto.getRandomValues.bind(crypto);
28
47
  }
29
- return acc;
30
- }, {});
31
- };
32
- function randomString$1(length = 6) {
33
- const characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
34
- let result = "";
35
- for (let index = length; index > 0; --index) {
36
- result += characters[Math.round(Math.random() * (characters.length - 1))];
37
- }
38
- return result;
48
+ return getRandomValues(rnds8);
39
49
  }
40
- var noTextChildNodes = [
41
- "br",
42
- "col",
43
- "colgroup",
44
- "dl",
45
- "hr",
46
- "iframe",
47
- "img",
48
- "input",
49
- "link",
50
- "menuitem",
51
- "meta",
52
- "ol",
53
- "param",
54
- "select",
55
- "table",
56
- "tbody",
57
- "tfoot",
58
- "thead",
59
- "tr",
60
- "ul",
61
- "wbr"
62
- ];
63
- var possibleStandardNames = {
64
- // HTML
65
- "accept-charset": "acceptCharset",
66
- acceptcharset: "acceptCharset",
67
- accesskey: "accessKey",
68
- allowfullscreen: "allowFullScreen",
69
- autocapitalize: "autoCapitalize",
70
- autocomplete: "autoComplete",
71
- autocorrect: "autoCorrect",
72
- autofocus: "autoFocus",
73
- autoplay: "autoPlay",
74
- autosave: "autoSave",
75
- cellpadding: "cellPadding",
76
- cellspacing: "cellSpacing",
77
- charset: "charSet",
78
- class: "className",
79
- classid: "classID",
80
- classname: "className",
81
- colspan: "colSpan",
82
- contenteditable: "contentEditable",
83
- contextmenu: "contextMenu",
84
- controlslist: "controlsList",
85
- crossorigin: "crossOrigin",
86
- dangerouslysetinnerhtml: "dangerouslySetInnerHTML",
87
- datetime: "dateTime",
88
- defaultchecked: "defaultChecked",
89
- defaultvalue: "defaultValue",
90
- enctype: "encType",
91
- for: "htmlFor",
92
- formmethod: "formMethod",
93
- formaction: "formAction",
94
- formenctype: "formEncType",
95
- formnovalidate: "formNoValidate",
96
- formtarget: "formTarget",
97
- frameborder: "frameBorder",
98
- hreflang: "hrefLang",
99
- htmlfor: "htmlFor",
100
- httpequiv: "httpEquiv",
101
- "http-equiv": "httpEquiv",
102
- icon: "icon",
103
- innerhtml: "innerHTML",
104
- inputmode: "inputMode",
105
- itemid: "itemID",
106
- itemprop: "itemProp",
107
- itemref: "itemRef",
108
- itemscope: "itemScope",
109
- itemtype: "itemType",
110
- keyparams: "keyParams",
111
- keytype: "keyType",
112
- marginwidth: "marginWidth",
113
- marginheight: "marginHeight",
114
- maxlength: "maxLength",
115
- mediagroup: "mediaGroup",
116
- minlength: "minLength",
117
- nomodule: "noModule",
118
- novalidate: "noValidate",
119
- playsinline: "playsInline",
120
- radiogroup: "radioGroup",
121
- readonly: "readOnly",
122
- referrerpolicy: "referrerPolicy",
123
- rowspan: "rowSpan",
124
- spellcheck: "spellCheck",
125
- srcdoc: "srcDoc",
126
- srclang: "srcLang",
127
- srcset: "srcSet",
128
- tabindex: "tabIndex",
129
- typemustmatch: "typeMustMatch",
130
- usemap: "useMap",
131
- // SVG
132
- accentheight: "accentHeight",
133
- "accent-height": "accentHeight",
134
- alignmentbaseline: "alignmentBaseline",
135
- "alignment-baseline": "alignmentBaseline",
136
- allowreorder: "allowReorder",
137
- arabicform: "arabicForm",
138
- "arabic-form": "arabicForm",
139
- attributename: "attributeName",
140
- attributetype: "attributeType",
141
- autoreverse: "autoReverse",
142
- basefrequency: "baseFrequency",
143
- baselineshift: "baselineShift",
144
- "baseline-shift": "baselineShift",
145
- baseprofile: "baseProfile",
146
- calcmode: "calcMode",
147
- capheight: "capHeight",
148
- "cap-height": "capHeight",
149
- clippath: "clipPath",
150
- "clip-path": "clipPath",
151
- clippathunits: "clipPathUnits",
152
- cliprule: "clipRule",
153
- "clip-rule": "clipRule",
154
- colorinterpolation: "colorInterpolation",
155
- "color-interpolation": "colorInterpolation",
156
- colorinterpolationfilters: "colorInterpolationFilters",
157
- "color-interpolation-filters": "colorInterpolationFilters",
158
- colorprofile: "colorProfile",
159
- "color-profile": "colorProfile",
160
- colorrendering: "colorRendering",
161
- "color-rendering": "colorRendering",
162
- contentscripttype: "contentScriptType",
163
- contentstyletype: "contentStyleType",
164
- diffuseconstant: "diffuseConstant",
165
- dominantbaseline: "dominantBaseline",
166
- "dominant-baseline": "dominantBaseline",
167
- edgemode: "edgeMode",
168
- enablebackground: "enableBackground",
169
- "enable-background": "enableBackground",
170
- externalresourcesrequired: "externalResourcesRequired",
171
- fillopacity: "fillOpacity",
172
- "fill-opacity": "fillOpacity",
173
- fillrule: "fillRule",
174
- "fill-rule": "fillRule",
175
- filterres: "filterRes",
176
- filterunits: "filterUnits",
177
- floodopacity: "floodOpacity",
178
- "flood-opacity": "floodOpacity",
179
- floodcolor: "floodColor",
180
- "flood-color": "floodColor",
181
- fontfamily: "fontFamily",
182
- "font-family": "fontFamily",
183
- fontsize: "fontSize",
184
- "font-size": "fontSize",
185
- fontsizeadjust: "fontSizeAdjust",
186
- "font-size-adjust": "fontSizeAdjust",
187
- fontstretch: "fontStretch",
188
- "font-stretch": "fontStretch",
189
- fontstyle: "fontStyle",
190
- "font-style": "fontStyle",
191
- fontvariant: "fontVariant",
192
- "font-variant": "fontVariant",
193
- fontweight: "fontWeight",
194
- "font-weight": "fontWeight",
195
- glyphname: "glyphName",
196
- "glyph-name": "glyphName",
197
- glyphorientationhorizontal: "glyphOrientationHorizontal",
198
- "glyph-orientation-horizontal": "glyphOrientationHorizontal",
199
- glyphorientationvertical: "glyphOrientationVertical",
200
- "glyph-orientation-vertical": "glyphOrientationVertical",
201
- glyphref: "glyphRef",
202
- gradienttransform: "gradientTransform",
203
- gradientunits: "gradientUnits",
204
- horizadvx: "horizAdvX",
205
- "horiz-adv-x": "horizAdvX",
206
- horizoriginx: "horizOriginX",
207
- "horiz-origin-x": "horizOriginX",
208
- imagerendering: "imageRendering",
209
- "image-rendering": "imageRendering",
210
- kernelmatrix: "kernelMatrix",
211
- kernelunitlength: "kernelUnitLength",
212
- keypoints: "keyPoints",
213
- keysplines: "keySplines",
214
- keytimes: "keyTimes",
215
- lengthadjust: "lengthAdjust",
216
- letterspacing: "letterSpacing",
217
- "letter-spacing": "letterSpacing",
218
- lightingcolor: "lightingColor",
219
- "lighting-color": "lightingColor",
220
- limitingconeangle: "limitingConeAngle",
221
- markerend: "markerEnd",
222
- "marker-end": "markerEnd",
223
- markerheight: "markerHeight",
224
- markermid: "markerMid",
225
- "marker-mid": "markerMid",
226
- markerstart: "markerStart",
227
- "marker-start": "markerStart",
228
- markerunits: "markerUnits",
229
- markerwidth: "markerWidth",
230
- maskcontentunits: "maskContentUnits",
231
- maskunits: "maskUnits",
232
- numoctaves: "numOctaves",
233
- overlineposition: "overlinePosition",
234
- "overline-position": "overlinePosition",
235
- overlinethickness: "overlineThickness",
236
- "overline-thickness": "overlineThickness",
237
- paintorder: "paintOrder",
238
- "paint-order": "paintOrder",
239
- "panose-1": "panose1",
240
- pathlength: "pathLength",
241
- patterncontentunits: "patternContentUnits",
242
- patterntransform: "patternTransform",
243
- patternunits: "patternUnits",
244
- pointerevents: "pointerEvents",
245
- "pointer-events": "pointerEvents",
246
- pointsatx: "pointsAtX",
247
- pointsaty: "pointsAtY",
248
- pointsatz: "pointsAtZ",
249
- preservealpha: "preserveAlpha",
250
- preserveaspectratio: "preserveAspectRatio",
251
- primitiveunits: "primitiveUnits",
252
- refx: "refX",
253
- refy: "refY",
254
- renderingintent: "renderingIntent",
255
- "rendering-intent": "renderingIntent",
256
- repeatcount: "repeatCount",
257
- repeatdur: "repeatDur",
258
- requiredextensions: "requiredExtensions",
259
- requiredfeatures: "requiredFeatures",
260
- shaperendering: "shapeRendering",
261
- "shape-rendering": "shapeRendering",
262
- specularconstant: "specularConstant",
263
- specularexponent: "specularExponent",
264
- spreadmethod: "spreadMethod",
265
- startoffset: "startOffset",
266
- stddeviation: "stdDeviation",
267
- stitchtiles: "stitchTiles",
268
- stopcolor: "stopColor",
269
- "stop-color": "stopColor",
270
- stopopacity: "stopOpacity",
271
- "stop-opacity": "stopOpacity",
272
- strikethroughposition: "strikethroughPosition",
273
- "strikethrough-position": "strikethroughPosition",
274
- strikethroughthickness: "strikethroughThickness",
275
- "strikethrough-thickness": "strikethroughThickness",
276
- strokedasharray: "strokeDasharray",
277
- "stroke-dasharray": "strokeDasharray",
278
- strokedashoffset: "strokeDashoffset",
279
- "stroke-dashoffset": "strokeDashoffset",
280
- strokelinecap: "strokeLinecap",
281
- "stroke-linecap": "strokeLinecap",
282
- strokelinejoin: "strokeLinejoin",
283
- "stroke-linejoin": "strokeLinejoin",
284
- strokemiterlimit: "strokeMiterlimit",
285
- "stroke-miterlimit": "strokeMiterlimit",
286
- strokewidth: "strokeWidth",
287
- "stroke-width": "strokeWidth",
288
- strokeopacity: "strokeOpacity",
289
- "stroke-opacity": "strokeOpacity",
290
- suppresscontenteditablewarning: "suppressContentEditableWarning",
291
- suppresshydrationwarning: "suppressHydrationWarning",
292
- surfacescale: "surfaceScale",
293
- systemlanguage: "systemLanguage",
294
- tablevalues: "tableValues",
295
- targetx: "targetX",
296
- targety: "targetY",
297
- textanchor: "textAnchor",
298
- "text-anchor": "textAnchor",
299
- textdecoration: "textDecoration",
300
- "text-decoration": "textDecoration",
301
- textlength: "textLength",
302
- textrendering: "textRendering",
303
- "text-rendering": "textRendering",
304
- underlineposition: "underlinePosition",
305
- "underline-position": "underlinePosition",
306
- underlinethickness: "underlineThickness",
307
- "underline-thickness": "underlineThickness",
308
- unicodebidi: "unicodeBidi",
309
- "unicode-bidi": "unicodeBidi",
310
- unicoderange: "unicodeRange",
311
- "unicode-range": "unicodeRange",
312
- unitsperem: "unitsPerEm",
313
- "units-per-em": "unitsPerEm",
314
- unselectable: "unselectable",
315
- valphabetic: "vAlphabetic",
316
- "v-alphabetic": "vAlphabetic",
317
- vectoreffect: "vectorEffect",
318
- "vector-effect": "vectorEffect",
319
- vertadvy: "vertAdvY",
320
- "vert-adv-y": "vertAdvY",
321
- vertoriginx: "vertOriginX",
322
- "vert-origin-x": "vertOriginX",
323
- vertoriginy: "vertOriginY",
324
- "vert-origin-y": "vertOriginY",
325
- vhanging: "vHanging",
326
- "v-hanging": "vHanging",
327
- videographic: "vIdeographic",
328
- "v-ideographic": "vIdeographic",
329
- viewbox: "viewBox",
330
- viewtarget: "viewTarget",
331
- vmathematical: "vMathematical",
332
- "v-mathematical": "vMathematical",
333
- wordspacing: "wordSpacing",
334
- "word-spacing": "wordSpacing",
335
- writingmode: "writingMode",
336
- "writing-mode": "writingMode",
337
- xchannelselector: "xChannelSelector",
338
- xheight: "xHeight",
339
- "x-height": "xHeight",
340
- xlinkactuate: "xlinkActuate",
341
- "xlink:actuate": "xlinkActuate",
342
- xlinkarcrole: "xlinkArcrole",
343
- "xlink:arcrole": "xlinkArcrole",
344
- xlinkhref: "xlinkHref",
345
- "xlink:href": "xlinkHref",
346
- xlinkrole: "xlinkRole",
347
- "xlink:role": "xlinkRole",
348
- xlinkshow: "xlinkShow",
349
- "xlink:show": "xlinkShow",
350
- xlinktitle: "xlinkTitle",
351
- "xlink:title": "xlinkTitle",
352
- xlinktype: "xlinkType",
353
- "xlink:type": "xlinkType",
354
- xmlbase: "xmlBase",
355
- "xml:base": "xmlBase",
356
- xmllang: "xmlLang",
357
- "xml:lang": "xmlLang",
358
- "xml:space": "xmlSpace",
359
- xmlnsxlink: "xmlnsXlink",
360
- "xmlns:xlink": "xmlnsXlink",
361
- xmlspace: "xmlSpace",
362
- ychannelselector: "yChannelSelector",
363
- zoomandpan: "zoomAndPan",
364
- // event handlers
365
- onblur: "onBlur",
366
- onchange: "onChange",
367
- onclick: "onClick",
368
- oncontextmenu: "onContextMenu",
369
- ondoubleclick: "onDoubleClick",
370
- ondrag: "onDrag",
371
- ondragend: "onDragEnd",
372
- ondragenter: "onDragEnter",
373
- ondragexit: "onDragExit",
374
- ondragleave: "onDragLeave",
375
- ondragover: "onDragOver",
376
- ondragstart: "onDragStart",
377
- ondrop: "onDrop",
378
- onerror: "onError",
379
- onfocus: "onFocus",
380
- oninput: "onInput",
381
- oninvalid: "onInvalid",
382
- onkeydown: "onKeyDown",
383
- onkeypress: "onKeyPress",
384
- onkeyup: "onKeyUp",
385
- onload: "onLoad",
386
- onmousedown: "onMouseDown",
387
- onmouseenter: "onMouseEnter",
388
- onmouseleave: "onMouseLeave",
389
- onmousemove: "onMouseMove",
390
- onmouseout: "onMouseOut",
391
- onmouseover: "onMouseOver",
392
- onmouseup: "onMouseUp",
393
- onscroll: "onScroll",
394
- onsubmit: "onSubmit",
395
- ontouchcancel: "onTouchCancel",
396
- ontouchend: "onTouchEnd",
397
- ontouchmove: "onTouchMove",
398
- ontouchstart: "onTouchStart",
399
- onwheel: "onWheel"
400
- };
401
50
 
402
- // src/index.ts
403
- function getReactNode(node, options) {
404
- const { key, level, ...rest } = options;
405
- switch (node.nodeType) {
406
- case 1: {
407
- return React.createElement(
408
- parseName(node.nodeName),
409
- parseAttributes(node, key),
410
- parseChildren(node.childNodes, level, rest)
411
- );
412
- }
413
- case 3: {
414
- const nodeText = node.nodeValue?.toString() ?? "";
415
- if (!rest.allowWhiteSpaces && /^\s+$/.test(nodeText) && !/[\u00A0\u202F]/.test(nodeText)) {
416
- return null;
417
- }
418
- if (!node.parentNode) {
419
- return nodeText;
420
- }
421
- const parentNodeName = node.parentNode.nodeName.toLowerCase();
422
- if (noTextChildNodes.includes(parentNodeName)) {
423
- if (/\S/.test(nodeText)) {
424
- console.warn(
425
- `A textNode is not allowed inside '${parentNodeName}'. Your text "${nodeText}" will be ignored`
426
- );
427
- }
428
- return null;
429
- }
430
- return nodeText;
431
- }
432
- case 8: {
433
- return null;
434
- }
435
- case 11: {
436
- return parseChildren(node.childNodes, level, options);
437
- }
438
- /* c8 ignore next 3 */
439
- default: {
440
- return null;
51
+ const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
52
+ var native = { randomUUID };
53
+
54
+ function _v4(options, buf, offset) {
55
+ options = options || {};
56
+ const rnds = options.random ?? options.rng?.() ?? rng();
57
+ if (rnds.length < 16) {
58
+ throw new Error('Random bytes length must be >= 16');
441
59
  }
442
- }
60
+ rnds[6] = (rnds[6] & 0x0f) | 0x40;
61
+ rnds[8] = (rnds[8] & 0x3f) | 0x80;
62
+ return unsafeStringify(rnds);
443
63
  }
444
- function parseAttributes(node, reactKey) {
445
- const attributes = {
446
- key: reactKey
447
- };
448
- if (node instanceof Element) {
449
- const nodeClassNames = node.getAttribute("class");
450
- if (nodeClassNames) {
451
- attributes.className = nodeClassNames;
64
+ function v4(options, buf, offset) {
65
+ if (native.randomUUID && true && !options) {
66
+ return native.randomUUID();
452
67
  }
453
- [...node.attributes].forEach((d) => {
454
- switch (d.name) {
455
- // this is manually handled above, so break;
456
- case "class":
457
- break;
458
- case "style":
459
- attributes[d.name] = styleToObject(d.value);
460
- break;
461
- case "allowfullscreen":
462
- case "allowpaymentrequest":
463
- case "async":
464
- case "autofocus":
465
- case "autoplay":
466
- case "checked":
467
- case "controls":
468
- case "default":
469
- case "defer":
470
- case "disabled":
471
- case "formnovalidate":
472
- case "hidden":
473
- case "ismap":
474
- case "itemscope":
475
- case "loop":
476
- case "multiple":
477
- case "muted":
478
- case "nomodule":
479
- case "novalidate":
480
- case "open":
481
- case "readonly":
482
- case "required":
483
- case "reversed":
484
- case "selected":
485
- case "typemustmatch":
486
- attributes[possibleStandardNames[d.name] || d.name] = true;
487
- break;
488
- default:
489
- attributes[possibleStandardNames[d.name] || d.name] = d.value;
490
- }
491
- });
492
- }
493
- return attributes;
494
- }
495
- function parseChildren(childNodeList, level, options) {
496
- const children = [...childNodeList].map(
497
- (node, index) => convertFromNode(node, {
498
- ...options,
499
- index,
500
- level: level + 1
501
- })
502
- ).filter(Boolean);
503
- if (!children.length) {
504
- return null;
505
- }
506
- return children;
507
- }
508
- function parseName(nodeName) {
509
- if (/[a-z]+[A-Z]+[a-z]+/.test(nodeName)) {
510
- return nodeName;
511
- }
512
- return nodeName.toLowerCase();
513
- }
514
- function convert(input, options = {}) {
515
- if (typeof input === "string") {
516
- return convertFromString(input, options);
517
- }
518
- if (input instanceof Node) {
519
- return convertFromNode(input, options);
520
- }
521
- return null;
522
- }
523
- function convertFromNode(input, options = {}) {
524
- if (!input || !(input instanceof Node)) {
525
- return null;
526
- }
527
- const { actions = [], index = 0, level = 0, randomKey } = options;
528
- let node = input;
529
- let key = `${level}-${index}`;
530
- const result = [];
531
- if (randomKey && level === 0) {
532
- key = `${randomString$1()}-${key}`;
533
- }
534
- if (Array.isArray(actions)) {
535
- actions.forEach((action) => {
536
- if (action.condition(node, key, level)) {
537
- if (typeof action.pre === "function") {
538
- node = action.pre(node, key, level);
539
- if (!(node instanceof Node)) {
540
- node = input;
541
- if (process.env.NODE_ENV !== "production") {
542
- console.warn(
543
- "The `pre` method always must return a valid DomNode (instanceof Node) - your modification will be ignored (Hint: if you want to render a React-component, use the `post` method instead)"
544
- );
545
- }
546
- }
547
- }
548
- if (typeof action.post === "function") {
549
- result.push(action.post(node, key, level));
550
- }
551
- }
552
- });
553
- }
554
- if (result.length) {
555
- return result;
556
- }
557
- return getReactNode(node, { key, level, ...options });
68
+ return _v4(options);
558
69
  }
559
- function convertFromString(input, options = {}) {
560
- if (!input || typeof input !== "string") {
561
- return null;
562
- }
563
- const {
564
- includeAllNodes = false,
565
- nodeOnly = false,
566
- selector = "body > *",
567
- type = "text/html"
568
- } = options;
569
- try {
570
- const parser = new DOMParser();
571
- const document = parser.parseFromString(input, type);
572
- if (includeAllNodes) {
573
- const { childNodes } = document.body;
574
- if (nodeOnly) {
575
- return childNodes;
576
- }
577
- return [...childNodes].map((node2) => convertFromNode(node2, options));
578
- }
579
- const node = document.querySelector(selector) || document.body.childNodes[0];
580
- if (!(node instanceof Node)) {
581
- throw new TypeError("Error parsing input");
582
- }
583
- if (nodeOnly) {
584
- return node;
585
- }
586
- return convertFromNode(node, options);
587
- } catch (error) {
588
- if (process.env.NODE_ENV !== "production") {
589
- console.error(error);
590
- }
591
- }
592
- return null;
70
+
71
+ function getDefaultExportFromCjs (x) {
72
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
593
73
  }
594
74
 
595
- var __defProp = Object.defineProperty;
596
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
597
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
75
+ var cssMediaquery = {};
598
76
 
599
- // src/config.ts
600
- var CACHE_NAME = "react-inlinesvg";
601
- var CACHE_MAX_RETRIES = 10;
602
- var STATUS = {
603
- IDLE: "idle",
604
- LOADING: "loading",
605
- LOADED: "loaded",
606
- FAILED: "failed",
607
- READY: "ready",
608
- UNSUPPORTED: "unsupported"
609
- };
77
+ /*
78
+ Copyright (c) 2014, Yahoo! Inc. All rights reserved.
79
+ Copyrights licensed under the New BSD License.
80
+ See the accompanying LICENSE file for terms.
81
+ */
610
82
 
611
- // src/modules/helpers.ts
612
- function randomCharacter(character) {
613
- return character[Math.floor(Math.random() * character.length)];
614
- }
615
- function canUseDOM() {
616
- return !!(typeof window !== "undefined" && window.document?.createElement);
617
- }
618
- function isSupportedEnvironment() {
619
- return supportsInlineSVG() && typeof window !== "undefined" && window !== null;
620
- }
621
- function omit(input, ...filter) {
622
- const output = {};
623
- for (const key in input) {
624
- if ({}.hasOwnProperty.call(input, key)) {
625
- if (!filter.includes(key)) {
626
- output[key] = input[key];
627
- }
628
- }
629
- }
630
- return output;
631
- }
632
- function randomString(length) {
633
- const letters = "abcdefghijklmnopqrstuvwxyz";
634
- const numbers = "1234567890";
635
- const charset = `${letters}${letters.toUpperCase()}${numbers}`;
636
- let R = "";
637
- for (let index = 0; index < length; index++) {
638
- R += randomCharacter(charset);
639
- }
640
- return R;
641
- }
642
- async function request(url, options) {
643
- const response = await fetch(url, options);
644
- const contentType = response.headers.get("content-type");
645
- const [fileType] = (contentType ?? "").split(/ ?; ?/);
646
- if (response.status > 299) {
647
- throw new Error("Not found");
648
- }
649
- if (!["image/svg+xml", "text/plain"].some((d) => fileType.includes(d))) {
650
- throw new Error(`Content type isn't valid: ${fileType}`);
651
- }
652
- return response.text();
653
- }
654
- function sleep(seconds = 1) {
655
- return new Promise((resolve) => {
656
- setTimeout(resolve, seconds * 1e3);
657
- });
658
- }
659
- function supportsInlineSVG() {
660
- if (!document) {
661
- return false;
662
- }
663
- const div = document.createElement("div");
664
- div.innerHTML = "<svg />";
665
- const svg = div.firstChild;
666
- return !!svg && svg.namespaceURI === "http://www.w3.org/2000/svg";
667
- }
83
+ var hasRequiredCssMediaquery;
668
84
 
669
- // src/modules/cache.ts
670
- var CacheStore = class {
671
- constructor() {
672
- __publicField(this, "cacheApi");
673
- __publicField(this, "cacheStore");
674
- __publicField(this, "subscribers", []);
675
- __publicField(this, "isReady", false);
676
- this.cacheStore = /* @__PURE__ */ new Map();
677
- let cacheName = CACHE_NAME;
678
- let usePersistentCache = false;
679
- if (canUseDOM()) {
680
- cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;
681
- usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE && "caches" in window;
682
- }
683
- if (usePersistentCache) {
684
- caches.open(cacheName).then((cache) => {
685
- this.cacheApi = cache;
686
- }).catch((error) => {
687
- console.error(`Failed to open cache: ${error.message}`);
688
- this.cacheApi = void 0;
689
- }).finally(() => {
690
- this.isReady = true;
691
- const callbacks = [...this.subscribers];
692
- this.subscribers.length = 0;
693
- callbacks.forEach((callback) => {
694
- try {
695
- callback();
696
- } catch (error) {
697
- console.error(`Error in CacheStore subscriber callback: ${error.message}`);
698
- }
699
- });
700
- });
701
- } else {
702
- this.isReady = true;
703
- }
704
- }
705
- onReady(callback) {
706
- if (this.isReady) {
707
- callback();
708
- } else {
709
- this.subscribers.push(callback);
710
- }
711
- }
712
- async get(url, fetchOptions) {
713
- await (this.cacheApi ? this.fetchAndAddToPersistentCache(url, fetchOptions) : this.fetchAndAddToInternalCache(url, fetchOptions));
714
- return this.cacheStore.get(url)?.content ?? "";
715
- }
716
- set(url, data) {
717
- this.cacheStore.set(url, data);
718
- }
719
- isCached(url) {
720
- return this.cacheStore.get(url)?.status === STATUS.LOADED;
721
- }
722
- async fetchAndAddToInternalCache(url, fetchOptions) {
723
- const cache = this.cacheStore.get(url);
724
- if (cache?.status === STATUS.LOADING) {
725
- await this.handleLoading(url, async () => {
726
- this.cacheStore.set(url, { content: "", status: STATUS.IDLE });
727
- await this.fetchAndAddToInternalCache(url, fetchOptions);
728
- });
729
- return;
730
- }
731
- if (!cache?.content) {
732
- this.cacheStore.set(url, { content: "", status: STATUS.LOADING });
733
- try {
734
- const content = await request(url, fetchOptions);
735
- this.cacheStore.set(url, { content, status: STATUS.LOADED });
736
- } catch (error) {
737
- this.cacheStore.set(url, { content: "", status: STATUS.FAILED });
738
- throw error;
739
- }
740
- }
741
- }
742
- async fetchAndAddToPersistentCache(url, fetchOptions) {
743
- const cache = this.cacheStore.get(url);
744
- if (cache?.status === STATUS.LOADED) {
745
- return;
746
- }
747
- if (cache?.status === STATUS.LOADING) {
748
- await this.handleLoading(url, async () => {
749
- this.cacheStore.set(url, { content: "", status: STATUS.IDLE });
750
- await this.fetchAndAddToPersistentCache(url, fetchOptions);
751
- });
752
- return;
753
- }
754
- this.cacheStore.set(url, { content: "", status: STATUS.LOADING });
755
- const data = await this.cacheApi?.match(url);
756
- if (data) {
757
- const content = await data.text();
758
- this.cacheStore.set(url, { content, status: STATUS.LOADED });
759
- return;
760
- }
761
- try {
762
- await this.cacheApi?.add(new Request(url, fetchOptions));
763
- const response = await this.cacheApi?.match(url);
764
- const content = await response?.text() ?? "";
765
- this.cacheStore.set(url, { content, status: STATUS.LOADED });
766
- } catch (error) {
767
- this.cacheStore.set(url, { content: "", status: STATUS.FAILED });
768
- throw error;
769
- }
770
- }
771
- async handleLoading(url, callback) {
772
- for (let retryCount = 0; retryCount < CACHE_MAX_RETRIES; retryCount++) {
773
- if (this.cacheStore.get(url)?.status !== STATUS.LOADING) {
774
- return;
775
- }
776
- await sleep(0.1);
777
- }
778
- await callback();
779
- }
780
- keys() {
781
- return [...this.cacheStore.keys()];
782
- }
783
- data() {
784
- return [...this.cacheStore.entries()].map(([key, value]) => ({ [key]: value }));
785
- }
786
- async delete(url) {
787
- if (this.cacheApi) {
788
- await this.cacheApi.delete(url);
789
- }
790
- this.cacheStore.delete(url);
791
- }
792
- async clear() {
793
- if (this.cacheApi) {
794
- const keys = await this.cacheApi.keys();
795
- await Promise.allSettled(keys.map((key) => this.cacheApi.delete(key)));
796
- }
797
- this.cacheStore.clear();
798
- }
799
- };
800
- function usePrevious(state) {
801
- const ref = useRef(void 0);
802
- useEffect(() => {
803
- ref.current = state;
804
- });
805
- return ref.current;
806
- }
807
- function getNode(options) {
808
- const {
809
- baseURL,
810
- content,
811
- description,
812
- handleError,
813
- hash,
814
- preProcessor,
815
- title,
816
- uniquifyIDs = false
817
- } = options;
818
- try {
819
- const svgText = processSVG(content, preProcessor);
820
- const node = convert(svgText, { nodeOnly: true });
821
- if (!node || !(node instanceof SVGSVGElement)) {
822
- throw new Error("Could not convert the src to a DOM Node");
823
- }
824
- const svg = updateSVGAttributes(node, { baseURL, hash, uniquifyIDs });
825
- if (description) {
826
- const originalDesc = svg.querySelector("desc");
827
- if (originalDesc?.parentNode) {
828
- originalDesc.parentNode.removeChild(originalDesc);
829
- }
830
- const descElement = document.createElementNS("http://www.w3.org/2000/svg", "desc");
831
- descElement.innerHTML = description;
832
- svg.prepend(descElement);
833
- }
834
- if (typeof title !== "undefined") {
835
- const originalTitle = svg.querySelector("title");
836
- if (originalTitle?.parentNode) {
837
- originalTitle.parentNode.removeChild(originalTitle);
838
- }
839
- if (title) {
840
- const titleElement = document.createElementNS("http://www.w3.org/2000/svg", "title");
841
- titleElement.innerHTML = title;
842
- svg.prepend(titleElement);
843
- }
844
- }
845
- return svg;
846
- } catch (error) {
847
- return handleError(error);
848
- }
849
- }
850
- function processSVG(content, preProcessor) {
851
- if (preProcessor) {
852
- return preProcessor(content);
853
- }
854
- return content;
855
- }
856
- function updateSVGAttributes(node, options) {
857
- const { baseURL = "", hash, uniquifyIDs } = options;
858
- const replaceableAttributes = ["id", "href", "xlink:href", "xlink:role", "xlink:arcrole"];
859
- const linkAttributes = ["href", "xlink:href"];
860
- const isDataValue = (name, value) => linkAttributes.includes(name) && (value ? !value.includes("#") : false);
861
- if (!uniquifyIDs) {
862
- return node;
863
- }
864
- [...node.children].forEach((d) => {
865
- if (d.attributes?.length) {
866
- const attributes = Object.values(d.attributes).map((a) => {
867
- const attribute = a;
868
- const match = /url\((.*?)\)/.exec(a.value);
869
- if (match?.[1]) {
870
- attribute.value = a.value.replace(match[0], `url(${baseURL}${match[1]}__${hash})`);
871
- }
872
- return attribute;
873
- });
874
- replaceableAttributes.forEach((r) => {
875
- const attribute = attributes.find((a) => a.name === r);
876
- if (attribute && !isDataValue(r, attribute.value)) {
877
- attribute.value = `${attribute.value}__${hash}`;
878
- }
879
- });
880
- }
881
- if (d.children.length) {
882
- return updateSVGAttributes(d, options);
883
- }
884
- return d;
885
- });
886
- return node;
887
- }
85
+ function requireCssMediaquery () {
86
+ if (hasRequiredCssMediaquery) return cssMediaquery;
87
+ hasRequiredCssMediaquery = 1;
888
88
 
889
- // src/index.tsx
890
- var cacheStore;
891
- function ReactInlineSVG(props) {
892
- const {
893
- cacheRequests = true,
894
- children = null,
895
- description,
896
- fetchOptions,
897
- innerRef,
898
- loader = null,
899
- onError,
900
- onLoad,
901
- src,
902
- title,
903
- uniqueHash
904
- } = props;
905
- const [state, setState] = useReducer(
906
- (previousState2, nextState) => ({
907
- ...previousState2,
908
- ...nextState
909
- }),
910
- {
911
- content: "",
912
- element: null,
913
- isCached: cacheRequests && cacheStore.isCached(props.src),
914
- status: STATUS.IDLE
915
- }
916
- );
917
- const { content, element, isCached, status } = state;
918
- const previousProps = usePrevious(props);
919
- const previousState = usePrevious(state);
920
- const hash = useRef(uniqueHash ?? randomString(8));
921
- const isActive = useRef(false);
922
- const isInitialized = useRef(false);
923
- const handleError = useCallback(
924
- (error) => {
925
- if (isActive.current) {
926
- setState({
927
- status: error.message === "Browser does not support SVG" ? STATUS.UNSUPPORTED : STATUS.FAILED
928
- });
929
- onError?.(error);
930
- }
931
- },
932
- [onError]
933
- );
934
- const handleLoad = useCallback((loadedContent, hasCache = false) => {
935
- if (isActive.current) {
936
- setState({
937
- content: loadedContent,
938
- isCached: hasCache,
939
- status: STATUS.LOADED
940
- });
941
- }
942
- }, []);
943
- const fetchContent = useCallback(async () => {
944
- const responseContent = await request(src, fetchOptions);
945
- handleLoad(responseContent);
946
- }, [fetchOptions, handleLoad, src]);
947
- const getElement = useCallback(() => {
948
- try {
949
- const node = getNode({ ...props, handleError, hash: hash.current, content });
950
- const convertedElement = convert(node);
951
- if (!convertedElement || !isValidElement(convertedElement)) {
952
- throw new Error("Could not convert the src to a React element");
953
- }
954
- setState({
955
- element: convertedElement,
956
- status: STATUS.READY
957
- });
958
- } catch (error) {
959
- handleError(error);
960
- }
961
- }, [content, handleError, props]);
962
- const getContent = useCallback(async () => {
963
- const dataURI = /^data:image\/svg[^,]*?(;base64)?,(.*)/u.exec(src);
964
- let inlineSrc;
965
- if (dataURI) {
966
- inlineSrc = dataURI[1] ? window.atob(dataURI[2]) : decodeURIComponent(dataURI[2]);
967
- } else if (src.includes("<svg")) {
968
- inlineSrc = src;
969
- }
970
- if (inlineSrc) {
971
- handleLoad(inlineSrc);
972
- return;
973
- }
974
- try {
975
- if (cacheRequests) {
976
- const cachedContent = await cacheStore.get(src, fetchOptions);
977
- handleLoad(cachedContent, true);
978
- } else {
979
- await fetchContent();
980
- }
981
- } catch (error) {
982
- handleError(error);
983
- }
984
- }, [cacheRequests, fetchContent, fetchOptions, handleError, handleLoad, src]);
985
- const load = useCallback(async () => {
986
- if (isActive.current) {
987
- setState({
988
- content: "",
989
- element: null,
990
- isCached: false,
991
- status: STATUS.LOADING
992
- });
993
- }
994
- }, []);
995
- useEffect(
996
- () => {
997
- isActive.current = true;
998
- if (!canUseDOM() || isInitialized.current) {
999
- return void 0;
1000
- }
1001
- try {
1002
- if (status === STATUS.IDLE) {
1003
- if (!isSupportedEnvironment()) {
1004
- throw new Error("Browser does not support SVG");
1005
- }
1006
- if (!src) {
1007
- throw new Error("Missing src");
1008
- }
1009
- load();
1010
- }
1011
- } catch (error) {
1012
- handleError(error);
1013
- }
1014
- isInitialized.current = true;
1015
- return () => {
1016
- isActive.current = false;
1017
- };
1018
- },
1019
- // eslint-disable-next-line react-hooks/exhaustive-deps
1020
- []
1021
- );
1022
- useEffect(() => {
1023
- if (!canUseDOM() || !previousProps) {
1024
- return;
1025
- }
1026
- if (previousProps.src !== src) {
1027
- if (!src) {
1028
- handleError(new Error("Missing src"));
1029
- return;
1030
- }
1031
- load();
1032
- }
1033
- }, [handleError, load, previousProps, src]);
1034
- useEffect(() => {
1035
- if (status === STATUS.LOADED) {
1036
- getElement();
1037
- }
1038
- }, [status, getElement]);
1039
- useEffect(() => {
1040
- if (!canUseDOM() || !previousProps || previousProps.src !== src) {
1041
- return;
1042
- }
1043
- if (previousProps.title !== title || previousProps.description !== description) {
1044
- getElement();
1045
- }
1046
- }, [description, getElement, previousProps, src, title]);
1047
- useEffect(() => {
1048
- if (!previousState) {
1049
- return;
1050
- }
1051
- switch (status) {
1052
- case STATUS.LOADING: {
1053
- if (previousState.status !== STATUS.LOADING) {
1054
- getContent();
1055
- }
1056
- break;
1057
- }
1058
- case STATUS.LOADED: {
1059
- if (previousState.status !== STATUS.LOADED) {
1060
- getElement();
1061
- }
1062
- break;
1063
- }
1064
- case STATUS.READY: {
1065
- if (previousState.status !== STATUS.READY) {
1066
- onLoad?.(src, isCached);
1067
- }
1068
- break;
1069
- }
1070
- }
1071
- }, [getContent, getElement, isCached, onLoad, previousState, src, status]);
1072
- const elementProps = omit(
1073
- props,
1074
- "baseURL",
1075
- "cacheRequests",
1076
- "children",
1077
- "description",
1078
- "fetchOptions",
1079
- "innerRef",
1080
- "loader",
1081
- "onError",
1082
- "onLoad",
1083
- "preProcessor",
1084
- "src",
1085
- "title",
1086
- "uniqueHash",
1087
- "uniquifyIDs"
1088
- );
1089
- if (!canUseDOM()) {
1090
- return loader;
1091
- }
1092
- if (element) {
1093
- return cloneElement(element, {
1094
- ref: innerRef,
1095
- ...elementProps
1096
- });
1097
- }
1098
- if ([STATUS.UNSUPPORTED, STATUS.FAILED].includes(status)) {
1099
- return children;
1100
- }
1101
- return loader;
1102
- }
1103
- function InlineSVG(props) {
1104
- if (!cacheStore) {
1105
- cacheStore = new CacheStore();
1106
- }
1107
- const { loader } = props;
1108
- const [isReady, setReady] = useState(cacheStore.isReady);
1109
- useEffect(() => {
1110
- if (isReady) {
1111
- return;
1112
- }
1113
- cacheStore.onReady(() => {
1114
- setReady(true);
1115
- });
1116
- }, [isReady]);
1117
- if (!isReady) {
1118
- return loader;
1119
- }
1120
- return /* @__PURE__ */ React__default.createElement(ReactInlineSVG, { ...props });
1121
- }
89
+ cssMediaquery.match = matchQuery;
90
+ cssMediaquery.parse = parseQuery;
1122
91
 
1123
- const useAppearanceConfig = (appearance, componentConfig, isDisabled) => {
1124
- const appearanceConfig = useMemo(() => {
1125
- if (appearance) {
1126
- const appearanceProps = appearance.split(' ').reduce((resultConfig, appearanceKey) => ({
1127
- ...resultConfig,
1128
- ...componentConfig.appearance?.[appearanceKey],
1129
- }), {});
1130
- if (isDisabled &&
1131
- (componentConfig?.appearance?.disabled ||
1132
- componentConfig?.appearance?.disabledPrimary)) {
1133
- Object.assign(appearanceProps, componentConfig?.appearance?.disabled ||
1134
- componentConfig?.appearance?.disabledPrimary);
1135
- }
1136
- return appearanceProps;
1137
- }
1138
- if (isDisabled) {
1139
- return (componentConfig?.appearance?.disabled ||
1140
- componentConfig?.appearance?.disabledPrimary);
1141
- }
1142
- return {};
1143
- }, [appearance, componentConfig?.appearance, isDisabled]);
1144
- return appearanceConfig;
1145
- };
92
+ // -----------------------------------------------------------------------------
1146
93
 
1147
- const byteToHex = [];
1148
- for (let i = 0; i < 256; ++i) {
1149
- byteToHex.push((i + 0x100).toString(16).slice(1));
1150
- }
1151
- function unsafeStringify(arr, offset = 0) {
1152
- return (byteToHex[arr[offset + 0]] +
1153
- byteToHex[arr[offset + 1]] +
1154
- byteToHex[arr[offset + 2]] +
1155
- byteToHex[arr[offset + 3]] +
1156
- '-' +
1157
- byteToHex[arr[offset + 4]] +
1158
- byteToHex[arr[offset + 5]] +
1159
- '-' +
1160
- byteToHex[arr[offset + 6]] +
1161
- byteToHex[arr[offset + 7]] +
1162
- '-' +
1163
- byteToHex[arr[offset + 8]] +
1164
- byteToHex[arr[offset + 9]] +
1165
- '-' +
1166
- byteToHex[arr[offset + 10]] +
1167
- byteToHex[arr[offset + 11]] +
1168
- byteToHex[arr[offset + 12]] +
1169
- byteToHex[arr[offset + 13]] +
1170
- byteToHex[arr[offset + 14]] +
1171
- byteToHex[arr[offset + 15]]).toLowerCase();
1172
- }
94
+ var RE_MEDIA_QUERY = /(?:(only|not)?\s*([^\s\(\)]+)(?:\s*and)?\s*)?(.+)?/i,
95
+ RE_MQ_EXPRESSION = /\(\s*([^\s\:\)]+)\s*(?:\:\s*([^\s\)]+))?\s*\)/,
96
+ RE_MQ_FEATURE = /^(?:(min|max)-)?(.+)/,
97
+ RE_LENGTH_UNIT = /(em|rem|px|cm|mm|in|pt|pc)?$/,
98
+ RE_RESOLUTION_UNIT = /(dpi|dpcm|dppx)?$/;
1173
99
 
1174
- let getRandomValues;
1175
- const rnds8 = new Uint8Array(16);
1176
- function rng() {
1177
- if (!getRandomValues) {
1178
- if (typeof crypto === 'undefined' || !crypto.getRandomValues) {
1179
- throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
1180
- }
1181
- getRandomValues = crypto.getRandomValues.bind(crypto);
1182
- }
1183
- return getRandomValues(rnds8);
1184
- }
100
+ function matchQuery(mediaQuery, values) {
101
+ return parseQuery(mediaQuery).some(function (query) {
102
+ var inverse = query.inverse;
1185
103
 
1186
- const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
1187
- var native = { randomUUID };
104
+ // Either the parsed or specified `type` is "all", or the types must be
105
+ // equal for a match.
106
+ var typeMatch = query.type === 'all' || values.type === query.type;
1188
107
 
1189
- function _v4(options, buf, offset) {
1190
- options = options || {};
1191
- const rnds = options.random ?? options.rng?.() ?? rng();
1192
- if (rnds.length < 16) {
1193
- throw new Error('Random bytes length must be >= 16');
1194
- }
1195
- rnds[6] = (rnds[6] & 0x0f) | 0x40;
1196
- rnds[8] = (rnds[8] & 0x3f) | 0x80;
1197
- return unsafeStringify(rnds);
1198
- }
1199
- function v4(options, buf, offset) {
1200
- if (native.randomUUID && true && !options) {
1201
- return native.randomUUID();
1202
- }
1203
- return _v4(options);
1204
- }
1205
-
1206
- const STATUSES = {
1207
- error: 'error',
1208
- info: 'info',
1209
- success: 'success',
1210
- warning: 'warning',
1211
- };
1212
- const NotificationsContext = createContext([]);
1213
- /* eslint-disable @typescript-eslint/no-unused-vars */
1214
- const NotificationsAPIContext = createContext({
1215
- hideNotifications: (targetId) => { },
1216
- showNotification: (notification, onClose) => { },
1217
- notificationStatuses: STATUSES,
1218
- });
1219
- /* eslint-enable @typescript-eslint/no-unused-vars */
1220
- function NotificationsProvider(props) {
1221
- const { initialNotificationsList = [], isLogRequestsErrors, children } = props;
1222
- const [notificationsList, setNotificationsList] = useState(() => {
1223
- // We need to set id to every notification item and original list also be have new id's
1224
- return (initialNotificationsList || []).map((notificationItem) => {
1225
- return createNotification(notificationItem, notificationItem.onClose);
1226
- });
1227
- });
1228
- const hideNotifications = useCallback((targetId) => {
1229
- // If not target, then nothing to hide
1230
- if (!targetId) {
1231
- return;
1232
- }
1233
- setNotificationsList((prevNotificationsList) => {
1234
- const newState = prevNotificationsList.filter((notificationItem) => {
1235
- // Check on need to hide, if current notification is target for hide
1236
- const isNeedToHide = String(notificationItem.id) === String(targetId);
1237
- // Callback for close if exists
1238
- if (isNeedToHide) {
1239
- clearTimeout(notificationItem._closeTimeout);
1240
- // @typescript-eslint/no-unused-expressions
1241
- notificationItem.onClose && notificationItem.onClose();
1242
- }
1243
- // Save in state if no need to hide
1244
- return !isNeedToHide;
1245
- });
1246
- // Set new notifications list without target item to state
1247
- return newState;
1248
- });
1249
- }, []);
1250
- const showNotification = useCallback((notification, onClose) => {
1251
- const newNotificationItem = createNotification(notification, onClose);
1252
- setNotificationsList((prevNotificationsList) => {
1253
- const newState = prevNotificationsList.slice();
1254
- const existsNotificationIndex = newState.findIndex((notificationItem) => String(notificationItem.id) === String(newNotificationItem.id));
1255
- // Add new notification
1256
- if (existsNotificationIndex === -1) {
1257
- return [...newState, newNotificationItem];
1258
- }
1259
- // Or update exists notification
1260
- const updatedNotificationItem = newState[existsNotificationIndex];
1261
- // Clear timeout to avoid close event for updated notification
1262
- clearTimeout(updatedNotificationItem._closeTimeout);
1263
- updatedNotificationItem._closeTimeout = undefined;
1264
- // Replace exists notification by new one
1265
- newState[existsNotificationIndex] = newNotificationItem;
1266
- return newState;
1267
- });
1268
- if (newNotificationItem.closeByTime) {
1269
- newNotificationItem._closeTimeout = setTimeout(() => hideNotifications(newNotificationItem.id), newNotificationItem.closeByTime);
1270
- }
1271
- return newNotificationItem;
1272
- },
1273
- // "hideNotifications" is never changed
1274
- // eslint-disable-next-line react-hooks/exhaustive-deps
1275
- []);
1276
- const notificationsAPI = useMemo(() => ({
1277
- hideNotifications: hideNotifications,
1278
- notificationStatuses: STATUSES,
1279
- showNotification: showNotification,
1280
- }),
1281
- // Functions is never changes, no sense to set as dependencies
1282
- // eslint-disable-next-line
1283
- []);
1284
- useEffect(() => {
1285
- // Set timeout for initial notifications list one time on first render
1286
- notificationsList.forEach((notificationItem) => {
1287
- if (notificationItem.closeByTime) {
1288
- setTimeout(() => hideNotifications(notificationItem.id), notificationItem.closeByTime);
1289
- }
1290
- });
1291
- // Show notifications on all requests errors.
1292
- // Enable one time without disabling. Use "isLogging" on request config level
1293
- // to disable notifications logger.
1294
- if (isLogRequestsErrors) {
1295
- axiosInstanceITCase.responseErrorHandler.loggerManager = {
1296
- log: (responseError) => {
1297
- if (responseError.message) {
1298
- // prevent from showing many network errors
1299
- const errorListToDedupe = ['network'];
1300
- const id = errorListToDedupe.includes(responseError.key)
1301
- ? responseError.key
1302
- : undefined;
1303
- showNotification({
1304
- id: id,
1305
- title: responseError.message,
1306
- status: 'error',
1307
- closeByTime: 4000,
1308
- });
1309
- }
1310
- },
1311
- };
1312
- }
1313
- // eslint-disable-next-line react-hooks/exhaustive-deps
1314
- }, []);
1315
- return (jsx(NotificationsAPIContext.Provider, { value: notificationsAPI, children: jsx(NotificationsContext.Provider, { value: notificationsList, children: children }) }));
1316
- }
1317
- function useNotifications() {
1318
- return useContext(NotificationsContext);
1319
- }
1320
- function useNotificationsAPI() {
1321
- return useContext(NotificationsAPIContext);
1322
- }
1323
- const statusToAppearanceList = {
1324
- error: 'errorPrimary sizeS solid rounded',
1325
- info: 'infoPrimary sizeS solid rounded',
1326
- success: 'successPrimary sizeS solid rounded',
1327
- warning: 'warningPrimary sizeS solid rounded',
1328
- };
1329
- function createNotification(notification, onClose) {
1330
- // Default notification item properties
1331
- let id = v4().split('-')[0];
1332
- let title = '';
1333
- let text = '';
1334
- let closeIcon = '';
1335
- let closeIconSrc = '';
1336
- let type = 'float';
1337
- let buttonLabel = '';
1338
- let status = STATUSES.warning;
1339
- let closeByTime = 4500;
1340
- let appearance = statusToAppearanceList[status];
1341
- let after = null;
1342
- let isLoading = false;
1343
- let closeIconAppearance = '';
1344
- let onClickButton = () => { };
1345
- if (typeof notification === 'string') {
1346
- text = notification;
1347
- }
1348
- else if (typeof notification === 'object') {
1349
- id = String(notification.id ?? id);
1350
- title = notification.title ?? title;
1351
- text = notification.text ?? text;
1352
- closeIconAppearance =
1353
- notification.closeIconAppearance ?? closeIconAppearance;
1354
- type = notification.type ?? type;
1355
- closeIcon = notification.closeIcon ?? closeIcon;
1356
- closeIconSrc = notification.closeIconSrc ?? closeIconSrc;
1357
- buttonLabel = notification.buttonLabel ?? buttonLabel;
1358
- onClickButton = notification.onClickButton ?? onClickButton;
1359
- status = notification.status ?? status;
1360
- closeByTime = notification.closeByTime ?? closeByTime;
1361
- isLoading = notification.isLoading ?? isLoading;
1362
- after = notification.after ?? after;
1363
- appearance =
1364
- notification.appearance ??
1365
- statusToAppearanceList[notification.status] ??
1366
- appearance;
1367
- }
1368
- return {
1369
- id: id,
1370
- appearance: appearance,
1371
- type: type,
1372
- title: title,
1373
- status: status,
1374
- text: text,
1375
- buttonLabel: buttonLabel,
1376
- after: after,
1377
- closeByTime: closeByTime,
1378
- closeIcon: closeIcon,
1379
- closeIconAppearance: closeIconAppearance,
1380
- closeIconSrc: closeIconSrc,
1381
- isLoading: isLoading,
1382
- onClickButton: onClickButton,
1383
- onClose: onClose,
1384
- };
1385
- }
1386
-
1387
- function getDefaultExportFromCjs (x) {
1388
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1389
- }
1390
-
1391
- var cssMediaquery = {};
1392
-
1393
- /*
1394
- Copyright (c) 2014, Yahoo! Inc. All rights reserved.
1395
- Copyrights licensed under the New BSD License.
1396
- See the accompanying LICENSE file for terms.
1397
- */
1398
-
1399
- var hasRequiredCssMediaquery;
1400
-
1401
- function requireCssMediaquery () {
1402
- if (hasRequiredCssMediaquery) return cssMediaquery;
1403
- hasRequiredCssMediaquery = 1;
1404
-
1405
- cssMediaquery.match = matchQuery;
1406
- cssMediaquery.parse = parseQuery;
1407
-
1408
- // -----------------------------------------------------------------------------
1409
-
1410
- var RE_MEDIA_QUERY = /(?:(only|not)?\s*([^\s\(\)]+)(?:\s*and)?\s*)?(.+)?/i,
1411
- RE_MQ_EXPRESSION = /\(\s*([^\s\:\)]+)\s*(?:\:\s*([^\s\)]+))?\s*\)/,
1412
- RE_MQ_FEATURE = /^(?:(min|max)-)?(.+)/,
1413
- RE_LENGTH_UNIT = /(em|rem|px|cm|mm|in|pt|pc)?$/,
1414
- RE_RESOLUTION_UNIT = /(dpi|dpcm|dppx)?$/;
1415
-
1416
- function matchQuery(mediaQuery, values) {
1417
- return parseQuery(mediaQuery).some(function (query) {
1418
- var inverse = query.inverse;
1419
-
1420
- // Either the parsed or specified `type` is "all", or the types must be
1421
- // equal for a match.
1422
- var typeMatch = query.type === 'all' || values.type === query.type;
1423
-
1424
- // Quit early when `type` doesn't match, but take "not" into account.
1425
- if ((typeMatch && inverse) || !(typeMatch || inverse)) {
1426
- return false;
1427
- }
108
+ // Quit early when `type` doesn't match, but take "not" into account.
109
+ if ((typeMatch && inverse) || !(typeMatch || inverse)) {
110
+ return false;
111
+ }
1428
112
 
1429
113
  var expressionsMatch = query.expressions.every(function (expression) {
1430
114
  var feature = expression.feature,
@@ -2718,320 +1402,1475 @@ function requireFactoryWithTypeCheckers () {
2718
1402
  return propType;
2719
1403
  }
2720
1404
 
2721
- // Returns a string that is postfixed to a warning about an invalid type.
2722
- // For example, "undefined" or "of type array"
2723
- function getPostfixForTypeWarning(value) {
2724
- var type = getPreciseType(value);
2725
- switch (type) {
2726
- case 'array':
2727
- case 'object':
2728
- return 'an ' + type;
2729
- case 'boolean':
2730
- case 'date':
2731
- case 'regexp':
2732
- return 'a ' + type;
2733
- default:
2734
- return type;
2735
- }
2736
- }
1405
+ // Returns a string that is postfixed to a warning about an invalid type.
1406
+ // For example, "undefined" or "of type array"
1407
+ function getPostfixForTypeWarning(value) {
1408
+ var type = getPreciseType(value);
1409
+ switch (type) {
1410
+ case 'array':
1411
+ case 'object':
1412
+ return 'an ' + type;
1413
+ case 'boolean':
1414
+ case 'date':
1415
+ case 'regexp':
1416
+ return 'a ' + type;
1417
+ default:
1418
+ return type;
1419
+ }
1420
+ }
1421
+
1422
+ // Returns class name of the object, if any.
1423
+ function getClassName(propValue) {
1424
+ if (!propValue.constructor || !propValue.constructor.name) {
1425
+ return ANONYMOUS;
1426
+ }
1427
+ return propValue.constructor.name;
1428
+ }
1429
+
1430
+ ReactPropTypes.checkPropTypes = checkPropTypes;
1431
+ ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;
1432
+ ReactPropTypes.PropTypes = ReactPropTypes;
1433
+
1434
+ return ReactPropTypes;
1435
+ };
1436
+ return factoryWithTypeCheckers;
1437
+ }
1438
+
1439
+ /**
1440
+ * Copyright (c) 2013-present, Facebook, Inc.
1441
+ *
1442
+ * This source code is licensed under the MIT license found in the
1443
+ * LICENSE file in the root directory of this source tree.
1444
+ */
1445
+
1446
+ var factoryWithThrowingShims;
1447
+ var hasRequiredFactoryWithThrowingShims;
1448
+
1449
+ function requireFactoryWithThrowingShims () {
1450
+ if (hasRequiredFactoryWithThrowingShims) return factoryWithThrowingShims;
1451
+ hasRequiredFactoryWithThrowingShims = 1;
1452
+
1453
+ var ReactPropTypesSecret = /*@__PURE__*/ requireReactPropTypesSecret();
1454
+
1455
+ function emptyFunction() {}
1456
+ function emptyFunctionWithReset() {}
1457
+ emptyFunctionWithReset.resetWarningCache = emptyFunction;
1458
+
1459
+ factoryWithThrowingShims = function() {
1460
+ function shim(props, propName, componentName, location, propFullName, secret) {
1461
+ if (secret === ReactPropTypesSecret) {
1462
+ // It is still safe when called from React.
1463
+ return;
1464
+ }
1465
+ var err = new Error(
1466
+ 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
1467
+ 'Use PropTypes.checkPropTypes() to call them. ' +
1468
+ 'Read more at http://fb.me/use-check-prop-types'
1469
+ );
1470
+ err.name = 'Invariant Violation';
1471
+ throw err;
1472
+ } shim.isRequired = shim;
1473
+ function getShim() {
1474
+ return shim;
1475
+ } // Important!
1476
+ // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
1477
+ var ReactPropTypes = {
1478
+ array: shim,
1479
+ bigint: shim,
1480
+ bool: shim,
1481
+ func: shim,
1482
+ number: shim,
1483
+ object: shim,
1484
+ string: shim,
1485
+ symbol: shim,
1486
+
1487
+ any: shim,
1488
+ arrayOf: getShim,
1489
+ element: shim,
1490
+ elementType: shim,
1491
+ instanceOf: getShim,
1492
+ node: shim,
1493
+ objectOf: getShim,
1494
+ oneOf: getShim,
1495
+ oneOfType: getShim,
1496
+ shape: getShim,
1497
+ exact: getShim,
1498
+
1499
+ checkPropTypes: emptyFunctionWithReset,
1500
+ resetWarningCache: emptyFunction
1501
+ };
1502
+
1503
+ ReactPropTypes.PropTypes = ReactPropTypes;
1504
+
1505
+ return ReactPropTypes;
1506
+ };
1507
+ return factoryWithThrowingShims;
1508
+ }
1509
+
1510
+ /**
1511
+ * Copyright (c) 2013-present, Facebook, Inc.
1512
+ *
1513
+ * This source code is licensed under the MIT license found in the
1514
+ * LICENSE file in the root directory of this source tree.
1515
+ */
1516
+
1517
+ var hasRequiredPropTypes;
1518
+
1519
+ function requirePropTypes () {
1520
+ if (hasRequiredPropTypes) return propTypes.exports;
1521
+ hasRequiredPropTypes = 1;
1522
+ if (process.env.NODE_ENV !== 'production') {
1523
+ var ReactIs = requireReactIs();
1524
+
1525
+ // By explicitly using `prop-types` you are opting into new development behavior.
1526
+ // http://fb.me/prop-types-in-prod
1527
+ var throwOnDirectAccess = true;
1528
+ propTypes.exports = /*@__PURE__*/ requireFactoryWithTypeCheckers()(ReactIs.isElement, throwOnDirectAccess);
1529
+ } else {
1530
+ // By explicitly using `prop-types` you are opting into new production behavior.
1531
+ // http://fb.me/prop-types-in-prod
1532
+ propTypes.exports = /*@__PURE__*/ requireFactoryWithThrowingShims()();
1533
+ }
1534
+ return propTypes.exports;
1535
+ }
1536
+
1537
+ var propTypesExports = /*@__PURE__*/ requirePropTypes();
1538
+ var PropTypes = /*@__PURE__*/getDefaultExportFromCjs(propTypesExports);
1539
+
1540
+ const stringOrNumber = PropTypes.oneOfType([PropTypes.string, PropTypes.number]);
1541
+ // media types
1542
+ const types = {
1543
+ all: PropTypes.bool,
1544
+ grid: PropTypes.bool,
1545
+ aural: PropTypes.bool,
1546
+ braille: PropTypes.bool,
1547
+ handheld: PropTypes.bool,
1548
+ print: PropTypes.bool,
1549
+ projection: PropTypes.bool,
1550
+ screen: PropTypes.bool,
1551
+ tty: PropTypes.bool,
1552
+ tv: PropTypes.bool,
1553
+ embossed: PropTypes.bool
1554
+ };
1555
+ // properties that match media queries
1556
+ const matchers = {
1557
+ orientation: PropTypes.oneOf(['portrait', 'landscape']),
1558
+ scan: PropTypes.oneOf(['progressive', 'interlace']),
1559
+ aspectRatio: PropTypes.string,
1560
+ deviceAspectRatio: PropTypes.string,
1561
+ height: stringOrNumber,
1562
+ deviceHeight: stringOrNumber,
1563
+ width: stringOrNumber,
1564
+ deviceWidth: stringOrNumber,
1565
+ color: PropTypes.bool,
1566
+ colorIndex: PropTypes.bool,
1567
+ monochrome: PropTypes.bool,
1568
+ resolution: stringOrNumber,
1569
+ type: Object.keys(types)
1570
+ };
1571
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1572
+ const { type, ...featureMatchers } = matchers;
1573
+ // media features
1574
+ const features = {
1575
+ minAspectRatio: PropTypes.string,
1576
+ maxAspectRatio: PropTypes.string,
1577
+ minDeviceAspectRatio: PropTypes.string,
1578
+ maxDeviceAspectRatio: PropTypes.string,
1579
+ minHeight: stringOrNumber,
1580
+ maxHeight: stringOrNumber,
1581
+ minDeviceHeight: stringOrNumber,
1582
+ maxDeviceHeight: stringOrNumber,
1583
+ minWidth: stringOrNumber,
1584
+ maxWidth: stringOrNumber,
1585
+ minDeviceWidth: stringOrNumber,
1586
+ maxDeviceWidth: stringOrNumber,
1587
+ minColor: PropTypes.number,
1588
+ maxColor: PropTypes.number,
1589
+ minColorIndex: PropTypes.number,
1590
+ maxColorIndex: PropTypes.number,
1591
+ minMonochrome: PropTypes.number,
1592
+ maxMonochrome: PropTypes.number,
1593
+ minResolution: stringOrNumber,
1594
+ maxResolution: stringOrNumber,
1595
+ ...featureMatchers
1596
+ };
1597
+ const all = { ...types, ...features };
1598
+ var mq = {
1599
+ all: all};
1600
+
1601
+ const negate = (cond) => `not ${cond}`;
1602
+ const keyVal = (k, v) => {
1603
+ const realKey = hyphenateStyleName(k);
1604
+ // px shorthand
1605
+ if (typeof v === 'number') {
1606
+ v = `${v}px`;
1607
+ }
1608
+ if (v === true) {
1609
+ return realKey;
1610
+ }
1611
+ if (v === false) {
1612
+ return negate(realKey);
1613
+ }
1614
+ return `(${realKey}: ${v})`;
1615
+ };
1616
+ const join = (conds) => conds.join(' and ');
1617
+ const toQuery = (obj) => {
1618
+ const rules = [];
1619
+ Object.keys(mq.all).forEach((k) => {
1620
+ const v = obj[k];
1621
+ if (v != null) {
1622
+ rules.push(keyVal(k, v));
1623
+ }
1624
+ });
1625
+ return join(rules);
1626
+ };
1627
+
1628
+ const Context = createContext(undefined);
1629
+
1630
+ const makeQuery = (settings) => settings.query || toQuery(settings);
1631
+ const hyphenateKeys = (obj) => {
1632
+ if (!obj)
1633
+ return undefined;
1634
+ const keys = Object.keys(obj);
1635
+ return keys.reduce((result, key) => {
1636
+ result[hyphenateStyleName(key)] = obj[key];
1637
+ return result;
1638
+ }, {});
1639
+ };
1640
+ const useIsUpdate = () => {
1641
+ const ref = useRef(false);
1642
+ useEffect(() => {
1643
+ ref.current = true;
1644
+ }, []);
1645
+ return ref.current;
1646
+ };
1647
+ const useDevice = (deviceFromProps) => {
1648
+ const deviceFromContext = useContext(Context);
1649
+ const getDevice = () => hyphenateKeys(deviceFromProps) || hyphenateKeys(deviceFromContext);
1650
+ const [device, setDevice] = useState(getDevice);
1651
+ useEffect(() => {
1652
+ const newDevice = getDevice();
1653
+ if (!shallowEqualObjects(device, newDevice)) {
1654
+ setDevice(newDevice);
1655
+ }
1656
+ }, [deviceFromProps, deviceFromContext]);
1657
+ return device;
1658
+ };
1659
+ const useQuery = (settings) => {
1660
+ const getQuery = () => makeQuery(settings);
1661
+ const [query, setQuery] = useState(getQuery);
1662
+ useEffect(() => {
1663
+ const newQuery = getQuery();
1664
+ if (query !== newQuery) {
1665
+ setQuery(newQuery);
1666
+ }
1667
+ }, [settings]);
1668
+ return query;
1669
+ };
1670
+ const useMatchMedia = (query, device) => {
1671
+ const getMatchMedia = () => matchMedia(query, device || {}, !!device);
1672
+ const [mq, setMq] = useState(getMatchMedia);
1673
+ const isUpdate = useIsUpdate();
1674
+ useEffect(() => {
1675
+ if (isUpdate) {
1676
+ // skip on mounting, it has already been set
1677
+ const newMq = getMatchMedia();
1678
+ setMq(newMq);
1679
+ return () => {
1680
+ if (newMq) {
1681
+ newMq.dispose();
1682
+ }
1683
+ };
1684
+ }
1685
+ }, [query, device]);
1686
+ return mq;
1687
+ };
1688
+ const useMatches = (mediaQuery) => {
1689
+ const [matches, setMatches] = useState(mediaQuery.matches);
1690
+ useEffect(() => {
1691
+ const updateMatches = (ev) => {
1692
+ setMatches(ev.matches);
1693
+ };
1694
+ mediaQuery.addListener(updateMatches);
1695
+ setMatches(mediaQuery.matches);
1696
+ return () => {
1697
+ mediaQuery.removeListener(updateMatches);
1698
+ };
1699
+ }, [mediaQuery]);
1700
+ return matches;
1701
+ };
1702
+ const useMediaQuery = (settings, device, onChange) => {
1703
+ const deviceSettings = useDevice(device);
1704
+ const query = useQuery(settings);
1705
+ if (!query)
1706
+ throw new Error('Invalid or missing MediaQuery!');
1707
+ const mq = useMatchMedia(query, deviceSettings);
1708
+ const matches = useMatches(mq);
1709
+ useIsUpdate();
1710
+ useEffect(() => {
1711
+ }, [matches]);
1712
+ useEffect(() => () => {
1713
+ if (mq) {
1714
+ mq.dispose();
1715
+ }
1716
+ }, []);
1717
+ return matches;
1718
+ };
1719
+
1720
+ // src/index.ts
1721
+
1722
+ // src/helpers.ts
1723
+ var styleToObject = (input) => {
1724
+ if (typeof input !== "string") {
1725
+ return {};
1726
+ }
1727
+ return input.split(/ ?; ?/).reduce((acc, item) => {
1728
+ const [key, value] = item.split(/ ?: ?/).map((d, index) => index === 0 ? d.replace(/\s+/g, "") : d.trim());
1729
+ if (key && value) {
1730
+ const nextKey = key.replace(/(\w)-(\w)/g, (_$0, $1, $2) => `${$1}${$2.toUpperCase()}`);
1731
+ let nextValue = value.trim();
1732
+ if (!Number.isNaN(Number(value))) {
1733
+ nextValue = Number(value);
1734
+ }
1735
+ acc[key.startsWith("-") ? key : nextKey] = nextValue;
1736
+ }
1737
+ return acc;
1738
+ }, {});
1739
+ };
1740
+ function randomString$1(length = 6) {
1741
+ const characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
1742
+ let result = "";
1743
+ for (let index = length; index > 0; --index) {
1744
+ result += characters[Math.round(Math.random() * (characters.length - 1))];
1745
+ }
1746
+ return result;
1747
+ }
1748
+ var noTextChildNodes = [
1749
+ "br",
1750
+ "col",
1751
+ "colgroup",
1752
+ "dl",
1753
+ "hr",
1754
+ "iframe",
1755
+ "img",
1756
+ "input",
1757
+ "link",
1758
+ "menuitem",
1759
+ "meta",
1760
+ "ol",
1761
+ "param",
1762
+ "select",
1763
+ "table",
1764
+ "tbody",
1765
+ "tfoot",
1766
+ "thead",
1767
+ "tr",
1768
+ "ul",
1769
+ "wbr"
1770
+ ];
1771
+ var possibleStandardNames = {
1772
+ // HTML
1773
+ "accept-charset": "acceptCharset",
1774
+ acceptcharset: "acceptCharset",
1775
+ accesskey: "accessKey",
1776
+ allowfullscreen: "allowFullScreen",
1777
+ autocapitalize: "autoCapitalize",
1778
+ autocomplete: "autoComplete",
1779
+ autocorrect: "autoCorrect",
1780
+ autofocus: "autoFocus",
1781
+ autoplay: "autoPlay",
1782
+ autosave: "autoSave",
1783
+ cellpadding: "cellPadding",
1784
+ cellspacing: "cellSpacing",
1785
+ charset: "charSet",
1786
+ class: "className",
1787
+ classid: "classID",
1788
+ classname: "className",
1789
+ colspan: "colSpan",
1790
+ contenteditable: "contentEditable",
1791
+ contextmenu: "contextMenu",
1792
+ controlslist: "controlsList",
1793
+ crossorigin: "crossOrigin",
1794
+ dangerouslysetinnerhtml: "dangerouslySetInnerHTML",
1795
+ datetime: "dateTime",
1796
+ defaultchecked: "defaultChecked",
1797
+ defaultvalue: "defaultValue",
1798
+ enctype: "encType",
1799
+ for: "htmlFor",
1800
+ formmethod: "formMethod",
1801
+ formaction: "formAction",
1802
+ formenctype: "formEncType",
1803
+ formnovalidate: "formNoValidate",
1804
+ formtarget: "formTarget",
1805
+ frameborder: "frameBorder",
1806
+ hreflang: "hrefLang",
1807
+ htmlfor: "htmlFor",
1808
+ httpequiv: "httpEquiv",
1809
+ "http-equiv": "httpEquiv",
1810
+ icon: "icon",
1811
+ innerhtml: "innerHTML",
1812
+ inputmode: "inputMode",
1813
+ itemid: "itemID",
1814
+ itemprop: "itemProp",
1815
+ itemref: "itemRef",
1816
+ itemscope: "itemScope",
1817
+ itemtype: "itemType",
1818
+ keyparams: "keyParams",
1819
+ keytype: "keyType",
1820
+ marginwidth: "marginWidth",
1821
+ marginheight: "marginHeight",
1822
+ maxlength: "maxLength",
1823
+ mediagroup: "mediaGroup",
1824
+ minlength: "minLength",
1825
+ nomodule: "noModule",
1826
+ novalidate: "noValidate",
1827
+ playsinline: "playsInline",
1828
+ radiogroup: "radioGroup",
1829
+ readonly: "readOnly",
1830
+ referrerpolicy: "referrerPolicy",
1831
+ rowspan: "rowSpan",
1832
+ spellcheck: "spellCheck",
1833
+ srcdoc: "srcDoc",
1834
+ srclang: "srcLang",
1835
+ srcset: "srcSet",
1836
+ tabindex: "tabIndex",
1837
+ typemustmatch: "typeMustMatch",
1838
+ usemap: "useMap",
1839
+ // SVG
1840
+ accentheight: "accentHeight",
1841
+ "accent-height": "accentHeight",
1842
+ alignmentbaseline: "alignmentBaseline",
1843
+ "alignment-baseline": "alignmentBaseline",
1844
+ allowreorder: "allowReorder",
1845
+ arabicform: "arabicForm",
1846
+ "arabic-form": "arabicForm",
1847
+ attributename: "attributeName",
1848
+ attributetype: "attributeType",
1849
+ autoreverse: "autoReverse",
1850
+ basefrequency: "baseFrequency",
1851
+ baselineshift: "baselineShift",
1852
+ "baseline-shift": "baselineShift",
1853
+ baseprofile: "baseProfile",
1854
+ calcmode: "calcMode",
1855
+ capheight: "capHeight",
1856
+ "cap-height": "capHeight",
1857
+ clippath: "clipPath",
1858
+ "clip-path": "clipPath",
1859
+ clippathunits: "clipPathUnits",
1860
+ cliprule: "clipRule",
1861
+ "clip-rule": "clipRule",
1862
+ colorinterpolation: "colorInterpolation",
1863
+ "color-interpolation": "colorInterpolation",
1864
+ colorinterpolationfilters: "colorInterpolationFilters",
1865
+ "color-interpolation-filters": "colorInterpolationFilters",
1866
+ colorprofile: "colorProfile",
1867
+ "color-profile": "colorProfile",
1868
+ colorrendering: "colorRendering",
1869
+ "color-rendering": "colorRendering",
1870
+ contentscripttype: "contentScriptType",
1871
+ contentstyletype: "contentStyleType",
1872
+ diffuseconstant: "diffuseConstant",
1873
+ dominantbaseline: "dominantBaseline",
1874
+ "dominant-baseline": "dominantBaseline",
1875
+ edgemode: "edgeMode",
1876
+ enablebackground: "enableBackground",
1877
+ "enable-background": "enableBackground",
1878
+ externalresourcesrequired: "externalResourcesRequired",
1879
+ fillopacity: "fillOpacity",
1880
+ "fill-opacity": "fillOpacity",
1881
+ fillrule: "fillRule",
1882
+ "fill-rule": "fillRule",
1883
+ filterres: "filterRes",
1884
+ filterunits: "filterUnits",
1885
+ floodopacity: "floodOpacity",
1886
+ "flood-opacity": "floodOpacity",
1887
+ floodcolor: "floodColor",
1888
+ "flood-color": "floodColor",
1889
+ fontfamily: "fontFamily",
1890
+ "font-family": "fontFamily",
1891
+ fontsize: "fontSize",
1892
+ "font-size": "fontSize",
1893
+ fontsizeadjust: "fontSizeAdjust",
1894
+ "font-size-adjust": "fontSizeAdjust",
1895
+ fontstretch: "fontStretch",
1896
+ "font-stretch": "fontStretch",
1897
+ fontstyle: "fontStyle",
1898
+ "font-style": "fontStyle",
1899
+ fontvariant: "fontVariant",
1900
+ "font-variant": "fontVariant",
1901
+ fontweight: "fontWeight",
1902
+ "font-weight": "fontWeight",
1903
+ glyphname: "glyphName",
1904
+ "glyph-name": "glyphName",
1905
+ glyphorientationhorizontal: "glyphOrientationHorizontal",
1906
+ "glyph-orientation-horizontal": "glyphOrientationHorizontal",
1907
+ glyphorientationvertical: "glyphOrientationVertical",
1908
+ "glyph-orientation-vertical": "glyphOrientationVertical",
1909
+ glyphref: "glyphRef",
1910
+ gradienttransform: "gradientTransform",
1911
+ gradientunits: "gradientUnits",
1912
+ horizadvx: "horizAdvX",
1913
+ "horiz-adv-x": "horizAdvX",
1914
+ horizoriginx: "horizOriginX",
1915
+ "horiz-origin-x": "horizOriginX",
1916
+ imagerendering: "imageRendering",
1917
+ "image-rendering": "imageRendering",
1918
+ kernelmatrix: "kernelMatrix",
1919
+ kernelunitlength: "kernelUnitLength",
1920
+ keypoints: "keyPoints",
1921
+ keysplines: "keySplines",
1922
+ keytimes: "keyTimes",
1923
+ lengthadjust: "lengthAdjust",
1924
+ letterspacing: "letterSpacing",
1925
+ "letter-spacing": "letterSpacing",
1926
+ lightingcolor: "lightingColor",
1927
+ "lighting-color": "lightingColor",
1928
+ limitingconeangle: "limitingConeAngle",
1929
+ markerend: "markerEnd",
1930
+ "marker-end": "markerEnd",
1931
+ markerheight: "markerHeight",
1932
+ markermid: "markerMid",
1933
+ "marker-mid": "markerMid",
1934
+ markerstart: "markerStart",
1935
+ "marker-start": "markerStart",
1936
+ markerunits: "markerUnits",
1937
+ markerwidth: "markerWidth",
1938
+ maskcontentunits: "maskContentUnits",
1939
+ maskunits: "maskUnits",
1940
+ numoctaves: "numOctaves",
1941
+ overlineposition: "overlinePosition",
1942
+ "overline-position": "overlinePosition",
1943
+ overlinethickness: "overlineThickness",
1944
+ "overline-thickness": "overlineThickness",
1945
+ paintorder: "paintOrder",
1946
+ "paint-order": "paintOrder",
1947
+ "panose-1": "panose1",
1948
+ pathlength: "pathLength",
1949
+ patterncontentunits: "patternContentUnits",
1950
+ patterntransform: "patternTransform",
1951
+ patternunits: "patternUnits",
1952
+ pointerevents: "pointerEvents",
1953
+ "pointer-events": "pointerEvents",
1954
+ pointsatx: "pointsAtX",
1955
+ pointsaty: "pointsAtY",
1956
+ pointsatz: "pointsAtZ",
1957
+ preservealpha: "preserveAlpha",
1958
+ preserveaspectratio: "preserveAspectRatio",
1959
+ primitiveunits: "primitiveUnits",
1960
+ refx: "refX",
1961
+ refy: "refY",
1962
+ renderingintent: "renderingIntent",
1963
+ "rendering-intent": "renderingIntent",
1964
+ repeatcount: "repeatCount",
1965
+ repeatdur: "repeatDur",
1966
+ requiredextensions: "requiredExtensions",
1967
+ requiredfeatures: "requiredFeatures",
1968
+ shaperendering: "shapeRendering",
1969
+ "shape-rendering": "shapeRendering",
1970
+ specularconstant: "specularConstant",
1971
+ specularexponent: "specularExponent",
1972
+ spreadmethod: "spreadMethod",
1973
+ startoffset: "startOffset",
1974
+ stddeviation: "stdDeviation",
1975
+ stitchtiles: "stitchTiles",
1976
+ stopcolor: "stopColor",
1977
+ "stop-color": "stopColor",
1978
+ stopopacity: "stopOpacity",
1979
+ "stop-opacity": "stopOpacity",
1980
+ strikethroughposition: "strikethroughPosition",
1981
+ "strikethrough-position": "strikethroughPosition",
1982
+ strikethroughthickness: "strikethroughThickness",
1983
+ "strikethrough-thickness": "strikethroughThickness",
1984
+ strokedasharray: "strokeDasharray",
1985
+ "stroke-dasharray": "strokeDasharray",
1986
+ strokedashoffset: "strokeDashoffset",
1987
+ "stroke-dashoffset": "strokeDashoffset",
1988
+ strokelinecap: "strokeLinecap",
1989
+ "stroke-linecap": "strokeLinecap",
1990
+ strokelinejoin: "strokeLinejoin",
1991
+ "stroke-linejoin": "strokeLinejoin",
1992
+ strokemiterlimit: "strokeMiterlimit",
1993
+ "stroke-miterlimit": "strokeMiterlimit",
1994
+ strokewidth: "strokeWidth",
1995
+ "stroke-width": "strokeWidth",
1996
+ strokeopacity: "strokeOpacity",
1997
+ "stroke-opacity": "strokeOpacity",
1998
+ suppresscontenteditablewarning: "suppressContentEditableWarning",
1999
+ suppresshydrationwarning: "suppressHydrationWarning",
2000
+ surfacescale: "surfaceScale",
2001
+ systemlanguage: "systemLanguage",
2002
+ tablevalues: "tableValues",
2003
+ targetx: "targetX",
2004
+ targety: "targetY",
2005
+ textanchor: "textAnchor",
2006
+ "text-anchor": "textAnchor",
2007
+ textdecoration: "textDecoration",
2008
+ "text-decoration": "textDecoration",
2009
+ textlength: "textLength",
2010
+ textrendering: "textRendering",
2011
+ "text-rendering": "textRendering",
2012
+ underlineposition: "underlinePosition",
2013
+ "underline-position": "underlinePosition",
2014
+ underlinethickness: "underlineThickness",
2015
+ "underline-thickness": "underlineThickness",
2016
+ unicodebidi: "unicodeBidi",
2017
+ "unicode-bidi": "unicodeBidi",
2018
+ unicoderange: "unicodeRange",
2019
+ "unicode-range": "unicodeRange",
2020
+ unitsperem: "unitsPerEm",
2021
+ "units-per-em": "unitsPerEm",
2022
+ unselectable: "unselectable",
2023
+ valphabetic: "vAlphabetic",
2024
+ "v-alphabetic": "vAlphabetic",
2025
+ vectoreffect: "vectorEffect",
2026
+ "vector-effect": "vectorEffect",
2027
+ vertadvy: "vertAdvY",
2028
+ "vert-adv-y": "vertAdvY",
2029
+ vertoriginx: "vertOriginX",
2030
+ "vert-origin-x": "vertOriginX",
2031
+ vertoriginy: "vertOriginY",
2032
+ "vert-origin-y": "vertOriginY",
2033
+ vhanging: "vHanging",
2034
+ "v-hanging": "vHanging",
2035
+ videographic: "vIdeographic",
2036
+ "v-ideographic": "vIdeographic",
2037
+ viewbox: "viewBox",
2038
+ viewtarget: "viewTarget",
2039
+ vmathematical: "vMathematical",
2040
+ "v-mathematical": "vMathematical",
2041
+ wordspacing: "wordSpacing",
2042
+ "word-spacing": "wordSpacing",
2043
+ writingmode: "writingMode",
2044
+ "writing-mode": "writingMode",
2045
+ xchannelselector: "xChannelSelector",
2046
+ xheight: "xHeight",
2047
+ "x-height": "xHeight",
2048
+ xlinkactuate: "xlinkActuate",
2049
+ "xlink:actuate": "xlinkActuate",
2050
+ xlinkarcrole: "xlinkArcrole",
2051
+ "xlink:arcrole": "xlinkArcrole",
2052
+ xlinkhref: "xlinkHref",
2053
+ "xlink:href": "xlinkHref",
2054
+ xlinkrole: "xlinkRole",
2055
+ "xlink:role": "xlinkRole",
2056
+ xlinkshow: "xlinkShow",
2057
+ "xlink:show": "xlinkShow",
2058
+ xlinktitle: "xlinkTitle",
2059
+ "xlink:title": "xlinkTitle",
2060
+ xlinktype: "xlinkType",
2061
+ "xlink:type": "xlinkType",
2062
+ xmlbase: "xmlBase",
2063
+ "xml:base": "xmlBase",
2064
+ xmllang: "xmlLang",
2065
+ "xml:lang": "xmlLang",
2066
+ "xml:space": "xmlSpace",
2067
+ xmlnsxlink: "xmlnsXlink",
2068
+ "xmlns:xlink": "xmlnsXlink",
2069
+ xmlspace: "xmlSpace",
2070
+ ychannelselector: "yChannelSelector",
2071
+ zoomandpan: "zoomAndPan",
2072
+ // event handlers
2073
+ onblur: "onBlur",
2074
+ onchange: "onChange",
2075
+ onclick: "onClick",
2076
+ oncontextmenu: "onContextMenu",
2077
+ ondoubleclick: "onDoubleClick",
2078
+ ondrag: "onDrag",
2079
+ ondragend: "onDragEnd",
2080
+ ondragenter: "onDragEnter",
2081
+ ondragexit: "onDragExit",
2082
+ ondragleave: "onDragLeave",
2083
+ ondragover: "onDragOver",
2084
+ ondragstart: "onDragStart",
2085
+ ondrop: "onDrop",
2086
+ onerror: "onError",
2087
+ onfocus: "onFocus",
2088
+ oninput: "onInput",
2089
+ oninvalid: "onInvalid",
2090
+ onkeydown: "onKeyDown",
2091
+ onkeypress: "onKeyPress",
2092
+ onkeyup: "onKeyUp",
2093
+ onload: "onLoad",
2094
+ onmousedown: "onMouseDown",
2095
+ onmouseenter: "onMouseEnter",
2096
+ onmouseleave: "onMouseLeave",
2097
+ onmousemove: "onMouseMove",
2098
+ onmouseout: "onMouseOut",
2099
+ onmouseover: "onMouseOver",
2100
+ onmouseup: "onMouseUp",
2101
+ onscroll: "onScroll",
2102
+ onsubmit: "onSubmit",
2103
+ ontouchcancel: "onTouchCancel",
2104
+ ontouchend: "onTouchEnd",
2105
+ ontouchmove: "onTouchMove",
2106
+ ontouchstart: "onTouchStart",
2107
+ onwheel: "onWheel"
2108
+ };
2109
+
2110
+ // src/index.ts
2111
+ function getReactNode(node, options) {
2112
+ const { key, level, ...rest } = options;
2113
+ switch (node.nodeType) {
2114
+ case 1: {
2115
+ return React.createElement(
2116
+ parseName(node.nodeName),
2117
+ parseAttributes(node, key),
2118
+ parseChildren(node.childNodes, level, rest)
2119
+ );
2120
+ }
2121
+ case 3: {
2122
+ const nodeText = node.nodeValue?.toString() ?? "";
2123
+ if (!rest.allowWhiteSpaces && /^\s+$/.test(nodeText) && !/[\u00A0\u202F]/.test(nodeText)) {
2124
+ return null;
2125
+ }
2126
+ if (!node.parentNode) {
2127
+ return nodeText;
2128
+ }
2129
+ const parentNodeName = node.parentNode.nodeName.toLowerCase();
2130
+ if (noTextChildNodes.includes(parentNodeName)) {
2131
+ if (/\S/.test(nodeText)) {
2132
+ console.warn(
2133
+ `A textNode is not allowed inside '${parentNodeName}'. Your text "${nodeText}" will be ignored`
2134
+ );
2135
+ }
2136
+ return null;
2137
+ }
2138
+ return nodeText;
2139
+ }
2140
+ case 8: {
2141
+ return null;
2142
+ }
2143
+ case 11: {
2144
+ return parseChildren(node.childNodes, level, options);
2145
+ }
2146
+ /* c8 ignore next 3 */
2147
+ default: {
2148
+ return null;
2149
+ }
2150
+ }
2151
+ }
2152
+ function parseAttributes(node, reactKey) {
2153
+ const attributes = {
2154
+ key: reactKey
2155
+ };
2156
+ if (node instanceof Element) {
2157
+ const nodeClassNames = node.getAttribute("class");
2158
+ if (nodeClassNames) {
2159
+ attributes.className = nodeClassNames;
2160
+ }
2161
+ [...node.attributes].forEach((d) => {
2162
+ switch (d.name) {
2163
+ // this is manually handled above, so break;
2164
+ case "class":
2165
+ break;
2166
+ case "style":
2167
+ attributes[d.name] = styleToObject(d.value);
2168
+ break;
2169
+ case "allowfullscreen":
2170
+ case "allowpaymentrequest":
2171
+ case "async":
2172
+ case "autofocus":
2173
+ case "autoplay":
2174
+ case "checked":
2175
+ case "controls":
2176
+ case "default":
2177
+ case "defer":
2178
+ case "disabled":
2179
+ case "formnovalidate":
2180
+ case "hidden":
2181
+ case "ismap":
2182
+ case "itemscope":
2183
+ case "loop":
2184
+ case "multiple":
2185
+ case "muted":
2186
+ case "nomodule":
2187
+ case "novalidate":
2188
+ case "open":
2189
+ case "readonly":
2190
+ case "required":
2191
+ case "reversed":
2192
+ case "selected":
2193
+ case "typemustmatch":
2194
+ attributes[possibleStandardNames[d.name] || d.name] = true;
2195
+ break;
2196
+ default:
2197
+ attributes[possibleStandardNames[d.name] || d.name] = d.value;
2198
+ }
2199
+ });
2200
+ }
2201
+ return attributes;
2202
+ }
2203
+ function parseChildren(childNodeList, level, options) {
2204
+ const children = [...childNodeList].map(
2205
+ (node, index) => convertFromNode(node, {
2206
+ ...options,
2207
+ index,
2208
+ level: level + 1
2209
+ })
2210
+ ).filter(Boolean);
2211
+ if (!children.length) {
2212
+ return null;
2213
+ }
2214
+ return children;
2215
+ }
2216
+ function parseName(nodeName) {
2217
+ if (/[a-z]+[A-Z]+[a-z]+/.test(nodeName)) {
2218
+ return nodeName;
2219
+ }
2220
+ return nodeName.toLowerCase();
2221
+ }
2222
+ function convert(input, options = {}) {
2223
+ if (typeof input === "string") {
2224
+ return convertFromString(input, options);
2225
+ }
2226
+ if (input instanceof Node) {
2227
+ return convertFromNode(input, options);
2228
+ }
2229
+ return null;
2230
+ }
2231
+ function convertFromNode(input, options = {}) {
2232
+ if (!input || !(input instanceof Node)) {
2233
+ return null;
2234
+ }
2235
+ const { actions = [], index = 0, level = 0, randomKey } = options;
2236
+ let node = input;
2237
+ let key = `${level}-${index}`;
2238
+ const result = [];
2239
+ if (randomKey && level === 0) {
2240
+ key = `${randomString$1()}-${key}`;
2241
+ }
2242
+ if (Array.isArray(actions)) {
2243
+ actions.forEach((action) => {
2244
+ if (action.condition(node, key, level)) {
2245
+ if (typeof action.pre === "function") {
2246
+ node = action.pre(node, key, level);
2247
+ if (!(node instanceof Node)) {
2248
+ node = input;
2249
+ if (process.env.NODE_ENV !== "production") {
2250
+ console.warn(
2251
+ "The `pre` method always must return a valid DomNode (instanceof Node) - your modification will be ignored (Hint: if you want to render a React-component, use the `post` method instead)"
2252
+ );
2253
+ }
2254
+ }
2255
+ }
2256
+ if (typeof action.post === "function") {
2257
+ result.push(action.post(node, key, level));
2258
+ }
2259
+ }
2260
+ });
2261
+ }
2262
+ if (result.length) {
2263
+ return result;
2264
+ }
2265
+ return getReactNode(node, { key, level, ...options });
2266
+ }
2267
+ function convertFromString(input, options = {}) {
2268
+ if (!input || typeof input !== "string") {
2269
+ return null;
2270
+ }
2271
+ const {
2272
+ includeAllNodes = false,
2273
+ nodeOnly = false,
2274
+ selector = "body > *",
2275
+ type = "text/html"
2276
+ } = options;
2277
+ try {
2278
+ const parser = new DOMParser();
2279
+ const document = parser.parseFromString(input, type);
2280
+ if (includeAllNodes) {
2281
+ const { childNodes } = document.body;
2282
+ if (nodeOnly) {
2283
+ return childNodes;
2284
+ }
2285
+ return [...childNodes].map((node2) => convertFromNode(node2, options));
2286
+ }
2287
+ const node = document.querySelector(selector) || document.body.childNodes[0];
2288
+ if (!(node instanceof Node)) {
2289
+ throw new TypeError("Error parsing input");
2290
+ }
2291
+ if (nodeOnly) {
2292
+ return node;
2293
+ }
2294
+ return convertFromNode(node, options);
2295
+ } catch (error) {
2296
+ if (process.env.NODE_ENV !== "production") {
2297
+ console.error(error);
2298
+ }
2299
+ }
2300
+ return null;
2301
+ }
2737
2302
 
2738
- // Returns class name of the object, if any.
2739
- function getClassName(propValue) {
2740
- if (!propValue.constructor || !propValue.constructor.name) {
2741
- return ANONYMOUS;
2742
- }
2743
- return propValue.constructor.name;
2744
- }
2303
+ var __defProp = Object.defineProperty;
2304
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2305
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
2745
2306
 
2746
- ReactPropTypes.checkPropTypes = checkPropTypes;
2747
- ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;
2748
- ReactPropTypes.PropTypes = ReactPropTypes;
2307
+ // src/config.ts
2308
+ var CACHE_NAME = "react-inlinesvg";
2309
+ var CACHE_MAX_RETRIES = 10;
2310
+ var STATUS = {
2311
+ IDLE: "idle",
2312
+ LOADING: "loading",
2313
+ LOADED: "loaded",
2314
+ FAILED: "failed",
2315
+ READY: "ready",
2316
+ UNSUPPORTED: "unsupported"
2317
+ };
2749
2318
 
2750
- return ReactPropTypes;
2751
- };
2752
- return factoryWithTypeCheckers;
2319
+ // src/modules/helpers.ts
2320
+ function randomCharacter(character) {
2321
+ return character[Math.floor(Math.random() * character.length)];
2322
+ }
2323
+ function canUseDOM() {
2324
+ return !!(typeof window !== "undefined" && window.document?.createElement);
2325
+ }
2326
+ function isSupportedEnvironment() {
2327
+ return supportsInlineSVG() && typeof window !== "undefined" && window !== null;
2328
+ }
2329
+ function omit(input, ...filter) {
2330
+ const output = {};
2331
+ for (const key in input) {
2332
+ if ({}.hasOwnProperty.call(input, key)) {
2333
+ if (!filter.includes(key)) {
2334
+ output[key] = input[key];
2335
+ }
2336
+ }
2337
+ }
2338
+ return output;
2339
+ }
2340
+ function randomString(length) {
2341
+ const letters = "abcdefghijklmnopqrstuvwxyz";
2342
+ const numbers = "1234567890";
2343
+ const charset = `${letters}${letters.toUpperCase()}${numbers}`;
2344
+ let R = "";
2345
+ for (let index = 0; index < length; index++) {
2346
+ R += randomCharacter(charset);
2347
+ }
2348
+ return R;
2349
+ }
2350
+ async function request(url, options) {
2351
+ const response = await fetch(url, options);
2352
+ const contentType = response.headers.get("content-type");
2353
+ const [fileType] = (contentType ?? "").split(/ ?; ?/);
2354
+ if (response.status > 299) {
2355
+ throw new Error("Not found");
2356
+ }
2357
+ if (!["image/svg+xml", "text/plain"].some((d) => fileType.includes(d))) {
2358
+ throw new Error(`Content type isn't valid: ${fileType}`);
2359
+ }
2360
+ return response.text();
2361
+ }
2362
+ function sleep(seconds = 1) {
2363
+ return new Promise((resolve) => {
2364
+ setTimeout(resolve, seconds * 1e3);
2365
+ });
2366
+ }
2367
+ function supportsInlineSVG() {
2368
+ if (!document) {
2369
+ return false;
2370
+ }
2371
+ const div = document.createElement("div");
2372
+ div.innerHTML = "<svg />";
2373
+ const svg = div.firstChild;
2374
+ return !!svg && svg.namespaceURI === "http://www.w3.org/2000/svg";
2375
+ }
2376
+
2377
+ // src/modules/cache.ts
2378
+ var CacheStore = class {
2379
+ constructor() {
2380
+ __publicField(this, "cacheApi");
2381
+ __publicField(this, "cacheStore");
2382
+ __publicField(this, "subscribers", []);
2383
+ __publicField(this, "isReady", false);
2384
+ this.cacheStore = /* @__PURE__ */ new Map();
2385
+ let cacheName = CACHE_NAME;
2386
+ let usePersistentCache = false;
2387
+ if (canUseDOM()) {
2388
+ cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;
2389
+ usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE && "caches" in window;
2390
+ }
2391
+ if (usePersistentCache) {
2392
+ caches.open(cacheName).then((cache) => {
2393
+ this.cacheApi = cache;
2394
+ }).catch((error) => {
2395
+ console.error(`Failed to open cache: ${error.message}`);
2396
+ this.cacheApi = void 0;
2397
+ }).finally(() => {
2398
+ this.isReady = true;
2399
+ const callbacks = [...this.subscribers];
2400
+ this.subscribers.length = 0;
2401
+ callbacks.forEach((callback) => {
2402
+ try {
2403
+ callback();
2404
+ } catch (error) {
2405
+ console.error(`Error in CacheStore subscriber callback: ${error.message}`);
2406
+ }
2407
+ });
2408
+ });
2409
+ } else {
2410
+ this.isReady = true;
2411
+ }
2412
+ }
2413
+ onReady(callback) {
2414
+ if (this.isReady) {
2415
+ callback();
2416
+ } else {
2417
+ this.subscribers.push(callback);
2418
+ }
2419
+ }
2420
+ async get(url, fetchOptions) {
2421
+ await (this.cacheApi ? this.fetchAndAddToPersistentCache(url, fetchOptions) : this.fetchAndAddToInternalCache(url, fetchOptions));
2422
+ return this.cacheStore.get(url)?.content ?? "";
2423
+ }
2424
+ set(url, data) {
2425
+ this.cacheStore.set(url, data);
2426
+ }
2427
+ isCached(url) {
2428
+ return this.cacheStore.get(url)?.status === STATUS.LOADED;
2429
+ }
2430
+ async fetchAndAddToInternalCache(url, fetchOptions) {
2431
+ const cache = this.cacheStore.get(url);
2432
+ if (cache?.status === STATUS.LOADING) {
2433
+ await this.handleLoading(url, async () => {
2434
+ this.cacheStore.set(url, { content: "", status: STATUS.IDLE });
2435
+ await this.fetchAndAddToInternalCache(url, fetchOptions);
2436
+ });
2437
+ return;
2438
+ }
2439
+ if (!cache?.content) {
2440
+ this.cacheStore.set(url, { content: "", status: STATUS.LOADING });
2441
+ try {
2442
+ const content = await request(url, fetchOptions);
2443
+ this.cacheStore.set(url, { content, status: STATUS.LOADED });
2444
+ } catch (error) {
2445
+ this.cacheStore.set(url, { content: "", status: STATUS.FAILED });
2446
+ throw error;
2447
+ }
2448
+ }
2449
+ }
2450
+ async fetchAndAddToPersistentCache(url, fetchOptions) {
2451
+ const cache = this.cacheStore.get(url);
2452
+ if (cache?.status === STATUS.LOADED) {
2453
+ return;
2454
+ }
2455
+ if (cache?.status === STATUS.LOADING) {
2456
+ await this.handleLoading(url, async () => {
2457
+ this.cacheStore.set(url, { content: "", status: STATUS.IDLE });
2458
+ await this.fetchAndAddToPersistentCache(url, fetchOptions);
2459
+ });
2460
+ return;
2461
+ }
2462
+ this.cacheStore.set(url, { content: "", status: STATUS.LOADING });
2463
+ const data = await this.cacheApi?.match(url);
2464
+ if (data) {
2465
+ const content = await data.text();
2466
+ this.cacheStore.set(url, { content, status: STATUS.LOADED });
2467
+ return;
2468
+ }
2469
+ try {
2470
+ await this.cacheApi?.add(new Request(url, fetchOptions));
2471
+ const response = await this.cacheApi?.match(url);
2472
+ const content = await response?.text() ?? "";
2473
+ this.cacheStore.set(url, { content, status: STATUS.LOADED });
2474
+ } catch (error) {
2475
+ this.cacheStore.set(url, { content: "", status: STATUS.FAILED });
2476
+ throw error;
2477
+ }
2478
+ }
2479
+ async handleLoading(url, callback) {
2480
+ for (let retryCount = 0; retryCount < CACHE_MAX_RETRIES; retryCount++) {
2481
+ if (this.cacheStore.get(url)?.status !== STATUS.LOADING) {
2482
+ return;
2483
+ }
2484
+ await sleep(0.1);
2485
+ }
2486
+ await callback();
2487
+ }
2488
+ keys() {
2489
+ return [...this.cacheStore.keys()];
2490
+ }
2491
+ data() {
2492
+ return [...this.cacheStore.entries()].map(([key, value]) => ({ [key]: value }));
2493
+ }
2494
+ async delete(url) {
2495
+ if (this.cacheApi) {
2496
+ await this.cacheApi.delete(url);
2497
+ }
2498
+ this.cacheStore.delete(url);
2499
+ }
2500
+ async clear() {
2501
+ if (this.cacheApi) {
2502
+ const keys = await this.cacheApi.keys();
2503
+ await Promise.allSettled(keys.map((key) => this.cacheApi.delete(key)));
2504
+ }
2505
+ this.cacheStore.clear();
2506
+ }
2507
+ };
2508
+ function usePrevious(state) {
2509
+ const ref = useRef(void 0);
2510
+ useEffect(() => {
2511
+ ref.current = state;
2512
+ });
2513
+ return ref.current;
2514
+ }
2515
+ function getNode(options) {
2516
+ const {
2517
+ baseURL,
2518
+ content,
2519
+ description,
2520
+ handleError,
2521
+ hash,
2522
+ preProcessor,
2523
+ title,
2524
+ uniquifyIDs = false
2525
+ } = options;
2526
+ try {
2527
+ const svgText = processSVG(content, preProcessor);
2528
+ const node = convert(svgText, { nodeOnly: true });
2529
+ if (!node || !(node instanceof SVGSVGElement)) {
2530
+ throw new Error("Could not convert the src to a DOM Node");
2531
+ }
2532
+ const svg = updateSVGAttributes(node, { baseURL, hash, uniquifyIDs });
2533
+ if (description) {
2534
+ const originalDesc = svg.querySelector("desc");
2535
+ if (originalDesc?.parentNode) {
2536
+ originalDesc.parentNode.removeChild(originalDesc);
2537
+ }
2538
+ const descElement = document.createElementNS("http://www.w3.org/2000/svg", "desc");
2539
+ descElement.innerHTML = description;
2540
+ svg.prepend(descElement);
2541
+ }
2542
+ if (typeof title !== "undefined") {
2543
+ const originalTitle = svg.querySelector("title");
2544
+ if (originalTitle?.parentNode) {
2545
+ originalTitle.parentNode.removeChild(originalTitle);
2546
+ }
2547
+ if (title) {
2548
+ const titleElement = document.createElementNS("http://www.w3.org/2000/svg", "title");
2549
+ titleElement.innerHTML = title;
2550
+ svg.prepend(titleElement);
2551
+ }
2552
+ }
2553
+ return svg;
2554
+ } catch (error) {
2555
+ return handleError(error);
2556
+ }
2753
2557
  }
2754
-
2755
- /**
2756
- * Copyright (c) 2013-present, Facebook, Inc.
2757
- *
2758
- * This source code is licensed under the MIT license found in the
2759
- * LICENSE file in the root directory of this source tree.
2760
- */
2761
-
2762
- var factoryWithThrowingShims;
2763
- var hasRequiredFactoryWithThrowingShims;
2764
-
2765
- function requireFactoryWithThrowingShims () {
2766
- if (hasRequiredFactoryWithThrowingShims) return factoryWithThrowingShims;
2767
- hasRequiredFactoryWithThrowingShims = 1;
2768
-
2769
- var ReactPropTypesSecret = /*@__PURE__*/ requireReactPropTypesSecret();
2770
-
2771
- function emptyFunction() {}
2772
- function emptyFunctionWithReset() {}
2773
- emptyFunctionWithReset.resetWarningCache = emptyFunction;
2774
-
2775
- factoryWithThrowingShims = function() {
2776
- function shim(props, propName, componentName, location, propFullName, secret) {
2777
- if (secret === ReactPropTypesSecret) {
2778
- // It is still safe when called from React.
2779
- return;
2780
- }
2781
- var err = new Error(
2782
- 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
2783
- 'Use PropTypes.checkPropTypes() to call them. ' +
2784
- 'Read more at http://fb.me/use-check-prop-types'
2785
- );
2786
- err.name = 'Invariant Violation';
2787
- throw err;
2788
- } shim.isRequired = shim;
2789
- function getShim() {
2790
- return shim;
2791
- } // Important!
2792
- // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
2793
- var ReactPropTypes = {
2794
- array: shim,
2795
- bigint: shim,
2796
- bool: shim,
2797
- func: shim,
2798
- number: shim,
2799
- object: shim,
2800
- string: shim,
2801
- symbol: shim,
2802
-
2803
- any: shim,
2804
- arrayOf: getShim,
2805
- element: shim,
2806
- elementType: shim,
2807
- instanceOf: getShim,
2808
- node: shim,
2809
- objectOf: getShim,
2810
- oneOf: getShim,
2811
- oneOfType: getShim,
2812
- shape: getShim,
2813
- exact: getShim,
2814
-
2815
- checkPropTypes: emptyFunctionWithReset,
2816
- resetWarningCache: emptyFunction
2817
- };
2818
-
2819
- ReactPropTypes.PropTypes = ReactPropTypes;
2820
-
2821
- return ReactPropTypes;
2822
- };
2823
- return factoryWithThrowingShims;
2558
+ function processSVG(content, preProcessor) {
2559
+ if (preProcessor) {
2560
+ return preProcessor(content);
2561
+ }
2562
+ return content;
2824
2563
  }
2825
-
2826
- /**
2827
- * Copyright (c) 2013-present, Facebook, Inc.
2828
- *
2829
- * This source code is licensed under the MIT license found in the
2830
- * LICENSE file in the root directory of this source tree.
2831
- */
2832
-
2833
- var hasRequiredPropTypes;
2834
-
2835
- function requirePropTypes () {
2836
- if (hasRequiredPropTypes) return propTypes.exports;
2837
- hasRequiredPropTypes = 1;
2838
- if (process.env.NODE_ENV !== 'production') {
2839
- var ReactIs = requireReactIs();
2840
-
2841
- // By explicitly using `prop-types` you are opting into new development behavior.
2842
- // http://fb.me/prop-types-in-prod
2843
- var throwOnDirectAccess = true;
2844
- propTypes.exports = /*@__PURE__*/ requireFactoryWithTypeCheckers()(ReactIs.isElement, throwOnDirectAccess);
2845
- } else {
2846
- // By explicitly using `prop-types` you are opting into new production behavior.
2847
- // http://fb.me/prop-types-in-prod
2848
- propTypes.exports = /*@__PURE__*/ requireFactoryWithThrowingShims()();
2849
- }
2850
- return propTypes.exports;
2564
+ function updateSVGAttributes(node, options) {
2565
+ const { baseURL = "", hash, uniquifyIDs } = options;
2566
+ const replaceableAttributes = ["id", "href", "xlink:href", "xlink:role", "xlink:arcrole"];
2567
+ const linkAttributes = ["href", "xlink:href"];
2568
+ const isDataValue = (name, value) => linkAttributes.includes(name) && (value ? !value.includes("#") : false);
2569
+ if (!uniquifyIDs) {
2570
+ return node;
2571
+ }
2572
+ [...node.children].forEach((d) => {
2573
+ if (d.attributes?.length) {
2574
+ const attributes = Object.values(d.attributes).map((a) => {
2575
+ const attribute = a;
2576
+ const match = /url\((.*?)\)/.exec(a.value);
2577
+ if (match?.[1]) {
2578
+ attribute.value = a.value.replace(match[0], `url(${baseURL}${match[1]}__${hash})`);
2579
+ }
2580
+ return attribute;
2581
+ });
2582
+ replaceableAttributes.forEach((r) => {
2583
+ const attribute = attributes.find((a) => a.name === r);
2584
+ if (attribute && !isDataValue(r, attribute.value)) {
2585
+ attribute.value = `${attribute.value}__${hash}`;
2586
+ }
2587
+ });
2588
+ }
2589
+ if (d.children.length) {
2590
+ return updateSVGAttributes(d, options);
2591
+ }
2592
+ return d;
2593
+ });
2594
+ return node;
2851
2595
  }
2852
2596
 
2853
- var propTypesExports = /*@__PURE__*/ requirePropTypes();
2854
- var PropTypes = /*@__PURE__*/getDefaultExportFromCjs(propTypesExports);
2855
-
2856
- const stringOrNumber = PropTypes.oneOfType([PropTypes.string, PropTypes.number]);
2857
- // media types
2858
- const types = {
2859
- all: PropTypes.bool,
2860
- grid: PropTypes.bool,
2861
- aural: PropTypes.bool,
2862
- braille: PropTypes.bool,
2863
- handheld: PropTypes.bool,
2864
- print: PropTypes.bool,
2865
- projection: PropTypes.bool,
2866
- screen: PropTypes.bool,
2867
- tty: PropTypes.bool,
2868
- tv: PropTypes.bool,
2869
- embossed: PropTypes.bool
2870
- };
2871
- // properties that match media queries
2872
- const matchers = {
2873
- orientation: PropTypes.oneOf(['portrait', 'landscape']),
2874
- scan: PropTypes.oneOf(['progressive', 'interlace']),
2875
- aspectRatio: PropTypes.string,
2876
- deviceAspectRatio: PropTypes.string,
2877
- height: stringOrNumber,
2878
- deviceHeight: stringOrNumber,
2879
- width: stringOrNumber,
2880
- deviceWidth: stringOrNumber,
2881
- color: PropTypes.bool,
2882
- colorIndex: PropTypes.bool,
2883
- monochrome: PropTypes.bool,
2884
- resolution: stringOrNumber,
2885
- type: Object.keys(types)
2886
- };
2887
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
2888
- const { type, ...featureMatchers } = matchers;
2889
- // media features
2890
- const features = {
2891
- minAspectRatio: PropTypes.string,
2892
- maxAspectRatio: PropTypes.string,
2893
- minDeviceAspectRatio: PropTypes.string,
2894
- maxDeviceAspectRatio: PropTypes.string,
2895
- minHeight: stringOrNumber,
2896
- maxHeight: stringOrNumber,
2897
- minDeviceHeight: stringOrNumber,
2898
- maxDeviceHeight: stringOrNumber,
2899
- minWidth: stringOrNumber,
2900
- maxWidth: stringOrNumber,
2901
- minDeviceWidth: stringOrNumber,
2902
- maxDeviceWidth: stringOrNumber,
2903
- minColor: PropTypes.number,
2904
- maxColor: PropTypes.number,
2905
- minColorIndex: PropTypes.number,
2906
- maxColorIndex: PropTypes.number,
2907
- minMonochrome: PropTypes.number,
2908
- maxMonochrome: PropTypes.number,
2909
- minResolution: stringOrNumber,
2910
- maxResolution: stringOrNumber,
2911
- ...featureMatchers
2912
- };
2913
- const all = { ...types, ...features };
2914
- var mq = {
2915
- all: all};
2916
-
2917
- const negate = (cond) => `not ${cond}`;
2918
- const keyVal = (k, v) => {
2919
- const realKey = hyphenateStyleName(k);
2920
- // px shorthand
2921
- if (typeof v === 'number') {
2922
- v = `${v}px`;
2597
+ // src/index.tsx
2598
+ var cacheStore;
2599
+ function ReactInlineSVG(props) {
2600
+ const {
2601
+ cacheRequests = true,
2602
+ children = null,
2603
+ description,
2604
+ fetchOptions,
2605
+ innerRef,
2606
+ loader = null,
2607
+ onError,
2608
+ onLoad,
2609
+ src,
2610
+ title,
2611
+ uniqueHash
2612
+ } = props;
2613
+ const [state, setState] = useReducer(
2614
+ (previousState2, nextState) => ({
2615
+ ...previousState2,
2616
+ ...nextState
2617
+ }),
2618
+ {
2619
+ content: "",
2620
+ element: null,
2621
+ isCached: cacheRequests && cacheStore.isCached(props.src),
2622
+ status: STATUS.IDLE
2623
+ }
2624
+ );
2625
+ const { content, element, isCached, status } = state;
2626
+ const previousProps = usePrevious(props);
2627
+ const previousState = usePrevious(state);
2628
+ const hash = useRef(uniqueHash ?? randomString(8));
2629
+ const isActive = useRef(false);
2630
+ const isInitialized = useRef(false);
2631
+ const handleError = useCallback(
2632
+ (error) => {
2633
+ if (isActive.current) {
2634
+ setState({
2635
+ status: error.message === "Browser does not support SVG" ? STATUS.UNSUPPORTED : STATUS.FAILED
2636
+ });
2637
+ onError?.(error);
2638
+ }
2639
+ },
2640
+ [onError]
2641
+ );
2642
+ const handleLoad = useCallback((loadedContent, hasCache = false) => {
2643
+ if (isActive.current) {
2644
+ setState({
2645
+ content: loadedContent,
2646
+ isCached: hasCache,
2647
+ status: STATUS.LOADED
2648
+ });
2649
+ }
2650
+ }, []);
2651
+ const fetchContent = useCallback(async () => {
2652
+ const responseContent = await request(src, fetchOptions);
2653
+ handleLoad(responseContent);
2654
+ }, [fetchOptions, handleLoad, src]);
2655
+ const getElement = useCallback(() => {
2656
+ try {
2657
+ const node = getNode({ ...props, handleError, hash: hash.current, content });
2658
+ const convertedElement = convert(node);
2659
+ if (!convertedElement || !isValidElement(convertedElement)) {
2660
+ throw new Error("Could not convert the src to a React element");
2661
+ }
2662
+ setState({
2663
+ element: convertedElement,
2664
+ status: STATUS.READY
2665
+ });
2666
+ } catch (error) {
2667
+ handleError(error);
2923
2668
  }
2924
- if (v === true) {
2925
- return realKey;
2669
+ }, [content, handleError, props]);
2670
+ const getContent = useCallback(async () => {
2671
+ const dataURI = /^data:image\/svg[^,]*?(;base64)?,(.*)/u.exec(src);
2672
+ let inlineSrc;
2673
+ if (dataURI) {
2674
+ inlineSrc = dataURI[1] ? window.atob(dataURI[2]) : decodeURIComponent(dataURI[2]);
2675
+ } else if (src.includes("<svg")) {
2676
+ inlineSrc = src;
2926
2677
  }
2927
- if (v === false) {
2928
- return negate(realKey);
2678
+ if (inlineSrc) {
2679
+ handleLoad(inlineSrc);
2680
+ return;
2929
2681
  }
2930
- return `(${realKey}: ${v})`;
2931
- };
2932
- const join = (conds) => conds.join(' and ');
2933
- const toQuery = (obj) => {
2934
- const rules = [];
2935
- Object.keys(mq.all).forEach((k) => {
2936
- const v = obj[k];
2937
- if (v != null) {
2938
- rules.push(keyVal(k, v));
2682
+ try {
2683
+ if (cacheRequests) {
2684
+ const cachedContent = await cacheStore.get(src, fetchOptions);
2685
+ handleLoad(cachedContent, true);
2686
+ } else {
2687
+ await fetchContent();
2688
+ }
2689
+ } catch (error) {
2690
+ handleError(error);
2691
+ }
2692
+ }, [cacheRequests, fetchContent, fetchOptions, handleError, handleLoad, src]);
2693
+ const load = useCallback(async () => {
2694
+ if (isActive.current) {
2695
+ setState({
2696
+ content: "",
2697
+ element: null,
2698
+ isCached: false,
2699
+ status: STATUS.LOADING
2700
+ });
2701
+ }
2702
+ }, []);
2703
+ useEffect(
2704
+ () => {
2705
+ isActive.current = true;
2706
+ if (!canUseDOM() || isInitialized.current) {
2707
+ return void 0;
2708
+ }
2709
+ try {
2710
+ if (status === STATUS.IDLE) {
2711
+ if (!isSupportedEnvironment()) {
2712
+ throw new Error("Browser does not support SVG");
2713
+ }
2714
+ if (!src) {
2715
+ throw new Error("Missing src");
2716
+ }
2717
+ load();
2939
2718
  }
2940
- });
2941
- return join(rules);
2942
- };
2943
-
2944
- const Context = createContext(undefined);
2945
-
2946
- const makeQuery = (settings) => settings.query || toQuery(settings);
2947
- const hyphenateKeys = (obj) => {
2948
- if (!obj)
2949
- return undefined;
2950
- const keys = Object.keys(obj);
2951
- return keys.reduce((result, key) => {
2952
- result[hyphenateStyleName(key)] = obj[key];
2953
- return result;
2954
- }, {});
2955
- };
2956
- const useIsUpdate = () => {
2957
- const ref = useRef(false);
2958
- useEffect(() => {
2959
- ref.current = true;
2960
- }, []);
2961
- return ref.current;
2962
- };
2963
- const useDevice = (deviceFromProps) => {
2964
- const deviceFromContext = useContext(Context);
2965
- const getDevice = () => hyphenateKeys(deviceFromProps) || hyphenateKeys(deviceFromContext);
2966
- const [device, setDevice] = useState(getDevice);
2967
- useEffect(() => {
2968
- const newDevice = getDevice();
2969
- if (!shallowEqualObjects(device, newDevice)) {
2970
- setDevice(newDevice);
2719
+ } catch (error) {
2720
+ handleError(error);
2721
+ }
2722
+ isInitialized.current = true;
2723
+ return () => {
2724
+ isActive.current = false;
2725
+ };
2726
+ },
2727
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2728
+ []
2729
+ );
2730
+ useEffect(() => {
2731
+ if (!canUseDOM() || !previousProps) {
2732
+ return;
2733
+ }
2734
+ if (previousProps.src !== src) {
2735
+ if (!src) {
2736
+ handleError(new Error("Missing src"));
2737
+ return;
2738
+ }
2739
+ load();
2740
+ }
2741
+ }, [handleError, load, previousProps, src]);
2742
+ useEffect(() => {
2743
+ if (status === STATUS.LOADED) {
2744
+ getElement();
2745
+ }
2746
+ }, [status, getElement]);
2747
+ useEffect(() => {
2748
+ if (!canUseDOM() || !previousProps || previousProps.src !== src) {
2749
+ return;
2750
+ }
2751
+ if (previousProps.title !== title || previousProps.description !== description) {
2752
+ getElement();
2753
+ }
2754
+ }, [description, getElement, previousProps, src, title]);
2755
+ useEffect(() => {
2756
+ if (!previousState) {
2757
+ return;
2758
+ }
2759
+ switch (status) {
2760
+ case STATUS.LOADING: {
2761
+ if (previousState.status !== STATUS.LOADING) {
2762
+ getContent();
2971
2763
  }
2972
- }, [deviceFromProps, deviceFromContext]);
2973
- return device;
2974
- };
2975
- const useQuery = (settings) => {
2976
- const getQuery = () => makeQuery(settings);
2977
- const [query, setQuery] = useState(getQuery);
2978
- useEffect(() => {
2979
- const newQuery = getQuery();
2980
- if (query !== newQuery) {
2981
- setQuery(newQuery);
2764
+ break;
2765
+ }
2766
+ case STATUS.LOADED: {
2767
+ if (previousState.status !== STATUS.LOADED) {
2768
+ getElement();
2982
2769
  }
2983
- }, [settings]);
2984
- return query;
2985
- };
2986
- const useMatchMedia = (query, device) => {
2987
- const getMatchMedia = () => matchMedia(query, device || {}, !!device);
2988
- const [mq, setMq] = useState(getMatchMedia);
2989
- const isUpdate = useIsUpdate();
2990
- useEffect(() => {
2991
- if (isUpdate) {
2992
- // skip on mounting, it has already been set
2993
- const newMq = getMatchMedia();
2994
- setMq(newMq);
2995
- return () => {
2996
- if (newMq) {
2997
- newMq.dispose();
2998
- }
2999
- };
2770
+ break;
2771
+ }
2772
+ case STATUS.READY: {
2773
+ if (previousState.status !== STATUS.READY) {
2774
+ onLoad?.(src, isCached);
2775
+ }
2776
+ break;
2777
+ }
2778
+ }
2779
+ }, [getContent, getElement, isCached, onLoad, previousState, src, status]);
2780
+ const elementProps = omit(
2781
+ props,
2782
+ "baseURL",
2783
+ "cacheRequests",
2784
+ "children",
2785
+ "description",
2786
+ "fetchOptions",
2787
+ "innerRef",
2788
+ "loader",
2789
+ "onError",
2790
+ "onLoad",
2791
+ "preProcessor",
2792
+ "src",
2793
+ "title",
2794
+ "uniqueHash",
2795
+ "uniquifyIDs"
2796
+ );
2797
+ if (!canUseDOM()) {
2798
+ return loader;
2799
+ }
2800
+ if (element) {
2801
+ return cloneElement(element, {
2802
+ ref: innerRef,
2803
+ ...elementProps
2804
+ });
2805
+ }
2806
+ if ([STATUS.UNSUPPORTED, STATUS.FAILED].includes(status)) {
2807
+ return children;
2808
+ }
2809
+ return loader;
2810
+ }
2811
+ function InlineSVG(props) {
2812
+ if (!cacheStore) {
2813
+ cacheStore = new CacheStore();
2814
+ }
2815
+ const { loader } = props;
2816
+ const [isReady, setReady] = useState(cacheStore.isReady);
2817
+ useEffect(() => {
2818
+ if (isReady) {
2819
+ return;
2820
+ }
2821
+ cacheStore.onReady(() => {
2822
+ setReady(true);
2823
+ });
2824
+ }, [isReady]);
2825
+ if (!isReady) {
2826
+ return loader;
2827
+ }
2828
+ return /* @__PURE__ */ React__default.createElement(ReactInlineSVG, { ...props });
2829
+ }
2830
+
2831
+ const useAppearanceConfig = (appearance, componentConfig, isDisabled) => {
2832
+ const appearanceConfig = useMemo(() => {
2833
+ if (appearance) {
2834
+ const appearanceProps = appearance.split(' ').reduce((resultConfig, appearanceKey) => ({
2835
+ ...resultConfig,
2836
+ ...componentConfig.appearance?.[appearanceKey],
2837
+ }), {});
2838
+ if (isDisabled &&
2839
+ (componentConfig?.appearance?.disabled ||
2840
+ componentConfig?.appearance?.disabledPrimary)) {
2841
+ Object.assign(appearanceProps, componentConfig?.appearance?.disabled ||
2842
+ componentConfig?.appearance?.disabledPrimary);
2843
+ }
2844
+ return appearanceProps;
3000
2845
  }
3001
- }, [query, device]);
3002
- return mq;
3003
- };
3004
- const useMatches = (mediaQuery) => {
3005
- const [matches, setMatches] = useState(mediaQuery.matches);
3006
- useEffect(() => {
3007
- const updateMatches = (ev) => {
3008
- setMatches(ev.matches);
3009
- };
3010
- mediaQuery.addListener(updateMatches);
3011
- setMatches(mediaQuery.matches);
3012
- return () => {
3013
- mediaQuery.removeListener(updateMatches);
3014
- };
3015
- }, [mediaQuery]);
3016
- return matches;
3017
- };
3018
- const useMediaQuery = (settings, device, onChange) => {
3019
- const deviceSettings = useDevice(device);
3020
- const query = useQuery(settings);
3021
- if (!query)
3022
- throw new Error('Invalid or missing MediaQuery!');
3023
- const mq = useMatchMedia(query, deviceSettings);
3024
- const matches = useMatches(mq);
3025
- useIsUpdate();
3026
- useEffect(() => {
3027
- }, [matches]);
3028
- useEffect(() => () => {
3029
- if (mq) {
3030
- mq.dispose();
2846
+ if (isDisabled) {
2847
+ return (componentConfig?.appearance?.disabled ||
2848
+ componentConfig?.appearance?.disabledPrimary);
3031
2849
  }
3032
- }, []);
3033
- return matches;
2850
+ return {};
2851
+ }, [appearance, componentConfig?.appearance, isDisabled]);
2852
+ return appearanceConfig;
2853
+ };
2854
+
2855
+ const STATUSES$1 = {
2856
+ error: 'error',
2857
+ info: 'info',
2858
+ success: 'success',
2859
+ warning: 'warning',
3034
2860
  };
2861
+ const NotificationsContext$1 = createContext([]);
2862
+ /* eslint-disable @typescript-eslint/no-unused-vars */
2863
+ const NotificationsAPIContext$1 = createContext({
2864
+ hideNotifications: (targetId) => { },
2865
+ showNotification: (notification, onClose) => { },
2866
+ notificationStatuses: STATUSES$1,
2867
+ });
2868
+ function useNotifications() {
2869
+ return useContext(NotificationsContext$1);
2870
+ }
2871
+ function useNotificationsAPI() {
2872
+ return useContext(NotificationsAPIContext$1);
2873
+ }
3035
2874
 
3036
2875
  var tablet = "48em";
3037
2876
  var mediaQueries = {
@@ -3148,12 +2987,27 @@ function useMediaQueries(userDevice = {}) {
3148
2987
  return deviceTypes;
3149
2988
  }
3150
2989
 
2990
+ /**
2991
+ * @example
2992
+ * mergeAppearanceKeys(' ', '1', undefined, '2', '1') === '1 2'
2993
+ */
2994
+ const mergeAppearanceKeys = (...appearances) => {
2995
+ const trimmedAppearances = appearances
2996
+ .map((appearance) => appearance?.trim())
2997
+ .filter(Boolean);
2998
+ if (trimmedAppearances.length < 2) {
2999
+ return trimmedAppearances[0] ?? '';
3000
+ }
3001
+ const uniqueAppearances = Array.from(new Set(trimmedAppearances));
3002
+ return uniqueAppearances.join(' ');
3003
+ };
3004
+
3151
3005
  const setViewportProperty = () => {
3152
3006
  const vh = window.innerHeight * 0.01;
3153
3007
  document.documentElement.style.setProperty('--vh', `${vh}px`);
3154
3008
  };
3155
3009
 
3156
- const UserDeviceContext = createContext({
3010
+ const UserDeviceContext$1 = createContext({
3157
3011
  isMobile: false,
3158
3012
  isTablet: false,
3159
3013
  isDesktop: false,
@@ -3161,7 +3015,7 @@ const UserDeviceContext = createContext({
3161
3015
  deviceCurrentType: '',
3162
3016
  deviceTypesList: [],
3163
3017
  });
3164
- const UIProvider = memo(function UIProvider(props) {
3018
+ memo(function UIProvider(props) {
3165
3019
  const { userDeviceState = {}, children } = props;
3166
3020
  /** NOTE:
3167
3021
  * Remember that the "useMediaQueries" hook works by next scenario:
@@ -3207,10 +3061,10 @@ const UIProvider = memo(function UIProvider(props) {
3207
3061
  setViewportProperty();
3208
3062
  window.addEventListener('resize', setViewportProperty);
3209
3063
  }, []);
3210
- return (jsx(UserDeviceContext.Provider, { value: deviceContextState, children: children }));
3064
+ return (jsx(UserDeviceContext$1.Provider, { value: deviceContextState, children: children }));
3211
3065
  });
3212
3066
  function useUserDeviceContext() {
3213
- const context = useContext(UserDeviceContext);
3067
+ const context = useContext(UserDeviceContext$1);
3214
3068
  if (!context) {
3215
3069
  throw new Error('useUserDeviceContext is not defined');
3216
3070
  }
@@ -3691,28 +3545,6 @@ const getTargetStyleAttributeKey = (styleKey, styleValue = '') => {
3691
3545
  return styleAttributeKey;
3692
3546
  };
3693
3547
 
3694
- const linkConfig = {
3695
- LinkComponent: 'a'};
3696
- function LinkWrapper(props) {
3697
- const { href, LinkComponent, rel, target, children, ...otherProps } = props;
3698
- if (href) {
3699
- const Component = LinkComponent || linkConfig.LinkComponent;
3700
- {
3701
- return (jsx(Component, { href: href, rel: rel, target: target, ...otherProps, children: children }));
3702
- }
3703
- }
3704
- else if (LinkComponent) {
3705
- return jsx(LinkComponent, { ...otherProps, children: children });
3706
- }
3707
- return React__default.Children.toArray(children)
3708
- .filter(Boolean)
3709
- .map((child) => {
3710
- return React__default.isValidElement(child)
3711
- ? React__default.cloneElement(child, otherProps)
3712
- : child;
3713
- });
3714
- }
3715
-
3716
3548
  const textAppearanceSize = {
3717
3549
  sizeXXL: {
3718
3550
  size: 'xxl',
@@ -3766,95 +3598,6 @@ function Text(props) {
3766
3598
  `text-color_active_${textColorActiveClass}`, textFontClass && `text-font_${textFontClass}`, textStyleClass && `text-style_${textStyleClass}`, textWrapClass && `word-wrap_${textWrapClass}`, textTruncateClass && `text-truncate_${textTruncateClass}`, isSkeleton && 'text_skeleton', widthClass && `width_${widthClass}`, cursorClass && `cursor_${cursorClass}`, onClick && (cursor || 'cursor_type_pointer')), "data-testid": dataTestId, "data-tour": dataTour, style: Object.assign({}, textStyles, style), onClick: onClick, onDoubleClick: onDoubleClick, children: [before, children, after] }));
3767
3599
  }
3768
3600
 
3769
- const UrlAssetPrefixContext = createContext({
3770
- assetPrefix: undefined,
3771
- ignorePathsList: undefined,
3772
- });
3773
-
3774
- const urlPropsList = ['src', 'imageSrc', 'svgSrc', 'placeholderUrl'];
3775
- /**
3776
- * HOC, который добавляет assetPrefix к URL-пропсам.
3777
- *
3778
- * @template P - Тип пропсов оборачиваемого компонента.
3779
- * @template T - Тип ref (если используется forwardRef).
3780
- * @template Check - Проверка на наличие хотя бы одного URL-пропа.
3781
- *
3782
- * @param WrappedComponent - Компонент, который оборачиваем.
3783
- * @param _error - Проверка: если ни одного URL-пропа нет, будет ошибка компиляции.
3784
- *
3785
- * @example
3786
- * const A = (props: { src?: string }) => <div />;
3787
- * urlWithAssetPrefix(A); // ✅ OK
3788
- *
3789
- * const B = (props: { id: string }) => <div />;
3790
- * urlWithAssetPrefix(B); // ❌ TS ошибка (нет url-пропов)
3791
- */
3792
- const urlWithAssetPrefix = (WrappedComponent, ..._error) => {
3793
- const HOC = React__default.forwardRef(function HOC(props, ref) {
3794
- const { assetPrefix, ignorePathsList } = useContext(UrlAssetPrefixContext);
3795
- const overrideProps = urlPropsList.reduce((resultProps, propKey) => {
3796
- let url = props[propKey];
3797
- if (url && typeof url === 'string') {
3798
- if (assetPrefix) {
3799
- const isNeedAssetPrefix = checkIsNeedAssetPrefix(url, assetPrefix, ignorePathsList);
3800
- if (isNeedAssetPrefix) {
3801
- const prefixPath = formatURL(assetPrefix).slice(0, -1);
3802
- url = `${prefixPath}${url}`;
3803
- }
3804
- }
3805
- resultProps[propKey] = url;
3806
- }
3807
- return resultProps;
3808
- }, {});
3809
- return jsx(WrappedComponent, { ...props, ...overrideProps, ref: ref });
3810
- });
3811
- return HOC;
3812
- };
3813
- const checkIsNeedAssetPrefix = (url, assetPrefix, ignorePathsList = []) => {
3814
- // Ignore prefix if:
3815
- const isPrefixIgnore =
3816
- // Url is absolute
3817
- url.startsWith('http:') ||
3818
- url.startsWith('https:') ||
3819
- // Url is data string
3820
- url.startsWith('data:') ||
3821
- // Url already have prefix
3822
- url.startsWith(assetPrefix);
3823
- if (isPrefixIgnore) {
3824
- return false;
3825
- }
3826
- // And check special paths for ignore prefix
3827
- for (const urlPath of ignorePathsList) {
3828
- if (urlPath instanceof RegExp) {
3829
- if (urlPath.test(url)) {
3830
- return false;
3831
- }
3832
- }
3833
- else {
3834
- if (formatURL(url).startsWith(formatURL(urlPath))) {
3835
- return false;
3836
- }
3837
- }
3838
- }
3839
- // Need to add prefix to url
3840
- return true;
3841
- };
3842
-
3843
- /**
3844
- * @example
3845
- * mergeAppearanceKeys(' ', '1', undefined, '2', '1') === '1 2'
3846
- */
3847
- const mergeAppearanceKeys = (...appearances) => {
3848
- const trimmedAppearances = appearances
3849
- .map((appearance) => appearance?.trim())
3850
- .filter(Boolean);
3851
- if (trimmedAppearances.length < 2) {
3852
- return trimmedAppearances[0] ?? '';
3853
- }
3854
- const uniqueAppearances = Array.from(new Set(trimmedAppearances));
3855
- return uniqueAppearances.join(' ');
3856
- };
3857
-
3858
3601
  const badgeAppearanceAccent = {
3859
3602
  accentPrimary: {
3860
3603
  fill: 'accentPrimary',
@@ -4111,6 +3854,28 @@ function Badge(props) {
4111
3854
  (value && (jsx(Text, { className: "badge__value", size: textSize, textColor: textColor, children: value })))] }));
4112
3855
  }
4113
3856
 
3857
+ const linkConfig = {
3858
+ LinkComponent: 'a'};
3859
+ function LinkWrapper(props) {
3860
+ const { href, LinkComponent, rel, target, children, ...otherProps } = props;
3861
+ if (href) {
3862
+ const Component = LinkComponent || linkConfig.LinkComponent;
3863
+ {
3864
+ return (jsx(Component, { href: href, rel: rel, target: target, ...otherProps, children: children }));
3865
+ }
3866
+ }
3867
+ else if (LinkComponent) {
3868
+ return jsx(LinkComponent, { ...otherProps, children: children });
3869
+ }
3870
+ return React__default.Children.toArray(children)
3871
+ .filter(Boolean)
3872
+ .map((child) => {
3873
+ return React__default.isValidElement(child)
3874
+ ? React__default.cloneElement(child, otherProps)
3875
+ : child;
3876
+ });
3877
+ }
3878
+
4114
3879
  const titleAppearanceAccent = {
4115
3880
  accentPrimary: {
4116
3881
  fill: 'accentPrimary',
@@ -4506,6 +4271,80 @@ const Tooltip = React__default.forwardRef(function Tooltip(props, ref) {
4506
4271
  : null, alignPosition && `tooltip_align-position_${alignPosition}`, alignDirectionClass && `align_${alignDirectionClass}`, alignClass && `align_${alignClass}`, elevationClass && `elevation_${elevationClass}`, centeringClass && `centering_${centeringClass}`, alignmentClass && `alignment_${alignmentClass}`, sizeClass && `tooltip_size_${sizeClass}`, isSkeleton && 'tooltip_skeleton', widthClass && `width_${widthClass}`), ref: tooltipElementRef, "data-testid": dataTestId, "data-tour": dataTour, style: tooltipStyles, onAnimationEnd: onAnimationEnd, children: [arrowPosition && (jsx("div", { className: clsx('tooltip__arrow', arrowPosition && `tooltip__arrow_position_${arrowPosition}`, fillClass && `fill_${fillClass}`), children: "\u00A0" })), before, jsxs("div", { className: clsx('tooltip__inner', borderWidthClass && `border-width_${borderWidthClass}`, borderColorClass && `border-color_${borderColorClass}`, borderTypeClass && `border_type_${borderTypeClass}`, fillClass && `fill_${fillClass}`, shapeClass && `shape_${shapeClass}`, shapeStrengthClass && `shape-strength_${shapeStrengthClass}`), children: [title && (jsx(Title, { className: "tooltip__title text", size: titleSize, textColor: titleColor, textWeight: titleWeight, children: title })), text && (jsx(Text, { className: "tooltip__text", size: textSize, textColor: textColor, textWeight: textWeight, children: text })), children] }), after] }));
4507
4272
  });
4508
4273
 
4274
+ const UrlAssetPrefixContext = createContext({
4275
+ assetPrefix: undefined,
4276
+ ignorePathsList: undefined,
4277
+ });
4278
+
4279
+ const urlPropsList = ['src', 'imageSrc', 'svgSrc', 'placeholderUrl'];
4280
+ /**
4281
+ * HOC, который добавляет assetPrefix к URL-пропсам.
4282
+ *
4283
+ * @template P - Тип пропсов оборачиваемого компонента.
4284
+ * @template T - Тип ref (если используется forwardRef).
4285
+ * @template Check - Проверка на наличие хотя бы одного URL-пропа.
4286
+ *
4287
+ * @param WrappedComponent - Компонент, который оборачиваем.
4288
+ * @param _error - Проверка: если ни одного URL-пропа нет, будет ошибка компиляции.
4289
+ *
4290
+ * @example
4291
+ * const A = (props: { src?: string }) => <div />;
4292
+ * urlWithAssetPrefix(A); // ✅ OK
4293
+ *
4294
+ * const B = (props: { id: string }) => <div />;
4295
+ * urlWithAssetPrefix(B); // ❌ TS ошибка (нет url-пропов)
4296
+ */
4297
+ const urlWithAssetPrefix = (WrappedComponent, ..._error) => {
4298
+ const HOC = React__default.forwardRef(function HOC(props, ref) {
4299
+ const { assetPrefix, ignorePathsList } = useContext(UrlAssetPrefixContext);
4300
+ const overrideProps = urlPropsList.reduce((resultProps, propKey) => {
4301
+ let url = props[propKey];
4302
+ if (url && typeof url === 'string') {
4303
+ if (assetPrefix) {
4304
+ const isNeedAssetPrefix = checkIsNeedAssetPrefix(url, assetPrefix, ignorePathsList);
4305
+ if (isNeedAssetPrefix) {
4306
+ const prefixPath = formatURL(assetPrefix).slice(0, -1);
4307
+ url = `${prefixPath}${url}`;
4308
+ }
4309
+ }
4310
+ resultProps[propKey] = url;
4311
+ }
4312
+ return resultProps;
4313
+ }, {});
4314
+ return jsx(WrappedComponent, { ...props, ...overrideProps, ref: ref });
4315
+ });
4316
+ return HOC;
4317
+ };
4318
+ const checkIsNeedAssetPrefix = (url, assetPrefix, ignorePathsList = []) => {
4319
+ // Ignore prefix if:
4320
+ const isPrefixIgnore =
4321
+ // Url is absolute
4322
+ url.startsWith('http:') ||
4323
+ url.startsWith('https:') ||
4324
+ // Url is data string
4325
+ url.startsWith('data:') ||
4326
+ // Url already have prefix
4327
+ url.startsWith(assetPrefix);
4328
+ if (isPrefixIgnore) {
4329
+ return false;
4330
+ }
4331
+ // And check special paths for ignore prefix
4332
+ for (const urlPath of ignorePathsList) {
4333
+ if (urlPath instanceof RegExp) {
4334
+ if (urlPath.test(url)) {
4335
+ return false;
4336
+ }
4337
+ }
4338
+ else {
4339
+ if (formatURL(url).startsWith(formatURL(urlPath))) {
4340
+ return false;
4341
+ }
4342
+ }
4343
+ }
4344
+ // Need to add prefix to url
4345
+ return true;
4346
+ };
4347
+
4509
4348
  const iconAppearanceAccent = {
4510
4349
  accentPrimary: {
4511
4350
  fill: 'accentPrimary',
@@ -5505,7 +5344,7 @@ const Button = React__default.forwardRef(function Button(props, ref) {
5505
5344
  ? 'button_type_label'
5506
5345
  : buttonTypeClass
5507
5346
  ? 'button_type_icon'
5508
- : '', borderWidthClass && `border-width_${borderWidthClass}`, borderColorClass && `border-color_${borderColorClass}`, borderTypeClass && `border_type_${borderTypeClass}`, fillClass && `fill_${fillClass}`, fillHoverClass && !isDisabled && `fill_hover_${fillHoverClass}`, shapeClass && `shape_${shapeClass}`, shapeStrengthClass && `shape-strength_${shapeStrengthClass}`, sizeClass && `button_size_${sizeClass}`, widthClass && `button_width_${widthClass}`, elevationClass && `elevation_${elevationClass}`, onClick && 'cursor_type_pointer', isDisabled && 'button_state_disabled cursor_type_default', Badge && 'button_type_badge', zeroPadding && 'button_reset-padding', zeroGap && 'button_reset-gap', isLoading && 'button_state_loading', isSkeleton && 'button_skeleton', isHolding && 'button_holding', holdState && `button_state_${holdState}`), type: htmlType, title: tooltip, "data-testid": dataTestId && `${dataTestId}-button`, "data-tour": dataTour, disabled: isDisabled, href: link || href, LinkComponent: "button", rel: rel, style: buttonStyles, target: target, onClick: onClick, onMouseDown: onMouseDown, onPointerCancel: onHoldEnd, onPointerDown: onHoldStart, onPointerLeave: onHoldEnd, onPointerUp: onHoldEnd, children: [isHolding && (jsx("div", { className: clsx('button__indication', `button__indication_${holdState}`), children: jsx("div", { className: "button__indication-item", children: "\u00A0" }) })), jsxs("div", { className: "button__wrapper", ref: ref, children: [isLoading && (jsx(Loader, { appearance: mergeAppearanceKeys(loaderAppearance, loaderAppearanceSize), className: clsx(className, 'button__loader'), type: loaderType, size: loaderSize, fill: loaderFill, itemFill: loaderItemFill })), before, (iconBefore || iconBeforeSrc) && (jsx(Icon, { appearance: mergeAppearanceKeys(iconBeforeAppearance, iconBeforeAppearanceSize), className: "button__icon_before", fill: iconBeforeFill, fillSize: iconBeforeFillSize, iconFill: iconBeforeFillIcon, iconSize: iconBeforeSize, imageSrc: iconBeforeSrc, shape: iconBeforeShape, SvgImage: iconBefore })), (icon || iconSrc) && (jsx(Icon, { appearance: mergeAppearanceKeys(iconAppearance, iconAppearanceSize), className: "button__icon", fill: iconFill, fillSize: iconFillSize, iconFill: iconFillIcon, iconSize: iconSize, imageSrc: iconSrc, shape: iconShape, SvgImage: icon })), (children || label) && (jsx(Text, { className: "button__label", width: labelTextWidth, size: labelTextSize, textColor: labelTextColor, textColorHover: labelTextColorHover, textTruncate: labelTextTruncate, textWeight: labelTextWeight, textWrap: labelTextWrap, style: labelStyles, children: children || label })), (iconAfter || iconAfterSrc) && (jsx(Icon, { appearance: mergeAppearanceKeys(iconAfterAppearance, iconAfterAppearanceSize), className: "button__icon_after", fill: iconAfterFill, fillSize: iconAfterFillSize, iconFill: iconAfterFillIcon, iconSize: iconAfterSize, imageSrc: iconAfterSrc, shape: iconAfterShape, SvgImage: iconAfter })), Badge, after] })] }));
5347
+ : '', borderWidthClass && `border-width_${borderWidthClass}`, borderColorClass && `border-color_${borderColorClass}`, borderTypeClass && `border_type_${borderTypeClass}`, fillClass && `fill_${fillClass}`, fillHoverClass && !isDisabled && `fill_hover_${fillHoverClass}`, shapeClass && `shape_${shapeClass}`, shapeStrengthClass && `shape-strength_${shapeStrengthClass}`, sizeClass && `button_size_${sizeClass}`, widthClass && `button_width_${widthClass}`, elevationClass && `elevation_${elevationClass}`, onClick && 'cursor_type_pointer', isDisabled && 'button_state_disabled cursor_type_default', Badge && 'button_type_badge', zeroPadding && 'button_reset-padding', zeroGap && 'button_reset-gap', isLoading && 'button_state_loading', isSkeleton && 'button_skeleton', isHolding && 'button_holding', holdState && `button_state_${holdState}`), type: htmlType, title: tooltip, "data-testid": dataTestId, "data-tour": dataTour, disabled: isDisabled, href: link || href, LinkComponent: "button", rel: rel, style: buttonStyles, target: target, onClick: onClick, onMouseDown: onMouseDown, onPointerCancel: onHoldEnd, onPointerDown: onHoldStart, onPointerLeave: onHoldEnd, onPointerUp: onHoldEnd, children: [isHolding && (jsx("div", { className: clsx('button__indication', `button__indication_${holdState}`), children: jsx("div", { className: "button__indication-item", children: "\u00A0" }) })), jsxs("div", { className: "button__wrapper", ref: ref, children: [isLoading && (jsx(Loader, { appearance: mergeAppearanceKeys(loaderAppearance, loaderAppearanceSize), className: clsx(className, 'button__loader'), type: loaderType, size: loaderSize, fill: loaderFill, itemFill: loaderItemFill })), before, (iconBefore || iconBeforeSrc) && (jsx(Icon, { appearance: mergeAppearanceKeys(iconBeforeAppearance, iconBeforeAppearanceSize), className: "button__icon_before", fill: iconBeforeFill, fillSize: iconBeforeFillSize, iconFill: iconBeforeFillIcon, iconSize: iconBeforeSize, imageSrc: iconBeforeSrc, shape: iconBeforeShape, SvgImage: iconBefore })), (icon || iconSrc) && (jsx(Icon, { appearance: mergeAppearanceKeys(iconAppearance, iconAppearanceSize), className: "button__icon", fill: iconFill, fillSize: iconFillSize, iconFill: iconFillIcon, iconSize: iconSize, imageSrc: iconSrc, shape: iconShape, SvgImage: icon })), (children || label) && (jsx(Text, { className: "button__label", width: labelTextWidth, size: labelTextSize, textColor: labelTextColor, textColorHover: labelTextColorHover, textTruncate: labelTextTruncate, textWeight: labelTextWeight, textWrap: labelTextWrap, style: labelStyles, children: children || label })), (iconAfter || iconAfterSrc) && (jsx(Icon, { appearance: mergeAppearanceKeys(iconAfterAppearance, iconAfterAppearanceSize), className: "button__icon_after", fill: iconAfterFill, fillSize: iconAfterFillSize, iconFill: iconAfterFillIcon, iconSize: iconAfterSize, imageSrc: iconAfterSrc, shape: iconAfterShape, SvgImage: iconAfter })), Badge, after] })] }));
5509
5348
  });
5510
5349
 
5511
5350
  var _path$3t;
@@ -5685,4 +5524,236 @@ function NotificationWrapper(props) {
5685
5524
  return (jsx("div", { className: clsx('notification', className), "data-testid": dataTestId, "data-tour": dataTour, children: jsx("div", { className: "notification__wrapper", children: notifications.map((notification) => (jsx(Notification, { id: notification.id, appearance: notification.appearance, type: notification.type, title: notification.title, status: notification.status, text: notification.text, buttonLabel: notification.buttonLabel, after: notification.after, closeIcon: notification.closeIcon, closeIconSrc: notification.closeIconSrc, isLoading: notification.isLoading, onClickButton: notification.onClickButton, onClickClose: hideNotifications }, notification.id))) }) }));
5686
5525
  }
5687
5526
 
5527
+ const STATUSES = {
5528
+ error: 'error',
5529
+ info: 'info',
5530
+ success: 'success',
5531
+ warning: 'warning',
5532
+ };
5533
+ const NotificationsContext = createContext([]);
5534
+ /* eslint-disable @typescript-eslint/no-unused-vars */
5535
+ const NotificationsAPIContext = createContext({
5536
+ hideNotifications: (targetId) => { },
5537
+ showNotification: (notification, onClose) => { },
5538
+ notificationStatuses: STATUSES,
5539
+ });
5540
+ /* eslint-enable @typescript-eslint/no-unused-vars */
5541
+ function NotificationsProvider(props) {
5542
+ const { initialNotificationsList = [], isLogRequestsErrors, children } = props;
5543
+ const [notificationsList, setNotificationsList] = useState(() => {
5544
+ // We need to set id to every notification item and original list also be have new id's
5545
+ return (initialNotificationsList || []).map((notificationItem) => {
5546
+ return createNotification(notificationItem, notificationItem.onClose);
5547
+ });
5548
+ });
5549
+ const hideNotifications = useCallback((targetId) => {
5550
+ // If not target, then nothing to hide
5551
+ if (!targetId) {
5552
+ return;
5553
+ }
5554
+ setNotificationsList((prevNotificationsList) => {
5555
+ const newState = prevNotificationsList.filter((notificationItem) => {
5556
+ // Check on need to hide, if current notification is target for hide
5557
+ const isNeedToHide = String(notificationItem.id) === String(targetId);
5558
+ // Callback for close if exists
5559
+ if (isNeedToHide) {
5560
+ clearTimeout(notificationItem._closeTimeout);
5561
+ // @typescript-eslint/no-unused-expressions
5562
+ notificationItem.onClose && notificationItem.onClose();
5563
+ }
5564
+ // Save in state if no need to hide
5565
+ return !isNeedToHide;
5566
+ });
5567
+ // Set new notifications list without target item to state
5568
+ return newState;
5569
+ });
5570
+ }, []);
5571
+ const showNotification = useCallback((notification, onClose) => {
5572
+ const newNotificationItem = createNotification(notification, onClose);
5573
+ setNotificationsList((prevNotificationsList) => {
5574
+ const newState = prevNotificationsList.slice();
5575
+ const existsNotificationIndex = newState.findIndex((notificationItem) => String(notificationItem.id) === String(newNotificationItem.id));
5576
+ // Add new notification
5577
+ if (existsNotificationIndex === -1) {
5578
+ return [...newState, newNotificationItem];
5579
+ }
5580
+ // Or update exists notification
5581
+ const updatedNotificationItem = newState[existsNotificationIndex];
5582
+ // Clear timeout to avoid close event for updated notification
5583
+ clearTimeout(updatedNotificationItem._closeTimeout);
5584
+ updatedNotificationItem._closeTimeout = undefined;
5585
+ // Replace exists notification by new one
5586
+ newState[existsNotificationIndex] = newNotificationItem;
5587
+ return newState;
5588
+ });
5589
+ if (newNotificationItem.closeByTime) {
5590
+ newNotificationItem._closeTimeout = setTimeout(() => hideNotifications(newNotificationItem.id), newNotificationItem.closeByTime);
5591
+ }
5592
+ return newNotificationItem;
5593
+ },
5594
+ // "hideNotifications" is never changed
5595
+ // eslint-disable-next-line react-hooks/exhaustive-deps
5596
+ []);
5597
+ const notificationsAPI = useMemo(() => ({
5598
+ hideNotifications: hideNotifications,
5599
+ notificationStatuses: STATUSES,
5600
+ showNotification: showNotification,
5601
+ }),
5602
+ // Functions is never changes, no sense to set as dependencies
5603
+ // eslint-disable-next-line
5604
+ []);
5605
+ useEffect(() => {
5606
+ // Set timeout for initial notifications list one time on first render
5607
+ notificationsList.forEach((notificationItem) => {
5608
+ if (notificationItem.closeByTime) {
5609
+ setTimeout(() => hideNotifications(notificationItem.id), notificationItem.closeByTime);
5610
+ }
5611
+ });
5612
+ // Show notifications on all requests errors.
5613
+ // Enable one time without disabling. Use "isLogging" on request config level
5614
+ // to disable notifications logger.
5615
+ if (isLogRequestsErrors) {
5616
+ axiosInstanceITCase.responseErrorHandler.loggerManager = {
5617
+ log: (responseError) => {
5618
+ if (responseError.message) {
5619
+ // prevent from showing many network errors
5620
+ const errorListToDedupe = ['network'];
5621
+ const id = errorListToDedupe.includes(responseError.key)
5622
+ ? responseError.key
5623
+ : undefined;
5624
+ showNotification({
5625
+ id: id,
5626
+ title: responseError.message,
5627
+ status: 'error',
5628
+ closeByTime: 4000,
5629
+ });
5630
+ }
5631
+ },
5632
+ };
5633
+ }
5634
+ // eslint-disable-next-line react-hooks/exhaustive-deps
5635
+ }, []);
5636
+ return (jsx(NotificationsAPIContext.Provider, { value: notificationsAPI, children: jsx(NotificationsContext.Provider, { value: notificationsList, children: children }) }));
5637
+ }
5638
+ const statusToAppearanceList = {
5639
+ error: 'errorPrimary sizeS solid rounded',
5640
+ info: 'infoPrimary sizeS solid rounded',
5641
+ success: 'successPrimary sizeS solid rounded',
5642
+ warning: 'warningPrimary sizeS solid rounded',
5643
+ };
5644
+ function createNotification(notification, onClose) {
5645
+ // Default notification item properties
5646
+ let id = v4().split('-')[0];
5647
+ let title = '';
5648
+ let text = '';
5649
+ let closeIcon = '';
5650
+ let closeIconSrc = '';
5651
+ let type = 'float';
5652
+ let buttonLabel = '';
5653
+ let status = STATUSES.warning;
5654
+ let closeByTime = 4500;
5655
+ let appearance = statusToAppearanceList[status];
5656
+ let after = null;
5657
+ let isLoading = false;
5658
+ let closeIconAppearance = '';
5659
+ let onClickButton = () => { };
5660
+ if (typeof notification === 'string') {
5661
+ text = notification;
5662
+ }
5663
+ else if (typeof notification === 'object') {
5664
+ id = String(notification.id ?? id);
5665
+ title = notification.title ?? title;
5666
+ text = notification.text ?? text;
5667
+ closeIconAppearance =
5668
+ notification.closeIconAppearance ?? closeIconAppearance;
5669
+ type = notification.type ?? type;
5670
+ closeIcon = notification.closeIcon ?? closeIcon;
5671
+ closeIconSrc = notification.closeIconSrc ?? closeIconSrc;
5672
+ buttonLabel = notification.buttonLabel ?? buttonLabel;
5673
+ onClickButton = notification.onClickButton ?? onClickButton;
5674
+ status = notification.status ?? status;
5675
+ closeByTime = notification.closeByTime ?? closeByTime;
5676
+ isLoading = notification.isLoading ?? isLoading;
5677
+ after = notification.after ?? after;
5678
+ appearance =
5679
+ notification.appearance ??
5680
+ statusToAppearanceList[notification.status] ??
5681
+ appearance;
5682
+ }
5683
+ return {
5684
+ id: id,
5685
+ appearance: appearance,
5686
+ type: type,
5687
+ title: title,
5688
+ status: status,
5689
+ text: text,
5690
+ buttonLabel: buttonLabel,
5691
+ after: after,
5692
+ closeByTime: closeByTime,
5693
+ closeIcon: closeIcon,
5694
+ closeIconAppearance: closeIconAppearance,
5695
+ closeIconSrc: closeIconSrc,
5696
+ isLoading: isLoading,
5697
+ onClickButton: onClickButton,
5698
+ onClose: onClose,
5699
+ };
5700
+ }
5701
+
5702
+ const UserDeviceContext = createContext({
5703
+ isMobile: false,
5704
+ isTablet: false,
5705
+ isDesktop: false,
5706
+ deviceCurrentMainType: '',
5707
+ deviceCurrentType: '',
5708
+ deviceTypesList: [],
5709
+ });
5710
+ const UIProvider = memo(function UIProvider(props) {
5711
+ const { userDeviceState = {}, children } = props;
5712
+ /** NOTE:
5713
+ * Remember that the "useMediaQueries" hook works by next scenario:
5714
+ * when changing the device type(browser width), the hook will first "enable"
5715
+ * the new type(set true), and then "disable" the previous one(set false),
5716
+ * what provoke to double rendering, and in moment we have two different types as "true".
5717
+ * We will need to look at how to change this behavior.
5718
+ */
5719
+ const allDevicesTypes = useMediaQueries(userDeviceState);
5720
+ const { isMobile, isTablet, isDesktop, ...fullNamedDeviceTypes } = allDevicesTypes;
5721
+ const deviceCurrentMainType = (isMobile && 'mobile') ||
5722
+ (isTablet && 'tablet') ||
5723
+ (isDesktop && 'desktop') ||
5724
+ '';
5725
+ const [deviceCurrentType, deviceTypesList] = useMemo(() => {
5726
+ const deviceTypesList = Object.keys(allDevicesTypes).map((key) => camelCase(key.replace('is', '')));
5727
+ // In same time "allDevicesTypes" can contain "isMobile" and "isMobileLarge" as true
5728
+ let deviceCurrentType = Object.keys(fullNamedDeviceTypes).find(
5729
+ // If "fullNamedDeviceTypes.isMobileLarge: true" - that our device
5730
+ (key) => fullNamedDeviceTypes[key]);
5731
+ // Or set main type (e.g. "isMobile")
5732
+ if (!deviceCurrentType) {
5733
+ deviceCurrentType = deviceCurrentMainType;
5734
+ }
5735
+ deviceCurrentType = camelCase(deviceCurrentType.replace('is', ''));
5736
+ // On server side render we doesn't known user device and we need to set special word
5737
+ return [deviceCurrentType || '_none_', deviceTypesList];
5738
+ }, [allDevicesTypes, deviceCurrentMainType, fullNamedDeviceTypes]);
5739
+ const deviceContextState = useMemo(() => {
5740
+ return {
5741
+ ...allDevicesTypes,
5742
+ deviceCurrentMainType: deviceCurrentMainType,
5743
+ deviceCurrentType: deviceCurrentType,
5744
+ deviceTypesList: deviceTypesList,
5745
+ };
5746
+ }, [
5747
+ allDevicesTypes,
5748
+ deviceCurrentMainType,
5749
+ deviceCurrentType,
5750
+ deviceTypesList,
5751
+ ]);
5752
+ useEffect(() => {
5753
+ setViewportProperty();
5754
+ window.addEventListener('resize', setViewportProperty);
5755
+ }, []);
5756
+ return (jsx(UserDeviceContext.Provider, { value: deviceContextState, children: children }));
5757
+ });
5758
+
5688
5759
  export { NotificationsProvider as N, UIProvider as U, NotificationWrapper as a };