@itcase/storybook-config 1.2.38 → 1.2.40

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