react-inlinesvg 4.1.0-0 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -73,4 +73,4 @@ declare class CacheStore {
73
73
  declare let cacheStore: CacheStore;
74
74
  declare function InlineSVG(props: Props): string | number | boolean | Iterable<React.ReactNode> | react_jsx_runtime.JSX.Element | null | undefined;
75
75
 
76
- export { ErrorCallback, FetchError, LoadCallback, PlainObject, PreProcessorCallback, Props, Simplify, State, Status, StorageItem, cacheStore, InlineSVG as default };
76
+ export { type ErrorCallback, type FetchError, type LoadCallback, type PlainObject, type PreProcessorCallback, type Props, type Simplify, type State, type Status, type StorageItem, cacheStore, InlineSVG as default };
package/dist/index.d.ts CHANGED
@@ -73,5 +73,5 @@ declare class CacheStore {
73
73
  declare let cacheStore: CacheStore;
74
74
  declare function InlineSVG(props: Props): string | number | boolean | Iterable<React.ReactNode> | react_jsx_runtime.JSX.Element | null | undefined;
75
75
 
76
- export { ErrorCallback, FetchError, LoadCallback, PlainObject, PreProcessorCallback, Props, Simplify, State, Status, StorageItem, cacheStore, InlineSVG as default };
76
+ export { type ErrorCallback, type FetchError, type LoadCallback, type PlainObject, type PreProcessorCallback, type Props, type Simplify, type State, type Status, type StorageItem, cacheStore, InlineSVG as default };
77
77
  export = InlineSVG
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ "use client";
1
2
  "use strict";
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
@@ -40,7 +41,7 @@ __export(src_exports, {
40
41
  });
41
42
  module.exports = __toCommonJS(src_exports);
42
43
  var import_react2 = require("react");
43
- var import_react_from_dom = __toESM(require("react-from-dom"));
44
+ var import_react_from_dom2 = __toESM(require("react-from-dom"));
44
45
 
45
46
  // src/config.ts
46
47
  var CACHE_NAME = "react-inlinesvg";
@@ -54,7 +55,7 @@ var STATUS = {
54
55
  UNSUPPORTED: "unsupported"
55
56
  };
56
57
 
57
- // src/helpers.ts
58
+ // src/modules/helpers.ts
58
59
  function canUseDOM() {
59
60
  return !!(typeof window !== "undefined" && window.document && window.document.createElement);
60
61
  }
@@ -112,7 +113,7 @@ function omit(input, ...filter) {
112
113
  return output;
113
114
  }
114
115
 
115
- // src/cache.ts
116
+ // src/modules/cache.ts
116
117
  var CacheStore = class {
117
118
  constructor() {
118
119
  __publicField(this, "cacheApi");
@@ -238,7 +239,7 @@ var CacheStore = class {
238
239
  }
239
240
  };
240
241
 
241
- // src/hooks.tsx
242
+ // src/modules/hooks.tsx
242
243
  var import_react = require("react");
243
244
  function usePrevious(state) {
244
245
  const ref = (0, import_react.useRef)();
@@ -248,41 +249,8 @@ function usePrevious(state) {
248
249
  return ref.current;
249
250
  }
250
251
 
251
- // src/index.tsx
252
- var import_jsx_runtime = require("react/jsx-runtime");
253
- var cacheStore;
254
- function updateSVGAttributes(node, options) {
255
- const { baseURL = "", hash, uniquifyIDs } = options;
256
- const replaceableAttributes = ["id", "href", "xlink:href", "xlink:role", "xlink:arcrole"];
257
- const linkAttributes = ["href", "xlink:href"];
258
- const isDataValue = (name, value) => linkAttributes.includes(name) && (value ? !value.includes("#") : false);
259
- if (!uniquifyIDs) {
260
- return node;
261
- }
262
- [...node.children].forEach((d) => {
263
- if (d.attributes?.length) {
264
- const attributes = Object.values(d.attributes).map((a) => {
265
- const attribute = a;
266
- const match = /url\((.*?)\)/.exec(a.value);
267
- if (match?.[1]) {
268
- attribute.value = a.value.replace(match[0], `url(${baseURL}${match[1]}__${hash})`);
269
- }
270
- return attribute;
271
- });
272
- replaceableAttributes.forEach((r) => {
273
- const attribute = attributes.find((a) => a.name === r);
274
- if (attribute && !isDataValue(r, attribute.value)) {
275
- attribute.value = `${attribute.value}__${hash}`;
276
- }
277
- });
278
- }
279
- if (d.children.length) {
280
- return updateSVGAttributes(d, options);
281
- }
282
- return d;
283
- });
284
- return node;
285
- }
252
+ // src/modules/utils.ts
253
+ var import_react_from_dom = __toESM(require("react-from-dom"));
286
254
  function getNode(options) {
287
255
  const {
288
256
  baseURL,
@@ -332,6 +300,42 @@ function processSVG(content, preProcessor) {
332
300
  }
333
301
  return content;
334
302
  }
303
+ function updateSVGAttributes(node, options) {
304
+ const { baseURL = "", hash, uniquifyIDs } = options;
305
+ const replaceableAttributes = ["id", "href", "xlink:href", "xlink:role", "xlink:arcrole"];
306
+ const linkAttributes = ["href", "xlink:href"];
307
+ const isDataValue = (name, value) => linkAttributes.includes(name) && (value ? !value.includes("#") : false);
308
+ if (!uniquifyIDs) {
309
+ return node;
310
+ }
311
+ [...node.children].forEach((d) => {
312
+ if (d.attributes?.length) {
313
+ const attributes = Object.values(d.attributes).map((a) => {
314
+ const attribute = a;
315
+ const match = /url\((.*?)\)/.exec(a.value);
316
+ if (match?.[1]) {
317
+ attribute.value = a.value.replace(match[0], `url(${baseURL}${match[1]}__${hash})`);
318
+ }
319
+ return attribute;
320
+ });
321
+ replaceableAttributes.forEach((r) => {
322
+ const attribute = attributes.find((a) => a.name === r);
323
+ if (attribute && !isDataValue(r, attribute.value)) {
324
+ attribute.value = `${attribute.value}__${hash}`;
325
+ }
326
+ });
327
+ }
328
+ if (d.children.length) {
329
+ return updateSVGAttributes(d, options);
330
+ }
331
+ return d;
332
+ });
333
+ return node;
334
+ }
335
+
336
+ // src/index.tsx
337
+ var import_jsx_runtime = require("react/jsx-runtime");
338
+ var cacheStore;
335
339
  function ReactInlineSVG(props) {
336
340
  const {
337
341
  cacheRequests = true,
@@ -384,10 +388,14 @@ function ReactInlineSVG(props) {
384
388
  });
385
389
  }
386
390
  }, []);
391
+ const fetchContent = (0, import_react2.useCallback)(async () => {
392
+ const responseContent = await request(src, fetchOptions);
393
+ handleLoad(responseContent);
394
+ }, [fetchOptions, handleLoad, src]);
387
395
  const getElement = (0, import_react2.useCallback)(() => {
388
396
  try {
389
397
  const node = getNode({ ...props, handleError, hash: hash.current, content });
390
- const convertedElement = (0, import_react_from_dom.default)(node);
398
+ const convertedElement = (0, import_react_from_dom2.default)(node);
391
399
  if (!convertedElement || !(0, import_react2.isValidElement)(convertedElement)) {
392
400
  throw new Error("Could not convert the src to a React element");
393
401
  }
@@ -399,10 +407,6 @@ function ReactInlineSVG(props) {
399
407
  handleError(new Error(error.message));
400
408
  }
401
409
  }, [content, handleError, props]);
402
- const fetchContent = (0, import_react2.useCallback)(async () => {
403
- const responseContent = await request(src, fetchOptions);
404
- handleLoad(responseContent);
405
- }, [fetchOptions, handleLoad, src]);
406
410
  const getContent = (0, import_react2.useCallback)(async () => {
407
411
  const dataURI = /^data:image\/svg[^,]*?(;base64)?,(.*)/u.exec(src);
408
412
  let inlineSrc;
@@ -479,19 +483,7 @@ function ReactInlineSVG(props) {
479
483
  } else if (previousProps.title !== title || previousProps.description !== description) {
480
484
  getElement();
481
485
  }
482
- }, [
483
- description,
484
- getElement,
485
- handleError,
486
- isCached,
487
- load,
488
- onLoad,
489
- previousProps,
490
- previousState,
491
- src,
492
- status,
493
- title
494
- ]);
486
+ }, [description, getElement, handleError, load, previousProps, src, title]);
495
487
  (0, import_react2.useEffect)(() => {
496
488
  if (!previousState) {
497
489
  return;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.tsx","../src/config.ts","../src/helpers.ts","../src/cache.ts","../src/hooks.tsx"],"sourcesContent":["import {\n cloneElement,\n isValidElement,\n ReactElement,\n useCallback,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react';\nimport convert from 'react-from-dom';\n\nimport CacheStore from './cache';\nimport { STATUS } from './config';\nimport { canUseDOM, isSupportedEnvironment, omit, randomString, request } from './helpers';\nimport { usePrevious } from './hooks';\nimport { FetchError, Props, State, Status } from './types';\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let cacheStore: CacheStore;\n\ninterface GetNodeOptions extends Props, Pick<State, 'content'> {\n handleError: (error: Error) => void;\n hash: string;\n}\n\ninterface UpdateSVGAttributesOptions extends Pick<Props, 'baseURL' | 'uniquifyIDs'> {\n hash: string;\n}\n\nfunction updateSVGAttributes(\n node: SVGSVGElement,\n options: UpdateSVGAttributesOptions,\n): SVGSVGElement {\n const { baseURL = '', hash, uniquifyIDs } = options;\n const replaceableAttributes = ['id', 'href', 'xlink:href', 'xlink:role', 'xlink:arcrole'];\n const linkAttributes = ['href', 'xlink:href'];\n const isDataValue = (name: string, value: string) =>\n linkAttributes.includes(name) && (value ? !value.includes('#') : false);\n\n if (!uniquifyIDs) {\n return node;\n }\n\n [...node.children].forEach(d => {\n if (d.attributes?.length) {\n const attributes = Object.values(d.attributes).map(a => {\n const attribute = a;\n const match = /url\\((.*?)\\)/.exec(a.value);\n\n if (match?.[1]) {\n attribute.value = a.value.replace(match[0], `url(${baseURL}${match[1]}__${hash})`);\n }\n\n return attribute;\n });\n\n replaceableAttributes.forEach(r => {\n const attribute = attributes.find(a => a.name === r);\n\n if (attribute && !isDataValue(r, attribute.value)) {\n attribute.value = `${attribute.value}__${hash}`;\n }\n });\n }\n\n if (d.children.length) {\n return updateSVGAttributes(d as SVGSVGElement, options);\n }\n\n return d;\n });\n\n return node;\n}\n\nfunction getNode(options: GetNodeOptions) {\n const {\n baseURL,\n content,\n description,\n handleError,\n hash,\n preProcessor,\n title,\n uniquifyIDs = false,\n } = options;\n\n try {\n const svgText = processSVG(content, preProcessor);\n const node = convert(svgText, { nodeOnly: true });\n\n if (!node || !(node instanceof SVGSVGElement)) {\n throw new Error('Could not convert the src to a DOM Node');\n }\n\n const svg = updateSVGAttributes(node, { baseURL, hash, uniquifyIDs });\n\n if (description) {\n const originalDesc = svg.querySelector('desc');\n\n if (originalDesc?.parentNode) {\n originalDesc.parentNode.removeChild(originalDesc);\n }\n\n const descElement = document.createElementNS('http://www.w3.org/2000/svg', 'desc');\n\n descElement.innerHTML = description;\n svg.prepend(descElement);\n }\n\n if (typeof title !== 'undefined') {\n const originalTitle = svg.querySelector('title');\n\n if (originalTitle?.parentNode) {\n originalTitle.parentNode.removeChild(originalTitle);\n }\n\n if (title) {\n const titleElement = document.createElementNS('http://www.w3.org/2000/svg', 'title');\n\n titleElement.innerHTML = title;\n svg.prepend(titleElement);\n }\n }\n\n return svg;\n } catch (error: any) {\n return handleError(error);\n }\n}\n\nfunction processSVG(content: string, preProcessor?: Props['preProcessor']) {\n if (preProcessor) {\n return preProcessor(content);\n }\n\n return content;\n}\n\nfunction ReactInlineSVG(props: Props) {\n const {\n cacheRequests = true,\n children = null,\n description,\n fetchOptions,\n innerRef,\n loader = null,\n onError,\n onLoad,\n src,\n title,\n uniqueHash,\n } = props;\n const [state, setState] = useReducer(\n (previousState: State, nextState: Partial<State>) => ({\n ...previousState,\n ...nextState,\n }),\n {\n content: '',\n element: null,\n\n isCached: cacheRequests && cacheStore.isCached(props.src),\n status: STATUS.IDLE,\n },\n );\n const { content, element, isCached, status } = state;\n const previousProps = usePrevious(props);\n const previousState = usePrevious(state);\n\n const hash = useRef(uniqueHash ?? randomString(8));\n const isActive = useRef(false);\n const isInitialized = useRef(false);\n\n const handleError = useCallback(\n (error: Error | FetchError) => {\n if (isActive.current) {\n setState({\n status:\n error.message === 'Browser does not support SVG' ? STATUS.UNSUPPORTED : STATUS.FAILED,\n });\n\n onError?.(error);\n }\n },\n [onError],\n );\n\n const handleLoad = useCallback((loadedContent: string, hasCache = false) => {\n if (isActive.current) {\n setState({\n content: loadedContent,\n isCached: hasCache,\n status: STATUS.LOADED,\n });\n }\n }, []);\n\n const getElement = useCallback(() => {\n try {\n const node = getNode({ ...props, handleError, hash: hash.current, content }) as Node;\n const convertedElement = convert(node);\n\n if (!convertedElement || !isValidElement(convertedElement)) {\n throw new Error('Could not convert the src to a React element');\n }\n\n setState({\n element: convertedElement,\n status: STATUS.READY,\n });\n } catch (error: any) {\n handleError(new Error(error.message));\n }\n }, [content, handleError, props]);\n\n const fetchContent = useCallback(async () => {\n const responseContent: string = await request(src, fetchOptions);\n\n handleLoad(responseContent);\n }, [fetchOptions, handleLoad, src]);\n\n const getContent = useCallback(async () => {\n const dataURI = /^data:image\\/svg[^,]*?(;base64)?,(.*)/u.exec(src);\n let inlineSrc;\n\n if (dataURI) {\n inlineSrc = dataURI[1] ? window.atob(dataURI[2]) : decodeURIComponent(dataURI[2]);\n } else if (src.includes('<svg')) {\n inlineSrc = src;\n }\n\n if (inlineSrc) {\n handleLoad(inlineSrc);\n\n return;\n }\n\n try {\n if (cacheRequests) {\n const cachedContent = await cacheStore.get(src, fetchOptions);\n\n handleLoad(cachedContent, true);\n } else {\n await fetchContent();\n }\n } catch (error: any) {\n handleError(error);\n }\n }, [cacheRequests, fetchContent, fetchOptions, handleError, handleLoad, src]);\n\n const load = useCallback(async () => {\n if (isActive.current) {\n setState({\n content: '',\n element: null,\n isCached: false,\n status: STATUS.LOADING,\n });\n }\n }, []);\n\n // Run on mount\n useEffect(\n () => {\n isActive.current = true;\n\n if (!canUseDOM() || isInitialized.current) {\n return () => undefined;\n }\n\n try {\n if (status === STATUS.IDLE) {\n if (!isSupportedEnvironment()) {\n throw new Error('Browser does not support SVG');\n }\n\n if (!src) {\n throw new Error('Missing src');\n }\n\n load();\n }\n } catch (error: any) {\n handleError(error);\n }\n\n isInitialized.current = true;\n\n return () => {\n isActive.current = false;\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [],\n );\n\n // Handle prop changes\n useEffect(() => {\n if (!canUseDOM()) {\n return;\n }\n\n if (!previousProps) {\n return;\n }\n\n if (previousProps.src !== src) {\n if (!src) {\n handleError(new Error('Missing src'));\n\n return;\n }\n\n load();\n } else if (previousProps.title !== title || previousProps.description !== description) {\n getElement();\n }\n }, [\n description,\n getElement,\n handleError,\n isCached,\n load,\n onLoad,\n previousProps,\n previousState,\n src,\n status,\n title,\n ]);\n\n // handle state\n useEffect(() => {\n if (!previousState) {\n return;\n }\n\n if (previousState.status !== STATUS.LOADING && status === STATUS.LOADING) {\n getContent();\n }\n\n if (previousState.status !== STATUS.LOADED && status === STATUS.LOADED) {\n getElement();\n }\n\n if (previousState.status !== STATUS.READY && status === STATUS.READY) {\n onLoad?.(src, isCached);\n }\n }, [getContent, getElement, isCached, onLoad, previousState, src, status]);\n\n const elementProps = omit(\n props,\n 'baseURL',\n 'cacheRequests',\n 'children',\n 'description',\n 'fetchOptions',\n 'innerRef',\n 'loader',\n 'onError',\n 'onLoad',\n 'preProcessor',\n 'src',\n 'title',\n 'uniqueHash',\n 'uniquifyIDs',\n );\n\n if (!canUseDOM()) {\n return loader;\n }\n\n if (element) {\n return cloneElement(element as ReactElement, { ref: innerRef, ...elementProps });\n }\n\n if (([STATUS.UNSUPPORTED, STATUS.FAILED] as Status[]).includes(status)) {\n return children;\n }\n\n return loader;\n}\n\nexport default function InlineSVG(props: Props) {\n if (!cacheStore) {\n cacheStore = new CacheStore();\n }\n\n const { loader } = props;\n const hasCallback = useRef(false);\n const [isReady, setReady] = useState(cacheStore.isReady);\n\n useEffect(() => {\n if (!hasCallback.current) {\n cacheStore.onReady(() => {\n setReady(true);\n });\n\n hasCallback.current = true;\n }\n }, []);\n\n if (!isReady) {\n return loader;\n }\n\n return <ReactInlineSVG {...props} />;\n}\n\nexport * from './types';\n","export const CACHE_NAME = 'react-inlinesvg';\nexport const CACHE_MAX_RETRIES = 10;\n\nexport const STATUS = {\n IDLE: 'idle',\n LOADING: 'loading',\n LOADED: 'loaded',\n FAILED: 'failed',\n READY: 'ready',\n UNSUPPORTED: 'unsupported',\n} as const;\n","import type { PlainObject } from './types';\n\nexport function canUseDOM(): boolean {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\n\nexport async function request(url: string, options?: RequestInit) {\n const response = await fetch(url, options);\n const contentType = response.headers.get('content-type');\n const [fileType] = (contentType ?? '').split(/ ?; ?/);\n\n if (response.status > 299) {\n throw new Error('Not found');\n }\n\n if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {\n throw new Error(`Content type isn't valid: ${fileType}`);\n }\n\n return response.text();\n}\n\nexport function sleep(seconds = 1) {\n return new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n}\n\nexport function supportsInlineSVG(): boolean {\n /* c8 ignore next 3 */\n if (!document) {\n return false;\n }\n\n const div = document.createElement('div');\n\n div.innerHTML = '<svg />';\n const svg = div.firstChild as SVGSVGElement;\n\n return !!svg && svg.namespaceURI === 'http://www.w3.org/2000/svg';\n}\n\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function randomString(length: number): string {\n const letters = 'abcdefghijklmnopqrstuvwxyz';\n const numbers = '1234567890';\n const charset = `${letters}${letters.toUpperCase()}${numbers}`;\n\n let R = '';\n\n for (let index = 0; index < length; index++) {\n R += randomCharacter(charset);\n }\n\n return R;\n}\n\n/**\n * Remove properties from an object\n */\nexport function omit<T extends PlainObject, K extends keyof T>(\n input: T,\n ...filter: K[]\n): Omit<T, K> {\n const output: any = {};\n\n for (const key in input) {\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n }\n\n return output as Omit<T, K>;\n}\n","import { CACHE_MAX_RETRIES, CACHE_NAME, STATUS } from './config';\nimport { canUseDOM, request, sleep } from './helpers';\nimport { StorageItem } from './types';\n\nexport default class CacheStore {\n private cacheApi: Cache | undefined;\n private readonly cacheStore: Map<string, StorageItem>;\n private readonly subscribers: Array<() => void> = [];\n public isReady = false;\n\n constructor() {\n this.cacheStore = new Map<string, StorageItem>();\n\n let cacheName = CACHE_NAME;\n let usePersistentCache = false;\n\n if (canUseDOM()) {\n cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;\n usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE && 'caches' in window;\n }\n\n if (usePersistentCache) {\n caches\n .open(cacheName)\n .then(cache => {\n this.cacheApi = cache;\n this.isReady = true;\n\n this.subscribers.forEach(callback => callback());\n })\n .catch(error => {\n this.isReady = true;\n\n // eslint-disable-next-line no-console\n console.error(`Failed to open cache: ${error.message}`);\n });\n } else {\n this.isReady = true;\n }\n }\n\n public onReady(callback: () => void) {\n if (this.isReady) {\n callback();\n } else {\n this.subscribers.push(callback);\n }\n }\n\n public async get(url: string, fetchOptions?: RequestInit) {\n await (this.cacheApi\n ? this.fetchAndAddToPersistentCache(url, fetchOptions)\n : this.fetchAndAddToInternalCache(url, fetchOptions));\n\n return this.cacheStore.get(url)?.content ?? '';\n }\n\n public set(url: string, data: StorageItem) {\n this.cacheStore.set(url, data);\n }\n\n public isCached(url: string) {\n return this.cacheStore.get(url)?.status === STATUS.LOADED;\n }\n\n private async fetchAndAddToInternalCache(url: string, fetchOptions?: RequestInit) {\n const cache = this.cacheStore.get(url);\n\n if (cache?.status === STATUS.LOADING) {\n await this.handleLoading(url, async () => {\n this.cacheStore.set(url, { content: '', status: STATUS.IDLE });\n await this.fetchAndAddToInternalCache(url, fetchOptions);\n });\n\n return;\n }\n\n if (!cache?.content) {\n this.cacheStore.set(url, { content: '', status: STATUS.LOADING });\n\n try {\n const content = await request(url, fetchOptions);\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n } catch (error: any) {\n this.cacheStore.set(url, { content: '', status: STATUS.FAILED });\n throw error;\n }\n }\n }\n\n private async fetchAndAddToPersistentCache(url: string, fetchOptions?: RequestInit) {\n const cache = this.cacheStore.get(url);\n\n if (cache?.status === STATUS.LOADED) {\n return;\n }\n\n if (cache?.status === STATUS.LOADING) {\n await this.handleLoading(url, async () => {\n this.cacheStore.set(url, { content: '', status: STATUS.IDLE });\n await this.fetchAndAddToPersistentCache(url, fetchOptions);\n });\n\n return;\n }\n\n this.cacheStore.set(url, { content: '', status: STATUS.LOADING });\n\n const data = await this.cacheApi?.match(url);\n\n if (data) {\n const content = await data.text();\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n\n return;\n }\n\n try {\n await this.cacheApi?.add(new Request(url, fetchOptions));\n\n const response = await this.cacheApi?.match(url);\n const content = (await response?.text()) ?? '';\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n } catch (error: any) {\n this.cacheStore.set(url, { content: '', status: STATUS.FAILED });\n throw error;\n }\n }\n\n private async handleLoading(url: string, callback: () => Promise<void>) {\n let retryCount = 0;\n\n // eslint-disable-next-line no-await-in-loop\n while (this.cacheStore.get(url)?.status === STATUS.LOADING && retryCount < CACHE_MAX_RETRIES) {\n // eslint-disable-next-line no-await-in-loop\n await sleep(0.1);\n retryCount += 1;\n }\n\n if (retryCount >= CACHE_MAX_RETRIES) {\n await callback();\n }\n }\n\n public keys(): Array<string> {\n return [...this.cacheStore.keys()];\n }\n\n public data(): Array<Record<string, StorageItem>> {\n return [...this.cacheStore.entries()].map(([key, value]) => ({ [key]: value }));\n }\n\n public async delete(url: string) {\n if (this.cacheApi) {\n await this.cacheApi.delete(url);\n }\n\n this.cacheStore.delete(url);\n }\n\n public async clear() {\n if (this.cacheApi) {\n const keys = await this.cacheApi.keys();\n\n for (const key of keys) {\n // eslint-disable-next-line no-await-in-loop\n await this.cacheApi.delete(key);\n }\n }\n\n this.cacheStore.clear();\n }\n}\n","import { useEffect, useRef } from 'react';\n\nexport function usePrevious<T>(state: T): T | undefined {\n const ref = useRef<T>();\n\n useEffect(() => {\n ref.current = state;\n });\n\n return ref.current;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,gBASO;AACP,4BAAoB;;;ACVb,IAAM,aAAa;AACnB,IAAM,oBAAoB;AAE1B,IAAM,SAAS;AAAA,EACpB,MAAM;AAAA,EACN,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,aAAa;AACf;;;ACRO,SAAS,YAAqB;AACnC,SAAO,CAAC,EAAE,OAAO,WAAW,eAAe,OAAO,YAAY,OAAO,SAAS;AAChF;AAEO,SAAS,yBAAkC;AAChD,SAAO,kBAAkB,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eAAS,KAAK,QAAQ;AAAA,IACxB;AAAA,EACF,GAAG,CAAC,YAAY,YAAY,UAAU,QAAQ,eAAe,KAAK,MAAM,CAAC;AAEzE,QAAM,eAAe;AAAA,IACnB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,MAAI,CAAC,UAAU,GAAG;AAChB,WAAO;AAAA,EACT;AAEA,MAAI,SAAS;AACX,eAAO,4BAAa,SAAyB,EAAE,KAAK,UAAU,GAAG,aAAa,CAAC;AAAA,EACjF;AAEA,MAAK,CAAC,OAAO,aAAa,OAAO,MAAM,EAAe,SAAS,MAAM,GAAG;AACtE,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAEe,SAAR,UAA2B,OAAc;AAC9C,MAAI,CAAC,YAAY;AACf,iBAAa,IAAI,WAAW;AAAA,EAC9B;AAEA,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,kBAAc,sBAAO,KAAK;AAChC,QAAM,CAAC,SAAS,QAAQ,QAAI,wBAAS,WAAW,OAAO;AAEvD,+BAAU,MAAM;AACd,QAAI,CAAC,YAAY,SAAS;AACxB,iBAAW,QAAQ,MAAM;AACvB,iBAAS,IAAI;AAAA,MACf,CAAC;AAED,kBAAY,UAAU;AAAA,IACxB;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,SAAO,4CAAC,kBAAgB,GAAG,OAAO;AACpC;","names":["import_react","convert","previousState"]}
1
+ {"version":3,"sources":["../src/index.tsx","../src/config.ts","../src/modules/helpers.ts","../src/modules/cache.ts","../src/modules/hooks.tsx","../src/modules/utils.ts"],"sourcesContent":["import {\n cloneElement,\n isValidElement,\n ReactElement,\n useCallback,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react';\nimport convert from 'react-from-dom';\n\nimport { STATUS } from './config';\nimport CacheStore from './modules/cache';\nimport { canUseDOM, isSupportedEnvironment, omit, randomString, request } from './modules/helpers';\nimport { usePrevious } from './modules/hooks';\nimport { getNode } from './modules/utils';\nimport { FetchError, Props, State, Status } from './types';\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let cacheStore: CacheStore;\n\nfunction ReactInlineSVG(props: Props) {\n const {\n cacheRequests = true,\n children = null,\n description,\n fetchOptions,\n innerRef,\n loader = null,\n onError,\n onLoad,\n src,\n title,\n uniqueHash,\n } = props;\n const [state, setState] = useReducer(\n (previousState: State, nextState: Partial<State>) => ({\n ...previousState,\n ...nextState,\n }),\n {\n content: '',\n element: null,\n\n isCached: cacheRequests && cacheStore.isCached(props.src),\n status: STATUS.IDLE,\n },\n );\n const { content, element, isCached, status } = state;\n const previousProps = usePrevious(props);\n const previousState = usePrevious(state);\n\n const hash = useRef(uniqueHash ?? randomString(8));\n const isActive = useRef(false);\n const isInitialized = useRef(false);\n\n const handleError = useCallback(\n (error: Error | FetchError) => {\n if (isActive.current) {\n setState({\n status:\n error.message === 'Browser does not support SVG' ? STATUS.UNSUPPORTED : STATUS.FAILED,\n });\n\n onError?.(error);\n }\n },\n [onError],\n );\n\n const handleLoad = useCallback((loadedContent: string, hasCache = false) => {\n if (isActive.current) {\n setState({\n content: loadedContent,\n isCached: hasCache,\n status: STATUS.LOADED,\n });\n }\n }, []);\n\n const fetchContent = useCallback(async () => {\n const responseContent: string = await request(src, fetchOptions);\n\n handleLoad(responseContent);\n }, [fetchOptions, handleLoad, src]);\n\n const getElement = useCallback(() => {\n try {\n const node = getNode({ ...props, handleError, hash: hash.current, content }) as Node;\n const convertedElement = convert(node);\n\n if (!convertedElement || !isValidElement(convertedElement)) {\n throw new Error('Could not convert the src to a React element');\n }\n\n setState({\n element: convertedElement,\n status: STATUS.READY,\n });\n } catch (error: any) {\n handleError(new Error(error.message));\n }\n }, [content, handleError, props]);\n\n const getContent = useCallback(async () => {\n const dataURI = /^data:image\\/svg[^,]*?(;base64)?,(.*)/u.exec(src);\n let inlineSrc;\n\n if (dataURI) {\n inlineSrc = dataURI[1] ? window.atob(dataURI[2]) : decodeURIComponent(dataURI[2]);\n } else if (src.includes('<svg')) {\n inlineSrc = src;\n }\n\n if (inlineSrc) {\n handleLoad(inlineSrc);\n\n return;\n }\n\n try {\n if (cacheRequests) {\n const cachedContent = await cacheStore.get(src, fetchOptions);\n\n handleLoad(cachedContent, true);\n } else {\n await fetchContent();\n }\n } catch (error: any) {\n handleError(error);\n }\n }, [cacheRequests, fetchContent, fetchOptions, handleError, handleLoad, src]);\n\n const load = useCallback(async () => {\n if (isActive.current) {\n setState({\n content: '',\n element: null,\n isCached: false,\n status: STATUS.LOADING,\n });\n }\n }, []);\n\n // Run on mount\n useEffect(\n () => {\n isActive.current = true;\n\n if (!canUseDOM() || isInitialized.current) {\n return () => undefined;\n }\n\n try {\n if (status === STATUS.IDLE) {\n if (!isSupportedEnvironment()) {\n throw new Error('Browser does not support SVG');\n }\n\n if (!src) {\n throw new Error('Missing src');\n }\n\n load();\n }\n } catch (error: any) {\n handleError(error);\n }\n\n isInitialized.current = true;\n\n return () => {\n isActive.current = false;\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [],\n );\n\n // Handle prop changes\n useEffect(() => {\n if (!canUseDOM()) {\n return;\n }\n\n if (!previousProps) {\n return;\n }\n\n if (previousProps.src !== src) {\n if (!src) {\n handleError(new Error('Missing src'));\n\n return;\n }\n\n load();\n } else if (previousProps.title !== title || previousProps.description !== description) {\n getElement();\n }\n }, [description, getElement, handleError, load, previousProps, src, title]);\n\n // handle state\n useEffect(() => {\n if (!previousState) {\n return;\n }\n\n if (previousState.status !== STATUS.LOADING && status === STATUS.LOADING) {\n getContent();\n }\n\n if (previousState.status !== STATUS.LOADED && status === STATUS.LOADED) {\n getElement();\n }\n\n if (previousState.status !== STATUS.READY && status === STATUS.READY) {\n onLoad?.(src, isCached);\n }\n }, [getContent, getElement, isCached, onLoad, previousState, src, status]);\n\n const elementProps = omit(\n props,\n 'baseURL',\n 'cacheRequests',\n 'children',\n 'description',\n 'fetchOptions',\n 'innerRef',\n 'loader',\n 'onError',\n 'onLoad',\n 'preProcessor',\n 'src',\n 'title',\n 'uniqueHash',\n 'uniquifyIDs',\n );\n\n if (!canUseDOM()) {\n return loader;\n }\n\n if (element) {\n return cloneElement(element as ReactElement, { ref: innerRef, ...elementProps });\n }\n\n if (([STATUS.UNSUPPORTED, STATUS.FAILED] as Status[]).includes(status)) {\n return children;\n }\n\n return loader;\n}\n\nexport default function InlineSVG(props: Props) {\n if (!cacheStore) {\n cacheStore = new CacheStore();\n }\n\n const { loader } = props;\n const hasCallback = useRef(false);\n const [isReady, setReady] = useState(cacheStore.isReady);\n\n useEffect(() => {\n if (!hasCallback.current) {\n cacheStore.onReady(() => {\n setReady(true);\n });\n\n hasCallback.current = true;\n }\n }, []);\n\n if (!isReady) {\n return loader;\n }\n\n return <ReactInlineSVG {...props} />;\n}\n\nexport * from './types';\n","export const CACHE_NAME = 'react-inlinesvg';\nexport const CACHE_MAX_RETRIES = 10;\n\nexport const STATUS = {\n IDLE: 'idle',\n LOADING: 'loading',\n LOADED: 'loaded',\n FAILED: 'failed',\n READY: 'ready',\n UNSUPPORTED: 'unsupported',\n} as const;\n","import type { PlainObject } from '../types';\n\nexport function canUseDOM(): boolean {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\n\nexport async function request(url: string, options?: RequestInit) {\n const response = await fetch(url, options);\n const contentType = response.headers.get('content-type');\n const [fileType] = (contentType ?? '').split(/ ?; ?/);\n\n if (response.status > 299) {\n throw new Error('Not found');\n }\n\n if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {\n throw new Error(`Content type isn't valid: ${fileType}`);\n }\n\n return response.text();\n}\n\nexport function sleep(seconds = 1) {\n return new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n}\n\nexport function supportsInlineSVG(): boolean {\n /* c8 ignore next 3 */\n if (!document) {\n return false;\n }\n\n const div = document.createElement('div');\n\n div.innerHTML = '<svg />';\n const svg = div.firstChild as SVGSVGElement;\n\n return !!svg && svg.namespaceURI === 'http://www.w3.org/2000/svg';\n}\n\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function randomString(length: number): string {\n const letters = 'abcdefghijklmnopqrstuvwxyz';\n const numbers = '1234567890';\n const charset = `${letters}${letters.toUpperCase()}${numbers}`;\n\n let R = '';\n\n for (let index = 0; index < length; index++) {\n R += randomCharacter(charset);\n }\n\n return R;\n}\n\n/**\n * Remove properties from an object\n */\nexport function omit<T extends PlainObject, K extends keyof T>(\n input: T,\n ...filter: K[]\n): Omit<T, K> {\n const output: any = {};\n\n for (const key in input) {\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n }\n\n return output as Omit<T, K>;\n}\n","import { canUseDOM, request, sleep } from './helpers';\n\nimport { CACHE_MAX_RETRIES, CACHE_NAME, STATUS } from '../config';\nimport { StorageItem } from '../types';\n\nexport default class CacheStore {\n private cacheApi: Cache | undefined;\n private readonly cacheStore: Map<string, StorageItem>;\n private readonly subscribers: Array<() => void> = [];\n public isReady = false;\n\n constructor() {\n this.cacheStore = new Map<string, StorageItem>();\n\n let cacheName = CACHE_NAME;\n let usePersistentCache = false;\n\n if (canUseDOM()) {\n cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;\n usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE && 'caches' in window;\n }\n\n if (usePersistentCache) {\n caches\n .open(cacheName)\n .then(cache => {\n this.cacheApi = cache;\n this.isReady = true;\n\n this.subscribers.forEach(callback => callback());\n })\n .catch(error => {\n this.isReady = true;\n\n // eslint-disable-next-line no-console\n console.error(`Failed to open cache: ${error.message}`);\n });\n } else {\n this.isReady = true;\n }\n }\n\n public onReady(callback: () => void) {\n if (this.isReady) {\n callback();\n } else {\n this.subscribers.push(callback);\n }\n }\n\n public async get(url: string, fetchOptions?: RequestInit) {\n await (this.cacheApi\n ? this.fetchAndAddToPersistentCache(url, fetchOptions)\n : this.fetchAndAddToInternalCache(url, fetchOptions));\n\n return this.cacheStore.get(url)?.content ?? '';\n }\n\n public set(url: string, data: StorageItem) {\n this.cacheStore.set(url, data);\n }\n\n public isCached(url: string) {\n return this.cacheStore.get(url)?.status === STATUS.LOADED;\n }\n\n private async fetchAndAddToInternalCache(url: string, fetchOptions?: RequestInit) {\n const cache = this.cacheStore.get(url);\n\n if (cache?.status === STATUS.LOADING) {\n await this.handleLoading(url, async () => {\n this.cacheStore.set(url, { content: '', status: STATUS.IDLE });\n await this.fetchAndAddToInternalCache(url, fetchOptions);\n });\n\n return;\n }\n\n if (!cache?.content) {\n this.cacheStore.set(url, { content: '', status: STATUS.LOADING });\n\n try {\n const content = await request(url, fetchOptions);\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n } catch (error: any) {\n this.cacheStore.set(url, { content: '', status: STATUS.FAILED });\n throw error;\n }\n }\n }\n\n private async fetchAndAddToPersistentCache(url: string, fetchOptions?: RequestInit) {\n const cache = this.cacheStore.get(url);\n\n if (cache?.status === STATUS.LOADED) {\n return;\n }\n\n if (cache?.status === STATUS.LOADING) {\n await this.handleLoading(url, async () => {\n this.cacheStore.set(url, { content: '', status: STATUS.IDLE });\n await this.fetchAndAddToPersistentCache(url, fetchOptions);\n });\n\n return;\n }\n\n this.cacheStore.set(url, { content: '', status: STATUS.LOADING });\n\n const data = await this.cacheApi?.match(url);\n\n if (data) {\n const content = await data.text();\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n\n return;\n }\n\n try {\n await this.cacheApi?.add(new Request(url, fetchOptions));\n\n const response = await this.cacheApi?.match(url);\n const content = (await response?.text()) ?? '';\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n } catch (error: any) {\n this.cacheStore.set(url, { content: '', status: STATUS.FAILED });\n throw error;\n }\n }\n\n private async handleLoading(url: string, callback: () => Promise<void>) {\n let retryCount = 0;\n\n while (this.cacheStore.get(url)?.status === STATUS.LOADING && retryCount < CACHE_MAX_RETRIES) {\n // eslint-disable-next-line no-await-in-loop\n await sleep(0.1);\n retryCount += 1;\n }\n\n if (retryCount >= CACHE_MAX_RETRIES) {\n await callback();\n }\n }\n\n public keys(): Array<string> {\n return [...this.cacheStore.keys()];\n }\n\n public data(): Array<Record<string, StorageItem>> {\n return [...this.cacheStore.entries()].map(([key, value]) => ({ [key]: value }));\n }\n\n public async delete(url: string) {\n if (this.cacheApi) {\n await this.cacheApi.delete(url);\n }\n\n this.cacheStore.delete(url);\n }\n\n public async clear() {\n if (this.cacheApi) {\n const keys = await this.cacheApi.keys();\n\n for (const key of keys) {\n // eslint-disable-next-line no-await-in-loop\n await this.cacheApi.delete(key);\n }\n }\n\n this.cacheStore.clear();\n }\n}\n","import { useEffect, useRef } from 'react';\n\nexport function usePrevious<T>(state: T): T | undefined {\n const ref = useRef<T>();\n\n useEffect(() => {\n ref.current = state;\n });\n\n return ref.current;\n}\n","import convert from 'react-from-dom';\n\nimport { Props, State } from '../types';\n\ninterface GetNodeOptions extends Props, Pick<State, 'content'> {\n handleError: (error: Error) => void;\n hash: string;\n}\n\ninterface UpdateSVGAttributesOptions extends Pick<Props, 'baseURL' | 'uniquifyIDs'> {\n hash: string;\n}\n\nexport function getNode(options: GetNodeOptions) {\n const {\n baseURL,\n content,\n description,\n handleError,\n hash,\n preProcessor,\n title,\n uniquifyIDs = false,\n } = options;\n\n try {\n const svgText = processSVG(content, preProcessor);\n const node = convert(svgText, { nodeOnly: true });\n\n if (!node || !(node instanceof SVGSVGElement)) {\n throw new Error('Could not convert the src to a DOM Node');\n }\n\n const svg = updateSVGAttributes(node, { baseURL, hash, uniquifyIDs });\n\n if (description) {\n const originalDesc = svg.querySelector('desc');\n\n if (originalDesc?.parentNode) {\n originalDesc.parentNode.removeChild(originalDesc);\n }\n\n const descElement = document.createElementNS('http://www.w3.org/2000/svg', 'desc');\n\n descElement.innerHTML = description;\n svg.prepend(descElement);\n }\n\n if (typeof title !== 'undefined') {\n const originalTitle = svg.querySelector('title');\n\n if (originalTitle?.parentNode) {\n originalTitle.parentNode.removeChild(originalTitle);\n }\n\n if (title) {\n const titleElement = document.createElementNS('http://www.w3.org/2000/svg', 'title');\n\n titleElement.innerHTML = title;\n svg.prepend(titleElement);\n }\n }\n\n return svg;\n } catch (error: any) {\n return handleError(error);\n }\n}\n\nexport function processSVG(content: string, preProcessor?: Props['preProcessor']) {\n if (preProcessor) {\n return preProcessor(content);\n }\n\n return content;\n}\n\nexport function updateSVGAttributes(\n node: SVGSVGElement,\n options: UpdateSVGAttributesOptions,\n): SVGSVGElement {\n const { baseURL = '', hash, uniquifyIDs } = options;\n const replaceableAttributes = ['id', 'href', 'xlink:href', 'xlink:role', 'xlink:arcrole'];\n const linkAttributes = ['href', 'xlink:href'];\n const isDataValue = (name: string, value: string) =>\n linkAttributes.includes(name) && (value ? !value.includes('#') : false);\n\n if (!uniquifyIDs) {\n return node;\n }\n\n [...node.children].forEach(d => {\n if (d.attributes?.length) {\n const attributes = Object.values(d.attributes).map(a => {\n const attribute = a;\n const match = /url\\((.*?)\\)/.exec(a.value);\n\n if (match?.[1]) {\n attribute.value = a.value.replace(match[0], `url(${baseURL}${match[1]}__${hash})`);\n }\n\n return attribute;\n });\n\n replaceableAttributes.forEach(r => {\n const attribute = attributes.find(a => a.name === r);\n\n if (attribute && !isDataValue(r, attribute.value)) {\n attribute.value = `${attribute.value}__${hash}`;\n }\n });\n }\n\n if (d.children.length) {\n return updateSVGAttributes(d as SVGSVGElement, options);\n }\n\n return d;\n });\n\n return node;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IA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;AAAA,EACT;AAEA,SAAO,4CAAC,kBAAgB,GAAG,OAAO;AACpC;","names":["import_react","import_react_from_dom","convert","previousState","convert"]}
package/dist/index.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ "use client";
1
2
  var __defProp = Object.defineProperty;
2
3
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
4
  var __publicField = (obj, key, value) => {
@@ -15,7 +16,7 @@ import {
15
16
  useRef as useRef2,
16
17
  useState
17
18
  } from "react";
18
- import convert from "react-from-dom";
19
+ import convert2 from "react-from-dom";
19
20
 
20
21
  // src/config.ts
21
22
  var CACHE_NAME = "react-inlinesvg";
@@ -29,7 +30,7 @@ var STATUS = {
29
30
  UNSUPPORTED: "unsupported"
30
31
  };
31
32
 
32
- // src/helpers.ts
33
+ // src/modules/helpers.ts
33
34
  function canUseDOM() {
34
35
  return !!(typeof window !== "undefined" && window.document && window.document.createElement);
35
36
  }
@@ -87,7 +88,7 @@ function omit(input, ...filter) {
87
88
  return output;
88
89
  }
89
90
 
90
- // src/cache.ts
91
+ // src/modules/cache.ts
91
92
  var CacheStore = class {
92
93
  constructor() {
93
94
  __publicField(this, "cacheApi");
@@ -213,7 +214,7 @@ var CacheStore = class {
213
214
  }
214
215
  };
215
216
 
216
- // src/hooks.tsx
217
+ // src/modules/hooks.tsx
217
218
  import { useEffect, useRef } from "react";
218
219
  function usePrevious(state) {
219
220
  const ref = useRef();
@@ -223,41 +224,8 @@ function usePrevious(state) {
223
224
  return ref.current;
224
225
  }
225
226
 
226
- // src/index.tsx
227
- import { jsx } from "react/jsx-runtime";
228
- var cacheStore;
229
- function updateSVGAttributes(node, options) {
230
- const { baseURL = "", hash, uniquifyIDs } = options;
231
- const replaceableAttributes = ["id", "href", "xlink:href", "xlink:role", "xlink:arcrole"];
232
- const linkAttributes = ["href", "xlink:href"];
233
- const isDataValue = (name, value) => linkAttributes.includes(name) && (value ? !value.includes("#") : false);
234
- if (!uniquifyIDs) {
235
- return node;
236
- }
237
- [...node.children].forEach((d) => {
238
- if (d.attributes?.length) {
239
- const attributes = Object.values(d.attributes).map((a) => {
240
- const attribute = a;
241
- const match = /url\((.*?)\)/.exec(a.value);
242
- if (match?.[1]) {
243
- attribute.value = a.value.replace(match[0], `url(${baseURL}${match[1]}__${hash})`);
244
- }
245
- return attribute;
246
- });
247
- replaceableAttributes.forEach((r) => {
248
- const attribute = attributes.find((a) => a.name === r);
249
- if (attribute && !isDataValue(r, attribute.value)) {
250
- attribute.value = `${attribute.value}__${hash}`;
251
- }
252
- });
253
- }
254
- if (d.children.length) {
255
- return updateSVGAttributes(d, options);
256
- }
257
- return d;
258
- });
259
- return node;
260
- }
227
+ // src/modules/utils.ts
228
+ import convert from "react-from-dom";
261
229
  function getNode(options) {
262
230
  const {
263
231
  baseURL,
@@ -307,6 +275,42 @@ function processSVG(content, preProcessor) {
307
275
  }
308
276
  return content;
309
277
  }
278
+ function updateSVGAttributes(node, options) {
279
+ const { baseURL = "", hash, uniquifyIDs } = options;
280
+ const replaceableAttributes = ["id", "href", "xlink:href", "xlink:role", "xlink:arcrole"];
281
+ const linkAttributes = ["href", "xlink:href"];
282
+ const isDataValue = (name, value) => linkAttributes.includes(name) && (value ? !value.includes("#") : false);
283
+ if (!uniquifyIDs) {
284
+ return node;
285
+ }
286
+ [...node.children].forEach((d) => {
287
+ if (d.attributes?.length) {
288
+ const attributes = Object.values(d.attributes).map((a) => {
289
+ const attribute = a;
290
+ const match = /url\((.*?)\)/.exec(a.value);
291
+ if (match?.[1]) {
292
+ attribute.value = a.value.replace(match[0], `url(${baseURL}${match[1]}__${hash})`);
293
+ }
294
+ return attribute;
295
+ });
296
+ replaceableAttributes.forEach((r) => {
297
+ const attribute = attributes.find((a) => a.name === r);
298
+ if (attribute && !isDataValue(r, attribute.value)) {
299
+ attribute.value = `${attribute.value}__${hash}`;
300
+ }
301
+ });
302
+ }
303
+ if (d.children.length) {
304
+ return updateSVGAttributes(d, options);
305
+ }
306
+ return d;
307
+ });
308
+ return node;
309
+ }
310
+
311
+ // src/index.tsx
312
+ import { jsx } from "react/jsx-runtime";
313
+ var cacheStore;
310
314
  function ReactInlineSVG(props) {
311
315
  const {
312
316
  cacheRequests = true,
@@ -359,10 +363,14 @@ function ReactInlineSVG(props) {
359
363
  });
360
364
  }
361
365
  }, []);
366
+ const fetchContent = useCallback(async () => {
367
+ const responseContent = await request(src, fetchOptions);
368
+ handleLoad(responseContent);
369
+ }, [fetchOptions, handleLoad, src]);
362
370
  const getElement = useCallback(() => {
363
371
  try {
364
372
  const node = getNode({ ...props, handleError, hash: hash.current, content });
365
- const convertedElement = convert(node);
373
+ const convertedElement = convert2(node);
366
374
  if (!convertedElement || !isValidElement(convertedElement)) {
367
375
  throw new Error("Could not convert the src to a React element");
368
376
  }
@@ -374,10 +382,6 @@ function ReactInlineSVG(props) {
374
382
  handleError(new Error(error.message));
375
383
  }
376
384
  }, [content, handleError, props]);
377
- const fetchContent = useCallback(async () => {
378
- const responseContent = await request(src, fetchOptions);
379
- handleLoad(responseContent);
380
- }, [fetchOptions, handleLoad, src]);
381
385
  const getContent = useCallback(async () => {
382
386
  const dataURI = /^data:image\/svg[^,]*?(;base64)?,(.*)/u.exec(src);
383
387
  let inlineSrc;
@@ -454,19 +458,7 @@ function ReactInlineSVG(props) {
454
458
  } else if (previousProps.title !== title || previousProps.description !== description) {
455
459
  getElement();
456
460
  }
457
- }, [
458
- description,
459
- getElement,
460
- handleError,
461
- isCached,
462
- load,
463
- onLoad,
464
- previousProps,
465
- previousState,
466
- src,
467
- status,
468
- title
469
- ]);
461
+ }, [description, getElement, handleError, load, previousProps, src, title]);
470
462
  useEffect2(() => {
471
463
  if (!previousState) {
472
464
  return;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.tsx","../src/config.ts","../src/helpers.ts","../src/cache.ts","../src/hooks.tsx"],"sourcesContent":["import {\n cloneElement,\n isValidElement,\n ReactElement,\n useCallback,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react';\nimport convert from 'react-from-dom';\n\nimport CacheStore from './cache';\nimport { STATUS } from './config';\nimport { canUseDOM, isSupportedEnvironment, omit, randomString, request } from './helpers';\nimport { usePrevious } from './hooks';\nimport { FetchError, Props, State, Status } from './types';\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let cacheStore: CacheStore;\n\ninterface GetNodeOptions extends Props, Pick<State, 'content'> {\n handleError: (error: Error) => void;\n hash: string;\n}\n\ninterface UpdateSVGAttributesOptions extends Pick<Props, 'baseURL' | 'uniquifyIDs'> {\n hash: string;\n}\n\nfunction updateSVGAttributes(\n node: SVGSVGElement,\n options: UpdateSVGAttributesOptions,\n): SVGSVGElement {\n const { baseURL = '', hash, uniquifyIDs } = options;\n const replaceableAttributes = ['id', 'href', 'xlink:href', 'xlink:role', 'xlink:arcrole'];\n const linkAttributes = ['href', 'xlink:href'];\n const isDataValue = (name: string, value: string) =>\n linkAttributes.includes(name) && (value ? !value.includes('#') : false);\n\n if (!uniquifyIDs) {\n return node;\n }\n\n [...node.children].forEach(d => {\n if (d.attributes?.length) {\n const attributes = Object.values(d.attributes).map(a => {\n const attribute = a;\n const match = /url\\((.*?)\\)/.exec(a.value);\n\n if (match?.[1]) {\n attribute.value = a.value.replace(match[0], `url(${baseURL}${match[1]}__${hash})`);\n }\n\n return attribute;\n });\n\n replaceableAttributes.forEach(r => {\n const attribute = attributes.find(a => a.name === r);\n\n if (attribute && !isDataValue(r, attribute.value)) {\n attribute.value = `${attribute.value}__${hash}`;\n }\n });\n }\n\n if (d.children.length) {\n return updateSVGAttributes(d as SVGSVGElement, options);\n }\n\n return d;\n });\n\n return node;\n}\n\nfunction getNode(options: GetNodeOptions) {\n const {\n baseURL,\n content,\n description,\n handleError,\n hash,\n preProcessor,\n title,\n uniquifyIDs = false,\n } = options;\n\n try {\n const svgText = processSVG(content, preProcessor);\n const node = convert(svgText, { nodeOnly: true });\n\n if (!node || !(node instanceof SVGSVGElement)) {\n throw new Error('Could not convert the src to a DOM Node');\n }\n\n const svg = updateSVGAttributes(node, { baseURL, hash, uniquifyIDs });\n\n if (description) {\n const originalDesc = svg.querySelector('desc');\n\n if (originalDesc?.parentNode) {\n originalDesc.parentNode.removeChild(originalDesc);\n }\n\n const descElement = document.createElementNS('http://www.w3.org/2000/svg', 'desc');\n\n descElement.innerHTML = description;\n svg.prepend(descElement);\n }\n\n if (typeof title !== 'undefined') {\n const originalTitle = svg.querySelector('title');\n\n if (originalTitle?.parentNode) {\n originalTitle.parentNode.removeChild(originalTitle);\n }\n\n if (title) {\n const titleElement = document.createElementNS('http://www.w3.org/2000/svg', 'title');\n\n titleElement.innerHTML = title;\n svg.prepend(titleElement);\n }\n }\n\n return svg;\n } catch (error: any) {\n return handleError(error);\n }\n}\n\nfunction processSVG(content: string, preProcessor?: Props['preProcessor']) {\n if (preProcessor) {\n return preProcessor(content);\n }\n\n return content;\n}\n\nfunction ReactInlineSVG(props: Props) {\n const {\n cacheRequests = true,\n children = null,\n description,\n fetchOptions,\n innerRef,\n loader = null,\n onError,\n onLoad,\n src,\n title,\n uniqueHash,\n } = props;\n const [state, setState] = useReducer(\n (previousState: State, nextState: Partial<State>) => ({\n ...previousState,\n ...nextState,\n }),\n {\n content: '',\n element: null,\n\n isCached: cacheRequests && cacheStore.isCached(props.src),\n status: STATUS.IDLE,\n },\n );\n const { content, element, isCached, status } = state;\n const previousProps = usePrevious(props);\n const previousState = usePrevious(state);\n\n const hash = useRef(uniqueHash ?? randomString(8));\n const isActive = useRef(false);\n const isInitialized = useRef(false);\n\n const handleError = useCallback(\n (error: Error | FetchError) => {\n if (isActive.current) {\n setState({\n status:\n error.message === 'Browser does not support SVG' ? STATUS.UNSUPPORTED : STATUS.FAILED,\n });\n\n onError?.(error);\n }\n },\n [onError],\n );\n\n const handleLoad = useCallback((loadedContent: string, hasCache = false) => {\n if (isActive.current) {\n setState({\n content: loadedContent,\n isCached: hasCache,\n status: STATUS.LOADED,\n });\n }\n }, []);\n\n const getElement = useCallback(() => {\n try {\n const node = getNode({ ...props, handleError, hash: hash.current, content }) as Node;\n const convertedElement = convert(node);\n\n if (!convertedElement || !isValidElement(convertedElement)) {\n throw new Error('Could not convert the src to a React element');\n }\n\n setState({\n element: convertedElement,\n status: STATUS.READY,\n });\n } catch (error: any) {\n handleError(new Error(error.message));\n }\n }, [content, handleError, props]);\n\n const fetchContent = useCallback(async () => {\n const responseContent: string = await request(src, fetchOptions);\n\n handleLoad(responseContent);\n }, [fetchOptions, handleLoad, src]);\n\n const getContent = useCallback(async () => {\n const dataURI = /^data:image\\/svg[^,]*?(;base64)?,(.*)/u.exec(src);\n let inlineSrc;\n\n if (dataURI) {\n inlineSrc = dataURI[1] ? window.atob(dataURI[2]) : decodeURIComponent(dataURI[2]);\n } else if (src.includes('<svg')) {\n inlineSrc = src;\n }\n\n if (inlineSrc) {\n handleLoad(inlineSrc);\n\n return;\n }\n\n try {\n if (cacheRequests) {\n const cachedContent = await cacheStore.get(src, fetchOptions);\n\n handleLoad(cachedContent, true);\n } else {\n await fetchContent();\n }\n } catch (error: any) {\n handleError(error);\n }\n }, [cacheRequests, fetchContent, fetchOptions, handleError, handleLoad, src]);\n\n const load = useCallback(async () => {\n if (isActive.current) {\n setState({\n content: '',\n element: null,\n isCached: false,\n status: STATUS.LOADING,\n });\n }\n }, []);\n\n // Run on mount\n useEffect(\n () => {\n isActive.current = true;\n\n if (!canUseDOM() || isInitialized.current) {\n return () => undefined;\n }\n\n try {\n if (status === STATUS.IDLE) {\n if (!isSupportedEnvironment()) {\n throw new Error('Browser does not support SVG');\n }\n\n if (!src) {\n throw new Error('Missing src');\n }\n\n load();\n }\n } catch (error: any) {\n handleError(error);\n }\n\n isInitialized.current = true;\n\n return () => {\n isActive.current = false;\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [],\n );\n\n // Handle prop changes\n useEffect(() => {\n if (!canUseDOM()) {\n return;\n }\n\n if (!previousProps) {\n return;\n }\n\n if (previousProps.src !== src) {\n if (!src) {\n handleError(new Error('Missing src'));\n\n return;\n }\n\n load();\n } else if (previousProps.title !== title || previousProps.description !== description) {\n getElement();\n }\n }, [\n description,\n getElement,\n handleError,\n isCached,\n load,\n onLoad,\n previousProps,\n previousState,\n src,\n status,\n title,\n ]);\n\n // handle state\n useEffect(() => {\n if (!previousState) {\n return;\n }\n\n if (previousState.status !== STATUS.LOADING && status === STATUS.LOADING) {\n getContent();\n }\n\n if (previousState.status !== STATUS.LOADED && status === STATUS.LOADED) {\n getElement();\n }\n\n if (previousState.status !== STATUS.READY && status === STATUS.READY) {\n onLoad?.(src, isCached);\n }\n }, [getContent, getElement, isCached, onLoad, previousState, src, status]);\n\n const elementProps = omit(\n props,\n 'baseURL',\n 'cacheRequests',\n 'children',\n 'description',\n 'fetchOptions',\n 'innerRef',\n 'loader',\n 'onError',\n 'onLoad',\n 'preProcessor',\n 'src',\n 'title',\n 'uniqueHash',\n 'uniquifyIDs',\n );\n\n if (!canUseDOM()) {\n return loader;\n }\n\n if (element) {\n return cloneElement(element as ReactElement, { ref: innerRef, ...elementProps });\n }\n\n if (([STATUS.UNSUPPORTED, STATUS.FAILED] as Status[]).includes(status)) {\n return children;\n }\n\n return loader;\n}\n\nexport default function InlineSVG(props: Props) {\n if (!cacheStore) {\n cacheStore = new CacheStore();\n }\n\n const { loader } = props;\n const hasCallback = useRef(false);\n const [isReady, setReady] = useState(cacheStore.isReady);\n\n useEffect(() => {\n if (!hasCallback.current) {\n cacheStore.onReady(() => {\n setReady(true);\n });\n\n hasCallback.current = true;\n }\n }, []);\n\n if (!isReady) {\n return loader;\n }\n\n return <ReactInlineSVG {...props} />;\n}\n\nexport * from './types';\n","export const CACHE_NAME = 'react-inlinesvg';\nexport const CACHE_MAX_RETRIES = 10;\n\nexport const STATUS = {\n IDLE: 'idle',\n LOADING: 'loading',\n LOADED: 'loaded',\n FAILED: 'failed',\n READY: 'ready',\n UNSUPPORTED: 'unsupported',\n} as const;\n","import type { PlainObject } from './types';\n\nexport function canUseDOM(): boolean {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\n\nexport async function request(url: string, options?: RequestInit) {\n const response = await fetch(url, options);\n const contentType = response.headers.get('content-type');\n const [fileType] = (contentType ?? '').split(/ ?; ?/);\n\n if (response.status > 299) {\n throw new Error('Not found');\n }\n\n if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {\n throw new Error(`Content type isn't valid: ${fileType}`);\n }\n\n return response.text();\n}\n\nexport function sleep(seconds = 1) {\n return new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n}\n\nexport function supportsInlineSVG(): boolean {\n /* c8 ignore next 3 */\n if (!document) {\n return false;\n }\n\n const div = document.createElement('div');\n\n div.innerHTML = '<svg />';\n const svg = div.firstChild as SVGSVGElement;\n\n return !!svg && svg.namespaceURI === 'http://www.w3.org/2000/svg';\n}\n\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function randomString(length: number): string {\n const letters = 'abcdefghijklmnopqrstuvwxyz';\n const numbers = '1234567890';\n const charset = `${letters}${letters.toUpperCase()}${numbers}`;\n\n let R = '';\n\n for (let index = 0; index < length; index++) {\n R += randomCharacter(charset);\n }\n\n return R;\n}\n\n/**\n * Remove properties from an object\n */\nexport function omit<T extends PlainObject, K extends keyof T>(\n input: T,\n ...filter: K[]\n): Omit<T, K> {\n const output: any = {};\n\n for (const key in input) {\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n }\n\n return output as Omit<T, K>;\n}\n","import { CACHE_MAX_RETRIES, CACHE_NAME, STATUS } from './config';\nimport { canUseDOM, request, sleep } from './helpers';\nimport { StorageItem } from './types';\n\nexport default class CacheStore {\n private cacheApi: Cache | undefined;\n private readonly cacheStore: Map<string, StorageItem>;\n private readonly subscribers: Array<() => void> = [];\n public isReady = false;\n\n constructor() {\n this.cacheStore = new Map<string, StorageItem>();\n\n let cacheName = CACHE_NAME;\n let usePersistentCache = false;\n\n if (canUseDOM()) {\n cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;\n usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE && 'caches' in window;\n }\n\n if (usePersistentCache) {\n caches\n .open(cacheName)\n .then(cache => {\n this.cacheApi = cache;\n this.isReady = true;\n\n this.subscribers.forEach(callback => callback());\n })\n .catch(error => {\n this.isReady = true;\n\n // eslint-disable-next-line no-console\n console.error(`Failed to open cache: ${error.message}`);\n });\n } else {\n this.isReady = true;\n }\n }\n\n public onReady(callback: () => void) {\n if (this.isReady) {\n callback();\n } else {\n this.subscribers.push(callback);\n }\n }\n\n public async get(url: string, fetchOptions?: RequestInit) {\n await (this.cacheApi\n ? this.fetchAndAddToPersistentCache(url, fetchOptions)\n : this.fetchAndAddToInternalCache(url, fetchOptions));\n\n return this.cacheStore.get(url)?.content ?? '';\n }\n\n public set(url: string, data: StorageItem) {\n this.cacheStore.set(url, data);\n }\n\n public isCached(url: string) {\n return this.cacheStore.get(url)?.status === STATUS.LOADED;\n }\n\n private async fetchAndAddToInternalCache(url: string, fetchOptions?: RequestInit) {\n const cache = this.cacheStore.get(url);\n\n if (cache?.status === STATUS.LOADING) {\n await this.handleLoading(url, async () => {\n this.cacheStore.set(url, { content: '', status: STATUS.IDLE });\n await this.fetchAndAddToInternalCache(url, fetchOptions);\n });\n\n return;\n }\n\n if (!cache?.content) {\n this.cacheStore.set(url, { content: '', status: STATUS.LOADING });\n\n try {\n const content = await request(url, fetchOptions);\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n } catch (error: any) {\n this.cacheStore.set(url, { content: '', status: STATUS.FAILED });\n throw error;\n }\n }\n }\n\n private async fetchAndAddToPersistentCache(url: string, fetchOptions?: RequestInit) {\n const cache = this.cacheStore.get(url);\n\n if (cache?.status === STATUS.LOADED) {\n return;\n }\n\n if (cache?.status === STATUS.LOADING) {\n await this.handleLoading(url, async () => {\n this.cacheStore.set(url, { content: '', status: STATUS.IDLE });\n await this.fetchAndAddToPersistentCache(url, fetchOptions);\n });\n\n return;\n }\n\n this.cacheStore.set(url, { content: '', status: STATUS.LOADING });\n\n const data = await this.cacheApi?.match(url);\n\n if (data) {\n const content = await data.text();\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n\n return;\n }\n\n try {\n await this.cacheApi?.add(new Request(url, fetchOptions));\n\n const response = await this.cacheApi?.match(url);\n const content = (await response?.text()) ?? '';\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n } catch (error: any) {\n this.cacheStore.set(url, { content: '', status: STATUS.FAILED });\n throw error;\n }\n }\n\n private async handleLoading(url: string, callback: () => Promise<void>) {\n let retryCount = 0;\n\n // eslint-disable-next-line no-await-in-loop\n while (this.cacheStore.get(url)?.status === STATUS.LOADING && retryCount < CACHE_MAX_RETRIES) {\n // eslint-disable-next-line no-await-in-loop\n await sleep(0.1);\n retryCount += 1;\n }\n\n if (retryCount >= CACHE_MAX_RETRIES) {\n await callback();\n }\n }\n\n public keys(): Array<string> {\n return [...this.cacheStore.keys()];\n }\n\n public data(): Array<Record<string, StorageItem>> {\n return [...this.cacheStore.entries()].map(([key, value]) => ({ [key]: value }));\n }\n\n public async delete(url: string) {\n if (this.cacheApi) {\n await this.cacheApi.delete(url);\n }\n\n this.cacheStore.delete(url);\n }\n\n public async clear() {\n if (this.cacheApi) {\n const keys = await this.cacheApi.keys();\n\n for (const key of keys) {\n // eslint-disable-next-line no-await-in-loop\n await this.cacheApi.delete(key);\n }\n }\n\n this.cacheStore.clear();\n }\n}\n","import { useEffect, useRef } from 'react';\n\nexport function usePrevious<T>(state: T): T | undefined {\n const ref = useRef<T>();\n\n useEffect(() => {\n ref.current = state;\n });\n\n return ref.current;\n}\n"],"mappings":";;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA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;AAAA,MACf,CAAC;AAED,kBAAY,UAAU;AAAA,IACxB;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,SAAO,oBAAC,kBAAgB,GAAG,OAAO;AACpC;","names":["useEffect","useRef","previousState","useRef","useEffect"]}
1
+ {"version":3,"sources":["../src/index.tsx","../src/config.ts","../src/modules/helpers.ts","../src/modules/cache.ts","../src/modules/hooks.tsx","../src/modules/utils.ts"],"sourcesContent":["import {\n cloneElement,\n isValidElement,\n ReactElement,\n useCallback,\n useEffect,\n useReducer,\n useRef,\n useState,\n} from 'react';\nimport convert from 'react-from-dom';\n\nimport { STATUS } from './config';\nimport CacheStore from './modules/cache';\nimport { canUseDOM, isSupportedEnvironment, omit, randomString, request } from './modules/helpers';\nimport { usePrevious } from './modules/hooks';\nimport { getNode } from './modules/utils';\nimport { FetchError, Props, State, Status } from './types';\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let cacheStore: CacheStore;\n\nfunction ReactInlineSVG(props: Props) {\n const {\n cacheRequests = true,\n children = null,\n description,\n fetchOptions,\n innerRef,\n loader = null,\n onError,\n onLoad,\n src,\n title,\n uniqueHash,\n } = props;\n const [state, setState] = useReducer(\n (previousState: State, nextState: Partial<State>) => ({\n ...previousState,\n ...nextState,\n }),\n {\n content: '',\n element: null,\n\n isCached: cacheRequests && cacheStore.isCached(props.src),\n status: STATUS.IDLE,\n },\n );\n const { content, element, isCached, status } = state;\n const previousProps = usePrevious(props);\n const previousState = usePrevious(state);\n\n const hash = useRef(uniqueHash ?? randomString(8));\n const isActive = useRef(false);\n const isInitialized = useRef(false);\n\n const handleError = useCallback(\n (error: Error | FetchError) => {\n if (isActive.current) {\n setState({\n status:\n error.message === 'Browser does not support SVG' ? STATUS.UNSUPPORTED : STATUS.FAILED,\n });\n\n onError?.(error);\n }\n },\n [onError],\n );\n\n const handleLoad = useCallback((loadedContent: string, hasCache = false) => {\n if (isActive.current) {\n setState({\n content: loadedContent,\n isCached: hasCache,\n status: STATUS.LOADED,\n });\n }\n }, []);\n\n const fetchContent = useCallback(async () => {\n const responseContent: string = await request(src, fetchOptions);\n\n handleLoad(responseContent);\n }, [fetchOptions, handleLoad, src]);\n\n const getElement = useCallback(() => {\n try {\n const node = getNode({ ...props, handleError, hash: hash.current, content }) as Node;\n const convertedElement = convert(node);\n\n if (!convertedElement || !isValidElement(convertedElement)) {\n throw new Error('Could not convert the src to a React element');\n }\n\n setState({\n element: convertedElement,\n status: STATUS.READY,\n });\n } catch (error: any) {\n handleError(new Error(error.message));\n }\n }, [content, handleError, props]);\n\n const getContent = useCallback(async () => {\n const dataURI = /^data:image\\/svg[^,]*?(;base64)?,(.*)/u.exec(src);\n let inlineSrc;\n\n if (dataURI) {\n inlineSrc = dataURI[1] ? window.atob(dataURI[2]) : decodeURIComponent(dataURI[2]);\n } else if (src.includes('<svg')) {\n inlineSrc = src;\n }\n\n if (inlineSrc) {\n handleLoad(inlineSrc);\n\n return;\n }\n\n try {\n if (cacheRequests) {\n const cachedContent = await cacheStore.get(src, fetchOptions);\n\n handleLoad(cachedContent, true);\n } else {\n await fetchContent();\n }\n } catch (error: any) {\n handleError(error);\n }\n }, [cacheRequests, fetchContent, fetchOptions, handleError, handleLoad, src]);\n\n const load = useCallback(async () => {\n if (isActive.current) {\n setState({\n content: '',\n element: null,\n isCached: false,\n status: STATUS.LOADING,\n });\n }\n }, []);\n\n // Run on mount\n useEffect(\n () => {\n isActive.current = true;\n\n if (!canUseDOM() || isInitialized.current) {\n return () => undefined;\n }\n\n try {\n if (status === STATUS.IDLE) {\n if (!isSupportedEnvironment()) {\n throw new Error('Browser does not support SVG');\n }\n\n if (!src) {\n throw new Error('Missing src');\n }\n\n load();\n }\n } catch (error: any) {\n handleError(error);\n }\n\n isInitialized.current = true;\n\n return () => {\n isActive.current = false;\n };\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [],\n );\n\n // Handle prop changes\n useEffect(() => {\n if (!canUseDOM()) {\n return;\n }\n\n if (!previousProps) {\n return;\n }\n\n if (previousProps.src !== src) {\n if (!src) {\n handleError(new Error('Missing src'));\n\n return;\n }\n\n load();\n } else if (previousProps.title !== title || previousProps.description !== description) {\n getElement();\n }\n }, [description, getElement, handleError, load, previousProps, src, title]);\n\n // handle state\n useEffect(() => {\n if (!previousState) {\n return;\n }\n\n if (previousState.status !== STATUS.LOADING && status === STATUS.LOADING) {\n getContent();\n }\n\n if (previousState.status !== STATUS.LOADED && status === STATUS.LOADED) {\n getElement();\n }\n\n if (previousState.status !== STATUS.READY && status === STATUS.READY) {\n onLoad?.(src, isCached);\n }\n }, [getContent, getElement, isCached, onLoad, previousState, src, status]);\n\n const elementProps = omit(\n props,\n 'baseURL',\n 'cacheRequests',\n 'children',\n 'description',\n 'fetchOptions',\n 'innerRef',\n 'loader',\n 'onError',\n 'onLoad',\n 'preProcessor',\n 'src',\n 'title',\n 'uniqueHash',\n 'uniquifyIDs',\n );\n\n if (!canUseDOM()) {\n return loader;\n }\n\n if (element) {\n return cloneElement(element as ReactElement, { ref: innerRef, ...elementProps });\n }\n\n if (([STATUS.UNSUPPORTED, STATUS.FAILED] as Status[]).includes(status)) {\n return children;\n }\n\n return loader;\n}\n\nexport default function InlineSVG(props: Props) {\n if (!cacheStore) {\n cacheStore = new CacheStore();\n }\n\n const { loader } = props;\n const hasCallback = useRef(false);\n const [isReady, setReady] = useState(cacheStore.isReady);\n\n useEffect(() => {\n if (!hasCallback.current) {\n cacheStore.onReady(() => {\n setReady(true);\n });\n\n hasCallback.current = true;\n }\n }, []);\n\n if (!isReady) {\n return loader;\n }\n\n return <ReactInlineSVG {...props} />;\n}\n\nexport * from './types';\n","export const CACHE_NAME = 'react-inlinesvg';\nexport const CACHE_MAX_RETRIES = 10;\n\nexport const STATUS = {\n IDLE: 'idle',\n LOADING: 'loading',\n LOADED: 'loaded',\n FAILED: 'failed',\n READY: 'ready',\n UNSUPPORTED: 'unsupported',\n} as const;\n","import type { PlainObject } from '../types';\n\nexport function canUseDOM(): boolean {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\n\nexport async function request(url: string, options?: RequestInit) {\n const response = await fetch(url, options);\n const contentType = response.headers.get('content-type');\n const [fileType] = (contentType ?? '').split(/ ?; ?/);\n\n if (response.status > 299) {\n throw new Error('Not found');\n }\n\n if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {\n throw new Error(`Content type isn't valid: ${fileType}`);\n }\n\n return response.text();\n}\n\nexport function sleep(seconds = 1) {\n return new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n}\n\nexport function supportsInlineSVG(): boolean {\n /* c8 ignore next 3 */\n if (!document) {\n return false;\n }\n\n const div = document.createElement('div');\n\n div.innerHTML = '<svg />';\n const svg = div.firstChild as SVGSVGElement;\n\n return !!svg && svg.namespaceURI === 'http://www.w3.org/2000/svg';\n}\n\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function randomString(length: number): string {\n const letters = 'abcdefghijklmnopqrstuvwxyz';\n const numbers = '1234567890';\n const charset = `${letters}${letters.toUpperCase()}${numbers}`;\n\n let R = '';\n\n for (let index = 0; index < length; index++) {\n R += randomCharacter(charset);\n }\n\n return R;\n}\n\n/**\n * Remove properties from an object\n */\nexport function omit<T extends PlainObject, K extends keyof T>(\n input: T,\n ...filter: K[]\n): Omit<T, K> {\n const output: any = {};\n\n for (const key in input) {\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n }\n\n return output as Omit<T, K>;\n}\n","import { canUseDOM, request, sleep } from './helpers';\n\nimport { CACHE_MAX_RETRIES, CACHE_NAME, STATUS } from '../config';\nimport { StorageItem } from '../types';\n\nexport default class CacheStore {\n private cacheApi: Cache | undefined;\n private readonly cacheStore: Map<string, StorageItem>;\n private readonly subscribers: Array<() => void> = [];\n public isReady = false;\n\n constructor() {\n this.cacheStore = new Map<string, StorageItem>();\n\n let cacheName = CACHE_NAME;\n let usePersistentCache = false;\n\n if (canUseDOM()) {\n cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;\n usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE && 'caches' in window;\n }\n\n if (usePersistentCache) {\n caches\n .open(cacheName)\n .then(cache => {\n this.cacheApi = cache;\n this.isReady = true;\n\n this.subscribers.forEach(callback => callback());\n })\n .catch(error => {\n this.isReady = true;\n\n // eslint-disable-next-line no-console\n console.error(`Failed to open cache: ${error.message}`);\n });\n } else {\n this.isReady = true;\n }\n }\n\n public onReady(callback: () => void) {\n if (this.isReady) {\n callback();\n } else {\n this.subscribers.push(callback);\n }\n }\n\n public async get(url: string, fetchOptions?: RequestInit) {\n await (this.cacheApi\n ? this.fetchAndAddToPersistentCache(url, fetchOptions)\n : this.fetchAndAddToInternalCache(url, fetchOptions));\n\n return this.cacheStore.get(url)?.content ?? '';\n }\n\n public set(url: string, data: StorageItem) {\n this.cacheStore.set(url, data);\n }\n\n public isCached(url: string) {\n return this.cacheStore.get(url)?.status === STATUS.LOADED;\n }\n\n private async fetchAndAddToInternalCache(url: string, fetchOptions?: RequestInit) {\n const cache = this.cacheStore.get(url);\n\n if (cache?.status === STATUS.LOADING) {\n await this.handleLoading(url, async () => {\n this.cacheStore.set(url, { content: '', status: STATUS.IDLE });\n await this.fetchAndAddToInternalCache(url, fetchOptions);\n });\n\n return;\n }\n\n if (!cache?.content) {\n this.cacheStore.set(url, { content: '', status: STATUS.LOADING });\n\n try {\n const content = await request(url, fetchOptions);\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n } catch (error: any) {\n this.cacheStore.set(url, { content: '', status: STATUS.FAILED });\n throw error;\n }\n }\n }\n\n private async fetchAndAddToPersistentCache(url: string, fetchOptions?: RequestInit) {\n const cache = this.cacheStore.get(url);\n\n if (cache?.status === STATUS.LOADED) {\n return;\n }\n\n if (cache?.status === STATUS.LOADING) {\n await this.handleLoading(url, async () => {\n this.cacheStore.set(url, { content: '', status: STATUS.IDLE });\n await this.fetchAndAddToPersistentCache(url, fetchOptions);\n });\n\n return;\n }\n\n this.cacheStore.set(url, { content: '', status: STATUS.LOADING });\n\n const data = await this.cacheApi?.match(url);\n\n if (data) {\n const content = await data.text();\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n\n return;\n }\n\n try {\n await this.cacheApi?.add(new Request(url, fetchOptions));\n\n const response = await this.cacheApi?.match(url);\n const content = (await response?.text()) ?? '';\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n } catch (error: any) {\n this.cacheStore.set(url, { content: '', status: STATUS.FAILED });\n throw error;\n }\n }\n\n private async handleLoading(url: string, callback: () => Promise<void>) {\n let retryCount = 0;\n\n while (this.cacheStore.get(url)?.status === STATUS.LOADING && retryCount < CACHE_MAX_RETRIES) {\n // eslint-disable-next-line no-await-in-loop\n await sleep(0.1);\n retryCount += 1;\n }\n\n if (retryCount >= CACHE_MAX_RETRIES) {\n await callback();\n }\n }\n\n public keys(): Array<string> {\n return [...this.cacheStore.keys()];\n }\n\n public data(): Array<Record<string, StorageItem>> {\n return [...this.cacheStore.entries()].map(([key, value]) => ({ [key]: value }));\n }\n\n public async delete(url: string) {\n if (this.cacheApi) {\n await this.cacheApi.delete(url);\n }\n\n this.cacheStore.delete(url);\n }\n\n public async clear() {\n if (this.cacheApi) {\n const keys = await this.cacheApi.keys();\n\n for (const key of keys) {\n // eslint-disable-next-line no-await-in-loop\n await this.cacheApi.delete(key);\n }\n }\n\n this.cacheStore.clear();\n }\n}\n","import { useEffect, useRef } from 'react';\n\nexport function usePrevious<T>(state: T): T | undefined {\n const ref = useRef<T>();\n\n useEffect(() => {\n ref.current = state;\n });\n\n return ref.current;\n}\n","import convert from 'react-from-dom';\n\nimport { Props, State } from '../types';\n\ninterface GetNodeOptions extends Props, Pick<State, 'content'> {\n handleError: (error: Error) => void;\n hash: string;\n}\n\ninterface UpdateSVGAttributesOptions extends Pick<Props, 'baseURL' | 'uniquifyIDs'> {\n hash: string;\n}\n\nexport function getNode(options: GetNodeOptions) {\n const {\n baseURL,\n content,\n description,\n handleError,\n hash,\n preProcessor,\n title,\n uniquifyIDs = false,\n } = options;\n\n try {\n const svgText = processSVG(content, preProcessor);\n const node = convert(svgText, { nodeOnly: true });\n\n if (!node || !(node instanceof SVGSVGElement)) {\n throw new Error('Could not convert the src to a DOM Node');\n }\n\n const svg = updateSVGAttributes(node, { baseURL, hash, uniquifyIDs });\n\n if (description) {\n const originalDesc = svg.querySelector('desc');\n\n if (originalDesc?.parentNode) {\n originalDesc.parentNode.removeChild(originalDesc);\n }\n\n const descElement = document.createElementNS('http://www.w3.org/2000/svg', 'desc');\n\n descElement.innerHTML = description;\n svg.prepend(descElement);\n }\n\n if (typeof title !== 'undefined') {\n const originalTitle = svg.querySelector('title');\n\n if (originalTitle?.parentNode) {\n originalTitle.parentNode.removeChild(originalTitle);\n }\n\n if (title) {\n const titleElement = document.createElementNS('http://www.w3.org/2000/svg', 'title');\n\n titleElement.innerHTML = title;\n svg.prepend(titleElement);\n }\n }\n\n return svg;\n } catch (error: any) {\n return handleError(error);\n }\n}\n\nexport function processSVG(content: string, preProcessor?: Props['preProcessor']) {\n if (preProcessor) {\n return preProcessor(content);\n }\n\n return content;\n}\n\nexport function updateSVGAttributes(\n node: SVGSVGElement,\n options: UpdateSVGAttributesOptions,\n): SVGSVGElement {\n const { baseURL = '', hash, uniquifyIDs } = options;\n const replaceableAttributes = ['id', 'href', 'xlink:href', 'xlink:role', 'xlink:arcrole'];\n const linkAttributes = ['href', 'xlink:href'];\n const isDataValue = (name: string, value: string) =>\n linkAttributes.includes(name) && (value ? !value.includes('#') : false);\n\n if (!uniquifyIDs) {\n return node;\n }\n\n [...node.children].forEach(d => {\n if (d.attributes?.length) {\n const attributes = Object.values(d.attributes).map(a => {\n const attribute = a;\n const match = /url\\((.*?)\\)/.exec(a.value);\n\n if (match?.[1]) {\n attribute.value = a.value.replace(match[0], `url(${baseURL}${match[1]}__${hash})`);\n }\n\n return attribute;\n });\n\n replaceableAttributes.forEach(r => {\n const attribute = attributes.find(a => a.name === r);\n\n if (attribute && !isDataValue(r, attribute.value)) {\n attribute.value = `${attribute.value}__${hash}`;\n }\n });\n }\n\n if (d.children.length) {\n return updateSVGAttributes(d as SVGSVGElement, options);\n }\n\n return d;\n });\n\n return node;\n}\n"],"mappings":";;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA,aAAAA;AAAA,EACA;AAAA,EACA,UAAAC;AAAA,EACA;AAAA,OACK;AACP,OAAOC,cAAa;;;ACVb,IAAM,aAAa;AACnB,IAAM,oBAAoB;AAE1B,IAAM,SAAS;AAAA,EACpB,MAAM;AAAA,EACN,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,aAAa;AACf;;;ACRO,SAAS,YAAqB;AACnC,SAAO,CAAC,EAAE,OAAO,WAAW,eAAe,OAAO,YAAY,OAAO,SAAS;AAChF;AAEO,SAAS,yBAAkC;AAChD,SAAO,kBAAkB,KAAK,OAAO,WAAW,eAAe,WAAW;AAC5E;AAEA,eAAsB,QAAQ,KAAa,SAAuB;AAChE,QAAM,WAAW,MAAM,MAAM,KAAK,OAAO;AACzC,QAAM,cAAc,SAAS,QAAQ,IAAI,cAAc;AACvD,QAAM,CAAC,QAAQ,KAAK,eAAe,IAAI,MAAM,OAAO;AAEpD,MAAI,SAAS,SAAS,KAAK;AACzB,UAAM,IAAI,MAAM,WAAW;AAAA,EAC7B;AAEA,MAAI,CAAC,CAAC,iBAAiB,YAAY,EAAE,KAAK,OAAK,SAAS,SAAS,CAAC,CAAC,GAAG;AACpE,UAAM,IAAI,MAAM,6BAA6B,QAAQ,EAAE;AAAA,EACzD;AAEA,SAAO,SAAS,KAAK;AACvB;AAEO,SAAS,MAAM,UA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T;AAEe,SAAR,UAA2B,OAAc;AAC9C,MAAI,CAAC,YAAY;AACf,iBAAa,IAAI,WAAW;AAAA,EAC9B;AAEA,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,cAAcF,QAAO,KAAK;AAChC,QAAM,CAAC,SAAS,QAAQ,IAAI,SAAS,WAAW,OAAO;AAEvD,EAAAE,WAAU,MAAM;AACd,QAAI,CAAC,YAAY,SAAS;AACxB,iBAAW,QAAQ,MAAM;AACvB,iBAAS,IAAI;AAAA,MACf,CAAC;AAED,kBAAY,UAAU;AAAA,IACxB;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,SAAO,oBAAC,kBAAgB,GAAG,OAAO;AACpC;","names":["useEffect","useRef","convert","previousState","useRef","convert","useEffect"]}
package/dist/provider.js CHANGED
@@ -1,3 +1,4 @@
1
+ "use client";
1
2
  "use strict";
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -24,7 +25,7 @@ __export(provider_exports, {
24
25
  });
25
26
  module.exports = __toCommonJS(provider_exports);
26
27
 
27
- // src/helpers.ts
28
+ // src/modules/helpers.ts
28
29
  function canUseDOM() {
29
30
  return !!(typeof window !== "undefined" && window.document && window.document.createElement);
30
31
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/provider.tsx","../src/helpers.ts"],"sourcesContent":["import { JSX } from 'react';\n\nimport { canUseDOM } from './helpers';\n\ninterface Props {\n children: JSX.Element;\n name?: string;\n}\n\nexport default function CacheProvider({ children, name }: Props) {\n if (canUseDOM()) {\n window.REACT_INLINESVG_CACHE_NAME = name;\n window.REACT_INLINESVG_PERSISTENT_CACHE = true;\n }\n\n return children;\n}\n","import type { PlainObject } from './types';\n\nexport function canUseDOM(): boolean {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\n\nexport async function request(url: string, options?: RequestInit) {\n const response = await fetch(url, options);\n const contentType = response.headers.get('content-type');\n const [fileType] = (contentType ?? '').split(/ ?; ?/);\n\n if (response.status > 299) {\n throw new Error('Not found');\n }\n\n if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {\n throw new Error(`Content type isn't valid: ${fileType}`);\n }\n\n return response.text();\n}\n\nexport function sleep(seconds = 1) {\n return new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n}\n\nexport function supportsInlineSVG(): boolean {\n /* c8 ignore next 3 */\n if (!document) {\n return false;\n }\n\n const div = document.createElement('div');\n\n div.innerHTML = '<svg />';\n const svg = div.firstChild as SVGSVGElement;\n\n return !!svg && svg.namespaceURI === 'http://www.w3.org/2000/svg';\n}\n\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function randomString(length: number): string {\n const letters = 'abcdefghijklmnopqrstuvwxyz';\n const numbers = '1234567890';\n const charset = `${letters}${letters.toUpperCase()}${numbers}`;\n\n let R = '';\n\n for (let index = 0; index < length; index++) {\n R += randomCharacter(charset);\n }\n\n return R;\n}\n\n/**\n * Remove properties from an object\n */\nexport function omit<T extends PlainObject, K extends keyof T>(\n input: T,\n ...filter: K[]\n): Omit<T, K> {\n const output: any = {};\n\n for (const key in input) {\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n }\n\n return output as Omit<T, K>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,SAAS,YAAqB;AACnC,SAAO,CAAC,EAAE,OAAO,WAAW,eAAe,OAAO,YAAY,OAAO,SAAS;AAChF;;;ADKe,SAAR,cAA+B,EAAE,UAAU,KAAK,GAAU;AAC/D,MAAI,UAAU,GAAG;AACf,WAAO,6BAA6B;AACpC,WAAO,mCAAmC;AAAA,EAC5C;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/provider.tsx","../src/modules/helpers.ts"],"sourcesContent":["import { JSX } from 'react';\n\nimport { canUseDOM } from './modules/helpers';\n\ninterface Props {\n children: JSX.Element;\n name?: string;\n}\n\nexport default function CacheProvider({ children, name }: Props) {\n if (canUseDOM()) {\n window.REACT_INLINESVG_CACHE_NAME = name;\n window.REACT_INLINESVG_PERSISTENT_CACHE = true;\n }\n\n return children;\n}\n","import type { PlainObject } from '../types';\n\nexport function canUseDOM(): boolean {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\n\nexport async function request(url: string, options?: RequestInit) {\n const response = await fetch(url, options);\n const contentType = response.headers.get('content-type');\n const [fileType] = (contentType ?? '').split(/ ?; ?/);\n\n if (response.status > 299) {\n throw new Error('Not found');\n }\n\n if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {\n throw new Error(`Content type isn't valid: ${fileType}`);\n }\n\n return response.text();\n}\n\nexport function sleep(seconds = 1) {\n return new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n}\n\nexport function supportsInlineSVG(): boolean {\n /* c8 ignore next 3 */\n if (!document) {\n return false;\n }\n\n const div = document.createElement('div');\n\n div.innerHTML = '<svg />';\n const svg = div.firstChild as SVGSVGElement;\n\n return !!svg && svg.namespaceURI === 'http://www.w3.org/2000/svg';\n}\n\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function randomString(length: number): string {\n const letters = 'abcdefghijklmnopqrstuvwxyz';\n const numbers = '1234567890';\n const charset = `${letters}${letters.toUpperCase()}${numbers}`;\n\n let R = '';\n\n for (let index = 0; index < length; index++) {\n R += randomCharacter(charset);\n }\n\n return R;\n}\n\n/**\n * Remove properties from an object\n */\nexport function omit<T extends PlainObject, K extends keyof T>(\n input: T,\n ...filter: K[]\n): Omit<T, K> {\n const output: any = {};\n\n for (const key in input) {\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n }\n\n return output as Omit<T, K>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,SAAS,YAAqB;AACnC,SAAO,CAAC,EAAE,OAAO,WAAW,eAAe,OAAO,YAAY,OAAO,SAAS;AAChF;;;ADKe,SAAR,cAA+B,EAAE,UAAU,KAAK,GAAU;AAC/D,MAAI,UAAU,GAAG;AACf,WAAO,6BAA6B;AACpC,WAAO,mCAAmC;AAAA,EAC5C;AAEA,SAAO;AACT;","names":[]}
package/dist/provider.mjs CHANGED
@@ -1,4 +1,6 @@
1
- // src/helpers.ts
1
+ "use client";
2
+
3
+ // src/modules/helpers.ts
2
4
  function canUseDOM() {
3
5
  return !!(typeof window !== "undefined" && window.document && window.document.createElement);
4
6
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/helpers.ts","../src/provider.tsx"],"sourcesContent":["import type { PlainObject } from './types';\n\nexport function canUseDOM(): boolean {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\n\nexport async function request(url: string, options?: RequestInit) {\n const response = await fetch(url, options);\n const contentType = response.headers.get('content-type');\n const [fileType] = (contentType ?? '').split(/ ?; ?/);\n\n if (response.status > 299) {\n throw new Error('Not found');\n }\n\n if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {\n throw new Error(`Content type isn't valid: ${fileType}`);\n }\n\n return response.text();\n}\n\nexport function sleep(seconds = 1) {\n return new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n}\n\nexport function supportsInlineSVG(): boolean {\n /* c8 ignore next 3 */\n if (!document) {\n return false;\n }\n\n const div = document.createElement('div');\n\n div.innerHTML = '<svg />';\n const svg = div.firstChild as SVGSVGElement;\n\n return !!svg && svg.namespaceURI === 'http://www.w3.org/2000/svg';\n}\n\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function randomString(length: number): string {\n const letters = 'abcdefghijklmnopqrstuvwxyz';\n const numbers = '1234567890';\n const charset = `${letters}${letters.toUpperCase()}${numbers}`;\n\n let R = '';\n\n for (let index = 0; index < length; index++) {\n R += randomCharacter(charset);\n }\n\n return R;\n}\n\n/**\n * Remove properties from an object\n */\nexport function omit<T extends PlainObject, K extends keyof T>(\n input: T,\n ...filter: K[]\n): Omit<T, K> {\n const output: any = {};\n\n for (const key in input) {\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n }\n\n return output as Omit<T, K>;\n}\n","import { JSX } from 'react';\n\nimport { canUseDOM } from './helpers';\n\ninterface Props {\n children: JSX.Element;\n name?: string;\n}\n\nexport default function CacheProvider({ children, name }: Props) {\n if (canUseDOM()) {\n window.REACT_INLINESVG_CACHE_NAME = name;\n window.REACT_INLINESVG_PERSISTENT_CACHE = true;\n }\n\n return children;\n}\n"],"mappings":";AAEO,SAAS,YAAqB;AACnC,SAAO,CAAC,EAAE,OAAO,WAAW,eAAe,OAAO,YAAY,OAAO,SAAS;AAChF;;;ACKe,SAAR,cAA+B,EAAE,UAAU,KAAK,GAAU;AAC/D,MAAI,UAAU,GAAG;AACf,WAAO,6BAA6B;AACpC,WAAO,mCAAmC;AAAA,EAC5C;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/modules/helpers.ts","../src/provider.tsx"],"sourcesContent":["import type { PlainObject } from '../types';\n\nexport function canUseDOM(): boolean {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\n\nexport async function request(url: string, options?: RequestInit) {\n const response = await fetch(url, options);\n const contentType = response.headers.get('content-type');\n const [fileType] = (contentType ?? '').split(/ ?; ?/);\n\n if (response.status > 299) {\n throw new Error('Not found');\n }\n\n if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {\n throw new Error(`Content type isn't valid: ${fileType}`);\n }\n\n return response.text();\n}\n\nexport function sleep(seconds = 1) {\n return new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n}\n\nexport function supportsInlineSVG(): boolean {\n /* c8 ignore next 3 */\n if (!document) {\n return false;\n }\n\n const div = document.createElement('div');\n\n div.innerHTML = '<svg />';\n const svg = div.firstChild as SVGSVGElement;\n\n return !!svg && svg.namespaceURI === 'http://www.w3.org/2000/svg';\n}\n\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function randomString(length: number): string {\n const letters = 'abcdefghijklmnopqrstuvwxyz';\n const numbers = '1234567890';\n const charset = `${letters}${letters.toUpperCase()}${numbers}`;\n\n let R = '';\n\n for (let index = 0; index < length; index++) {\n R += randomCharacter(charset);\n }\n\n return R;\n}\n\n/**\n * Remove properties from an object\n */\nexport function omit<T extends PlainObject, K extends keyof T>(\n input: T,\n ...filter: K[]\n): Omit<T, K> {\n const output: any = {};\n\n for (const key in input) {\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n }\n\n return output as Omit<T, K>;\n}\n","import { JSX } from 'react';\n\nimport { canUseDOM } from './modules/helpers';\n\ninterface Props {\n children: JSX.Element;\n name?: string;\n}\n\nexport default function CacheProvider({ children, name }: Props) {\n if (canUseDOM()) {\n window.REACT_INLINESVG_CACHE_NAME = name;\n window.REACT_INLINESVG_PERSISTENT_CACHE = true;\n }\n\n return children;\n}\n"],"mappings":";;;AAEO,SAAS,YAAqB;AACnC,SAAO,CAAC,EAAE,OAAO,WAAW,eAAe,OAAO,YAAY,OAAO,SAAS;AAChF;;;ACKe,SAAR,cAA+B,EAAE,UAAU,KAAK,GAAU;AAC/D,MAAI,UAAU,GAAG;AACf,WAAO,6BAA6B;AACpC,WAAO,mCAAmC;AAAA,EAC5C;AAEA,SAAO;AACT;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-inlinesvg",
3
- "version": "4.1.0-0",
3
+ "version": "4.1.1",
4
4
  "description": "An SVG loader for React",
5
5
  "author": "Gil Barbara <gilbarbara@gmail.com>",
6
6
  "contributors": [
@@ -54,40 +54,40 @@
54
54
  "react-from-dom": "^0.6.2"
55
55
  },
56
56
  "devDependencies": {
57
- "@gilbarbara/eslint-config": "^0.5.4",
57
+ "@gilbarbara/eslint-config": "^0.7.3",
58
58
  "@gilbarbara/prettier-config": "^1.0.0",
59
59
  "@gilbarbara/tsconfig": "^0.2.3",
60
- "@size-limit/preset-small-lib": "^10.0.1",
61
- "@testing-library/jest-dom": "^6.1.4",
62
- "@testing-library/react": "^14.0.0",
63
- "@types/node": "^20.8.8",
64
- "@types/react": "^18.2.31",
65
- "@types/react-dom": "^18.2.14",
66
- "@vitejs/plugin-react": "^4.1.0",
67
- "@vitest/coverage-v8": "^0.34.6",
60
+ "@size-limit/preset-small-lib": "^11.0.2",
61
+ "@testing-library/jest-dom": "^6.2.1",
62
+ "@testing-library/react": "^14.1.2",
63
+ "@types/node": "^20.11.5",
64
+ "@types/react": "^18.2.48",
65
+ "@types/react-dom": "^18.2.18",
66
+ "@vitejs/plugin-react": "^4.2.1",
67
+ "@vitest/coverage-v8": "^1.2.1",
68
68
  "browser-cache-mock": "^0.1.7",
69
69
  "del-cli": "^5.1.0",
70
70
  "fix-tsup-cjs": "^1.2.0",
71
71
  "http-server": "^14.1.1",
72
72
  "husky": "^8.0.3",
73
73
  "jest-extended": "^4.0.2",
74
- "jsdom": "^22.1.0",
74
+ "jsdom": "^24.0.0",
75
75
  "react": "^18.2.0",
76
76
  "react-dom": "^18.2.0",
77
77
  "repo-tools": "^0.3.1",
78
- "size-limit": "^10.0.1",
79
- "start-server-and-test": "^2.0.1",
80
- "ts-node": "^10.9.1",
81
- "tsup": "^7.2.0",
82
- "typescript": "^5.2.2",
83
- "vitest": "^0.34.6",
78
+ "size-limit": "^11.0.2",
79
+ "start-server-and-test": "^2.0.3",
80
+ "ts-node": "^10.9.2",
81
+ "tsup": "^8.0.1",
82
+ "typescript": "^5.3.3",
83
+ "vitest": "^1.2.1",
84
84
  "vitest-fetch-mock": "^0.2.2"
85
85
  },
86
86
  "scripts": {
87
87
  "build": "pnpm run clean && tsup && fix-tsup-cjs",
88
88
  "watch": "tsup --watch",
89
89
  "clean": "del dist/*",
90
- "lint": "eslint src test",
90
+ "lint": "eslint --fix src test",
91
91
  "start": "http-server test/__fixtures__ -p 1337 --cors",
92
92
  "test": "start-server-and-test start http://127.0.0.1:1337 test:coverage",
93
93
  "test:coverage": "vitest run --coverage",
@@ -100,6 +100,9 @@
100
100
  "prepare": "husky install"
101
101
  },
102
102
  "tsup": {
103
+ "banner": {
104
+ "js": "\"use client\";"
105
+ },
103
106
  "dts": true,
104
107
  "entry": [
105
108
  "src/index.tsx",
package/src/index.tsx CHANGED
@@ -10,134 +10,16 @@ import {
10
10
  } from 'react';
11
11
  import convert from 'react-from-dom';
12
12
 
13
- import CacheStore from './cache';
14
13
  import { STATUS } from './config';
15
- import { canUseDOM, isSupportedEnvironment, omit, randomString, request } from './helpers';
16
- import { usePrevious } from './hooks';
14
+ import CacheStore from './modules/cache';
15
+ import { canUseDOM, isSupportedEnvironment, omit, randomString, request } from './modules/helpers';
16
+ import { usePrevious } from './modules/hooks';
17
+ import { getNode } from './modules/utils';
17
18
  import { FetchError, Props, State, Status } from './types';
18
19
 
19
20
  // eslint-disable-next-line import/no-mutable-exports
20
21
  export let cacheStore: CacheStore;
21
22
 
22
- interface GetNodeOptions extends Props, Pick<State, 'content'> {
23
- handleError: (error: Error) => void;
24
- hash: string;
25
- }
26
-
27
- interface UpdateSVGAttributesOptions extends Pick<Props, 'baseURL' | 'uniquifyIDs'> {
28
- hash: string;
29
- }
30
-
31
- function updateSVGAttributes(
32
- node: SVGSVGElement,
33
- options: UpdateSVGAttributesOptions,
34
- ): SVGSVGElement {
35
- const { baseURL = '', hash, uniquifyIDs } = options;
36
- const replaceableAttributes = ['id', 'href', 'xlink:href', 'xlink:role', 'xlink:arcrole'];
37
- const linkAttributes = ['href', 'xlink:href'];
38
- const isDataValue = (name: string, value: string) =>
39
- linkAttributes.includes(name) && (value ? !value.includes('#') : false);
40
-
41
- if (!uniquifyIDs) {
42
- return node;
43
- }
44
-
45
- [...node.children].forEach(d => {
46
- if (d.attributes?.length) {
47
- const attributes = Object.values(d.attributes).map(a => {
48
- const attribute = a;
49
- const match = /url\((.*?)\)/.exec(a.value);
50
-
51
- if (match?.[1]) {
52
- attribute.value = a.value.replace(match[0], `url(${baseURL}${match[1]}__${hash})`);
53
- }
54
-
55
- return attribute;
56
- });
57
-
58
- replaceableAttributes.forEach(r => {
59
- const attribute = attributes.find(a => a.name === r);
60
-
61
- if (attribute && !isDataValue(r, attribute.value)) {
62
- attribute.value = `${attribute.value}__${hash}`;
63
- }
64
- });
65
- }
66
-
67
- if (d.children.length) {
68
- return updateSVGAttributes(d as SVGSVGElement, options);
69
- }
70
-
71
- return d;
72
- });
73
-
74
- return node;
75
- }
76
-
77
- function getNode(options: GetNodeOptions) {
78
- const {
79
- baseURL,
80
- content,
81
- description,
82
- handleError,
83
- hash,
84
- preProcessor,
85
- title,
86
- uniquifyIDs = false,
87
- } = options;
88
-
89
- try {
90
- const svgText = processSVG(content, preProcessor);
91
- const node = convert(svgText, { nodeOnly: true });
92
-
93
- if (!node || !(node instanceof SVGSVGElement)) {
94
- throw new Error('Could not convert the src to a DOM Node');
95
- }
96
-
97
- const svg = updateSVGAttributes(node, { baseURL, hash, uniquifyIDs });
98
-
99
- if (description) {
100
- const originalDesc = svg.querySelector('desc');
101
-
102
- if (originalDesc?.parentNode) {
103
- originalDesc.parentNode.removeChild(originalDesc);
104
- }
105
-
106
- const descElement = document.createElementNS('http://www.w3.org/2000/svg', 'desc');
107
-
108
- descElement.innerHTML = description;
109
- svg.prepend(descElement);
110
- }
111
-
112
- if (typeof title !== 'undefined') {
113
- const originalTitle = svg.querySelector('title');
114
-
115
- if (originalTitle?.parentNode) {
116
- originalTitle.parentNode.removeChild(originalTitle);
117
- }
118
-
119
- if (title) {
120
- const titleElement = document.createElementNS('http://www.w3.org/2000/svg', 'title');
121
-
122
- titleElement.innerHTML = title;
123
- svg.prepend(titleElement);
124
- }
125
- }
126
-
127
- return svg;
128
- } catch (error: any) {
129
- return handleError(error);
130
- }
131
- }
132
-
133
- function processSVG(content: string, preProcessor?: Props['preProcessor']) {
134
- if (preProcessor) {
135
- return preProcessor(content);
136
- }
137
-
138
- return content;
139
- }
140
-
141
23
  function ReactInlineSVG(props: Props) {
142
24
  const {
143
25
  cacheRequests = true,
@@ -197,6 +79,12 @@ function ReactInlineSVG(props: Props) {
197
79
  }
198
80
  }, []);
199
81
 
82
+ const fetchContent = useCallback(async () => {
83
+ const responseContent: string = await request(src, fetchOptions);
84
+
85
+ handleLoad(responseContent);
86
+ }, [fetchOptions, handleLoad, src]);
87
+
200
88
  const getElement = useCallback(() => {
201
89
  try {
202
90
  const node = getNode({ ...props, handleError, hash: hash.current, content }) as Node;
@@ -215,12 +103,6 @@ function ReactInlineSVG(props: Props) {
215
103
  }
216
104
  }, [content, handleError, props]);
217
105
 
218
- const fetchContent = useCallback(async () => {
219
- const responseContent: string = await request(src, fetchOptions);
220
-
221
- handleLoad(responseContent);
222
- }, [fetchOptions, handleLoad, src]);
223
-
224
106
  const getContent = useCallback(async () => {
225
107
  const dataURI = /^data:image\/svg[^,]*?(;base64)?,(.*)/u.exec(src);
226
108
  let inlineSrc;
@@ -317,19 +199,7 @@ function ReactInlineSVG(props: Props) {
317
199
  } else if (previousProps.title !== title || previousProps.description !== description) {
318
200
  getElement();
319
201
  }
320
- }, [
321
- description,
322
- getElement,
323
- handleError,
324
- isCached,
325
- load,
326
- onLoad,
327
- previousProps,
328
- previousState,
329
- src,
330
- status,
331
- title,
332
- ]);
202
+ }, [description, getElement, handleError, load, previousProps, src, title]);
333
203
 
334
204
  // handle state
335
205
  useEffect(() => {
@@ -1,6 +1,7 @@
1
- import { CACHE_MAX_RETRIES, CACHE_NAME, STATUS } from './config';
2
1
  import { canUseDOM, request, sleep } from './helpers';
3
- import { StorageItem } from './types';
2
+
3
+ import { CACHE_MAX_RETRIES, CACHE_NAME, STATUS } from '../config';
4
+ import { StorageItem } from '../types';
4
5
 
5
6
  export default class CacheStore {
6
7
  private cacheApi: Cache | undefined;
@@ -133,7 +134,6 @@ export default class CacheStore {
133
134
  private async handleLoading(url: string, callback: () => Promise<void>) {
134
135
  let retryCount = 0;
135
136
 
136
- // eslint-disable-next-line no-await-in-loop
137
137
  while (this.cacheStore.get(url)?.status === STATUS.LOADING && retryCount < CACHE_MAX_RETRIES) {
138
138
  // eslint-disable-next-line no-await-in-loop
139
139
  await sleep(0.1);
@@ -1,4 +1,4 @@
1
- import type { PlainObject } from './types';
1
+ import type { PlainObject } from '../types';
2
2
 
3
3
  export function canUseDOM(): boolean {
4
4
  return !!(typeof window !== 'undefined' && window.document && window.document.createElement);
@@ -0,0 +1,122 @@
1
+ import convert from 'react-from-dom';
2
+
3
+ import { Props, State } from '../types';
4
+
5
+ interface GetNodeOptions extends Props, Pick<State, 'content'> {
6
+ handleError: (error: Error) => void;
7
+ hash: string;
8
+ }
9
+
10
+ interface UpdateSVGAttributesOptions extends Pick<Props, 'baseURL' | 'uniquifyIDs'> {
11
+ hash: string;
12
+ }
13
+
14
+ export function getNode(options: GetNodeOptions) {
15
+ const {
16
+ baseURL,
17
+ content,
18
+ description,
19
+ handleError,
20
+ hash,
21
+ preProcessor,
22
+ title,
23
+ uniquifyIDs = false,
24
+ } = options;
25
+
26
+ try {
27
+ const svgText = processSVG(content, preProcessor);
28
+ const node = convert(svgText, { nodeOnly: true });
29
+
30
+ if (!node || !(node instanceof SVGSVGElement)) {
31
+ throw new Error('Could not convert the src to a DOM Node');
32
+ }
33
+
34
+ const svg = updateSVGAttributes(node, { baseURL, hash, uniquifyIDs });
35
+
36
+ if (description) {
37
+ const originalDesc = svg.querySelector('desc');
38
+
39
+ if (originalDesc?.parentNode) {
40
+ originalDesc.parentNode.removeChild(originalDesc);
41
+ }
42
+
43
+ const descElement = document.createElementNS('http://www.w3.org/2000/svg', 'desc');
44
+
45
+ descElement.innerHTML = description;
46
+ svg.prepend(descElement);
47
+ }
48
+
49
+ if (typeof title !== 'undefined') {
50
+ const originalTitle = svg.querySelector('title');
51
+
52
+ if (originalTitle?.parentNode) {
53
+ originalTitle.parentNode.removeChild(originalTitle);
54
+ }
55
+
56
+ if (title) {
57
+ const titleElement = document.createElementNS('http://www.w3.org/2000/svg', 'title');
58
+
59
+ titleElement.innerHTML = title;
60
+ svg.prepend(titleElement);
61
+ }
62
+ }
63
+
64
+ return svg;
65
+ } catch (error: any) {
66
+ return handleError(error);
67
+ }
68
+ }
69
+
70
+ export function processSVG(content: string, preProcessor?: Props['preProcessor']) {
71
+ if (preProcessor) {
72
+ return preProcessor(content);
73
+ }
74
+
75
+ return content;
76
+ }
77
+
78
+ export function updateSVGAttributes(
79
+ node: SVGSVGElement,
80
+ options: UpdateSVGAttributesOptions,
81
+ ): SVGSVGElement {
82
+ const { baseURL = '', hash, uniquifyIDs } = options;
83
+ const replaceableAttributes = ['id', 'href', 'xlink:href', 'xlink:role', 'xlink:arcrole'];
84
+ const linkAttributes = ['href', 'xlink:href'];
85
+ const isDataValue = (name: string, value: string) =>
86
+ linkAttributes.includes(name) && (value ? !value.includes('#') : false);
87
+
88
+ if (!uniquifyIDs) {
89
+ return node;
90
+ }
91
+
92
+ [...node.children].forEach(d => {
93
+ if (d.attributes?.length) {
94
+ const attributes = Object.values(d.attributes).map(a => {
95
+ const attribute = a;
96
+ const match = /url\((.*?)\)/.exec(a.value);
97
+
98
+ if (match?.[1]) {
99
+ attribute.value = a.value.replace(match[0], `url(${baseURL}${match[1]}__${hash})`);
100
+ }
101
+
102
+ return attribute;
103
+ });
104
+
105
+ replaceableAttributes.forEach(r => {
106
+ const attribute = attributes.find(a => a.name === r);
107
+
108
+ if (attribute && !isDataValue(r, attribute.value)) {
109
+ attribute.value = `${attribute.value}__${hash}`;
110
+ }
111
+ });
112
+ }
113
+
114
+ if (d.children.length) {
115
+ return updateSVGAttributes(d as SVGSVGElement, options);
116
+ }
117
+
118
+ return d;
119
+ });
120
+
121
+ return node;
122
+ }
package/src/provider.tsx CHANGED
@@ -1,6 +1,6 @@
1
1
  import { JSX } from 'react';
2
2
 
3
- import { canUseDOM } from './helpers';
3
+ import { canUseDOM } from './modules/helpers';
4
4
 
5
5
  interface Props {
6
6
  children: JSX.Element;
File without changes