react-inlinesvg 4.1.4 → 4.1.6

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
@@ -1,5 +1,4 @@
1
- import * as React from 'react';
2
- import React__default from 'react';
1
+ import React, { SVGProps, ReactNode, RefObject } from 'react';
3
2
 
4
3
  declare const STATUS: {
5
4
  readonly IDLE: "idle";
@@ -14,14 +13,14 @@ type ErrorCallback = (error: Error | FetchError) => void;
14
13
  type LoadCallback = (src: string, isCached: boolean) => void;
15
14
  type PlainObject<T = unknown> = Record<string, T>;
16
15
  type PreProcessorCallback = (code: string) => string;
17
- type Props = Simplify<Omit<React.SVGProps<SVGElement>, 'onLoad' | 'onError' | 'ref'> & {
16
+ type Props = Simplify<Omit<SVGProps<SVGElement>, 'onLoad' | 'onError' | 'ref'> & {
18
17
  baseURL?: string;
19
18
  cacheRequests?: boolean;
20
- children?: React.ReactNode;
19
+ children?: ReactNode;
21
20
  description?: string;
22
21
  fetchOptions?: RequestInit;
23
- innerRef?: React.Ref<SVGElement>;
24
- loader?: React.ReactNode;
22
+ innerRef?: RefObject<SVGElement | null>;
23
+ loader?: ReactNode;
25
24
  onError?: ErrorCallback;
26
25
  onLoad?: LoadCallback;
27
26
  preProcessor?: PreProcessorCallback;
@@ -30,22 +29,22 @@ type Props = Simplify<Omit<React.SVGProps<SVGElement>, 'onLoad' | 'onError' | 'r
30
29
  uniqueHash?: string;
31
30
  uniquifyIDs?: boolean;
32
31
  }>;
33
- interface State {
34
- content: string;
35
- element: React.ReactNode;
36
- isCached: boolean;
37
- status: Status;
38
- }
32
+ type Simplify<T> = {
33
+ [KeyType in keyof T]: T[KeyType];
34
+ } & {};
35
+ type Status = (typeof STATUS)[keyof typeof STATUS];
39
36
  interface FetchError extends Error {
40
37
  code: string;
41
38
  errno: string;
42
39
  message: string;
43
40
  type: string;
44
41
  }
45
- type Simplify<T> = {
46
- [KeyType in keyof T]: T[KeyType];
47
- } & {};
48
- type Status = (typeof STATUS)[keyof typeof STATUS];
42
+ interface State {
43
+ content: string;
44
+ element: ReactNode;
45
+ isCached: boolean;
46
+ status: Status;
47
+ }
49
48
  interface StorageItem {
50
49
  content: string;
51
50
  status: Status;
@@ -71,6 +70,6 @@ declare class CacheStore {
71
70
  }
72
71
 
73
72
  declare let cacheStore: CacheStore;
74
- declare function InlineSVG(props: Props): string | number | boolean | Iterable<React__default.ReactNode> | React__default.JSX.Element | null | undefined;
73
+ declare function InlineSVG(props: Props): string | number | bigint | boolean | Iterable<React.ReactNode> | Promise<string | number | bigint | boolean | React.ReactPortal | React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | null | undefined> | React.JSX.Element | null | undefined;
75
74
 
76
75
  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
@@ -1,5 +1,4 @@
1
- import * as React from 'react';
2
- import React__default from 'react';
1
+ import React, { SVGProps, ReactNode, RefObject } from 'react';
3
2
 
4
3
  declare const STATUS: {
5
4
  readonly IDLE: "idle";
@@ -14,14 +13,14 @@ type ErrorCallback = (error: Error | FetchError) => void;
14
13
  type LoadCallback = (src: string, isCached: boolean) => void;
15
14
  type PlainObject<T = unknown> = Record<string, T>;
16
15
  type PreProcessorCallback = (code: string) => string;
17
- type Props = Simplify<Omit<React.SVGProps<SVGElement>, 'onLoad' | 'onError' | 'ref'> & {
16
+ type Props = Simplify<Omit<SVGProps<SVGElement>, 'onLoad' | 'onError' | 'ref'> & {
18
17
  baseURL?: string;
19
18
  cacheRequests?: boolean;
20
- children?: React.ReactNode;
19
+ children?: ReactNode;
21
20
  description?: string;
22
21
  fetchOptions?: RequestInit;
23
- innerRef?: React.Ref<SVGElement>;
24
- loader?: React.ReactNode;
22
+ innerRef?: RefObject<SVGElement | null>;
23
+ loader?: ReactNode;
25
24
  onError?: ErrorCallback;
26
25
  onLoad?: LoadCallback;
27
26
  preProcessor?: PreProcessorCallback;
@@ -30,22 +29,22 @@ type Props = Simplify<Omit<React.SVGProps<SVGElement>, 'onLoad' | 'onError' | 'r
30
29
  uniqueHash?: string;
31
30
  uniquifyIDs?: boolean;
32
31
  }>;
33
- interface State {
34
- content: string;
35
- element: React.ReactNode;
36
- isCached: boolean;
37
- status: Status;
38
- }
32
+ type Simplify<T> = {
33
+ [KeyType in keyof T]: T[KeyType];
34
+ } & {};
35
+ type Status = (typeof STATUS)[keyof typeof STATUS];
39
36
  interface FetchError extends Error {
40
37
  code: string;
41
38
  errno: string;
42
39
  message: string;
43
40
  type: string;
44
41
  }
45
- type Simplify<T> = {
46
- [KeyType in keyof T]: T[KeyType];
47
- } & {};
48
- type Status = (typeof STATUS)[keyof typeof STATUS];
42
+ interface State {
43
+ content: string;
44
+ element: ReactNode;
45
+ isCached: boolean;
46
+ status: Status;
47
+ }
49
48
  interface StorageItem {
50
49
  content: string;
51
50
  status: Status;
@@ -71,7 +70,7 @@ declare class CacheStore {
71
70
  }
72
71
 
73
72
  declare let cacheStore: CacheStore;
74
- declare function InlineSVG(props: Props): string | number | boolean | Iterable<React__default.ReactNode> | React__default.JSX.Element | null | undefined;
73
+ declare function InlineSVG(props: Props): string | number | bigint | boolean | Iterable<React.ReactNode> | Promise<string | number | bigint | boolean | React.ReactPortal | React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | null | undefined> | React.JSX.Element | null | undefined;
75
74
 
76
75
  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
76
  export = InlineSVG
package/dist/index.js CHANGED
@@ -53,12 +53,36 @@ var STATUS = {
53
53
  };
54
54
 
55
55
  // src/modules/helpers.ts
56
+ function randomCharacter(character) {
57
+ return character[Math.floor(Math.random() * character.length)];
58
+ }
56
59
  function canUseDOM() {
57
- return !!(typeof window !== "undefined" && window.document && window.document.createElement);
60
+ return !!window?.document?.createElement;
58
61
  }
59
62
  function isSupportedEnvironment() {
60
63
  return supportsInlineSVG() && typeof window !== "undefined" && window !== null;
61
64
  }
65
+ function omit(input, ...filter) {
66
+ const output = {};
67
+ for (const key in input) {
68
+ if ({}.hasOwnProperty.call(input, key)) {
69
+ if (!filter.includes(key)) {
70
+ output[key] = input[key];
71
+ }
72
+ }
73
+ }
74
+ return output;
75
+ }
76
+ function randomString(length) {
77
+ const letters = "abcdefghijklmnopqrstuvwxyz";
78
+ const numbers = "1234567890";
79
+ const charset = `${letters}${letters.toUpperCase()}${numbers}`;
80
+ let R = "";
81
+ for (let index = 0; index < length; index++) {
82
+ R += randomCharacter(charset);
83
+ }
84
+ return R;
85
+ }
62
86
  async function request(url, options) {
63
87
  const response = await fetch(url, options);
64
88
  const contentType = response.headers.get("content-type");
@@ -85,30 +109,6 @@ function supportsInlineSVG() {
85
109
  const svg = div.firstChild;
86
110
  return !!svg && svg.namespaceURI === "http://www.w3.org/2000/svg";
87
111
  }
88
- function randomCharacter(character) {
89
- return character[Math.floor(Math.random() * character.length)];
90
- }
91
- function randomString(length) {
92
- const letters = "abcdefghijklmnopqrstuvwxyz";
93
- const numbers = "1234567890";
94
- const charset = `${letters}${letters.toUpperCase()}${numbers}`;
95
- let R = "";
96
- for (let index = 0; index < length; index++) {
97
- R += randomCharacter(charset);
98
- }
99
- return R;
100
- }
101
- function omit(input, ...filter) {
102
- const output = {};
103
- for (const key in input) {
104
- if ({}.hasOwnProperty.call(input, key)) {
105
- if (!filter.includes(key)) {
106
- output[key] = input[key];
107
- }
108
- }
109
- }
110
- return output;
111
- }
112
112
 
113
113
  // src/modules/cache.ts
114
114
  var CacheStore = class {
@@ -127,11 +127,11 @@ var CacheStore = class {
127
127
  if (usePersistentCache) {
128
128
  caches.open(cacheName).then((cache) => {
129
129
  this.cacheApi = cache;
130
- this.isReady = true;
131
- this.subscribers.forEach((callback) => callback());
132
130
  }).catch((error) => {
133
- this.isReady = true;
134
131
  console.error(`Failed to open cache: ${error.message}`);
132
+ }).finally(() => {
133
+ this.isReady = true;
134
+ this.subscribers.forEach((callback) => callback());
135
135
  });
136
136
  } else {
137
137
  this.isReady = true;
@@ -239,7 +239,7 @@ var CacheStore = class {
239
239
  // src/modules/hooks.tsx
240
240
  var import_react = require("react");
241
241
  function usePrevious(state) {
242
- const ref = (0, import_react.useRef)();
242
+ const ref = (0, import_react.useRef)(void 0);
243
243
  (0, import_react.useEffect)(() => {
244
244
  ref.current = state;
245
245
  });
@@ -515,7 +515,10 @@ function ReactInlineSVG(props) {
515
515
  return loader;
516
516
  }
517
517
  if (element) {
518
- return (0, import_react2.cloneElement)(element, { ref: innerRef, ...elementProps });
518
+ return (0, import_react2.cloneElement)(element, {
519
+ ref: innerRef,
520
+ ...elementProps
521
+ });
519
522
  }
520
523
  if ([STATUS.UNSUPPORTED, STATUS.FAILED].includes(status)) {
521
524
  return children;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
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 React, {\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,IAAAA,gBASO;AACP,IAAAC,yBAAoB;;;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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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,8BAAAC,QAAA,cAAC,kBAAgB,GAAG,OAAO;AACpC;","names":["import_react","import_react_from_dom","convert","previousState","convert","React"]}
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 React, {\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<any>, {\n ref: innerRef,\n ...elementProps,\n });\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\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function canUseDOM(): boolean {\n return !!window?.document?.createElement;\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\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\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\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","import { CACHE_MAX_RETRIES, CACHE_NAME, STATUS } from '../config';\nimport { StorageItem } from '../types';\n\nimport { canUseDOM, request, sleep } from './helpers';\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 })\n .catch(error => {\n // eslint-disable-next-line no-console\n console.error(`Failed to open cache: ${error.message}`);\n })\n .finally(() => {\n this.isReady = true;\n this.subscribers.forEach(callback => callback());\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>(undefined);\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,IAAAA,gBASO;AACP,IAAAC,yBAAoB;;;ACVb,IAAM,aAAa;AACnB,IAAM,oBAAoB;AAE1B,IAAM,SAAS;AAAA,EACpB,MAAM;AAAA,E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ACb;AAEA,QAAI,cAAc,WAAW,OAAO,UAAU,WAAW,OAAO,QAAQ;AACtE,iBAAW;AAAA,IACb;AAEA,QAAI,cAAc,WAAW,OAAO,SAAS,WAAW,OAAO,OAAO;AACpE,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,SAA8B;AAAA,MAChD,KAAK;AAAA,MACL,GAAG;AAAA,IACL,CAAC;AAAA,EACH;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,8BAAAC,QAAA,cAAC,kBAAgB,GAAG,OAAO;AACpC;","names":["import_react","import_react_from_dom","convert","previousState","convert","React"]}
package/dist/index.mjs CHANGED
@@ -28,12 +28,36 @@ var STATUS = {
28
28
  };
29
29
 
30
30
  // src/modules/helpers.ts
31
+ function randomCharacter(character) {
32
+ return character[Math.floor(Math.random() * character.length)];
33
+ }
31
34
  function canUseDOM() {
32
- return !!(typeof window !== "undefined" && window.document && window.document.createElement);
35
+ return !!window?.document?.createElement;
33
36
  }
34
37
  function isSupportedEnvironment() {
35
38
  return supportsInlineSVG() && typeof window !== "undefined" && window !== null;
36
39
  }
40
+ function omit(input, ...filter) {
41
+ const output = {};
42
+ for (const key in input) {
43
+ if ({}.hasOwnProperty.call(input, key)) {
44
+ if (!filter.includes(key)) {
45
+ output[key] = input[key];
46
+ }
47
+ }
48
+ }
49
+ return output;
50
+ }
51
+ function randomString(length) {
52
+ const letters = "abcdefghijklmnopqrstuvwxyz";
53
+ const numbers = "1234567890";
54
+ const charset = `${letters}${letters.toUpperCase()}${numbers}`;
55
+ let R = "";
56
+ for (let index = 0; index < length; index++) {
57
+ R += randomCharacter(charset);
58
+ }
59
+ return R;
60
+ }
37
61
  async function request(url, options) {
38
62
  const response = await fetch(url, options);
39
63
  const contentType = response.headers.get("content-type");
@@ -60,30 +84,6 @@ function supportsInlineSVG() {
60
84
  const svg = div.firstChild;
61
85
  return !!svg && svg.namespaceURI === "http://www.w3.org/2000/svg";
62
86
  }
63
- function randomCharacter(character) {
64
- return character[Math.floor(Math.random() * character.length)];
65
- }
66
- function randomString(length) {
67
- const letters = "abcdefghijklmnopqrstuvwxyz";
68
- const numbers = "1234567890";
69
- const charset = `${letters}${letters.toUpperCase()}${numbers}`;
70
- let R = "";
71
- for (let index = 0; index < length; index++) {
72
- R += randomCharacter(charset);
73
- }
74
- return R;
75
- }
76
- function omit(input, ...filter) {
77
- const output = {};
78
- for (const key in input) {
79
- if ({}.hasOwnProperty.call(input, key)) {
80
- if (!filter.includes(key)) {
81
- output[key] = input[key];
82
- }
83
- }
84
- }
85
- return output;
86
- }
87
87
 
88
88
  // src/modules/cache.ts
89
89
  var CacheStore = class {
@@ -102,11 +102,11 @@ var CacheStore = class {
102
102
  if (usePersistentCache) {
103
103
  caches.open(cacheName).then((cache) => {
104
104
  this.cacheApi = cache;
105
- this.isReady = true;
106
- this.subscribers.forEach((callback) => callback());
107
105
  }).catch((error) => {
108
- this.isReady = true;
109
106
  console.error(`Failed to open cache: ${error.message}`);
107
+ }).finally(() => {
108
+ this.isReady = true;
109
+ this.subscribers.forEach((callback) => callback());
110
110
  });
111
111
  } else {
112
112
  this.isReady = true;
@@ -214,7 +214,7 @@ var CacheStore = class {
214
214
  // src/modules/hooks.tsx
215
215
  import { useEffect, useRef } from "react";
216
216
  function usePrevious(state) {
217
- const ref = useRef();
217
+ const ref = useRef(void 0);
218
218
  useEffect(() => {
219
219
  ref.current = state;
220
220
  });
@@ -490,7 +490,10 @@ function ReactInlineSVG(props) {
490
490
  return loader;
491
491
  }
492
492
  if (element) {
493
- return cloneElement(element, { ref: innerRef, ...elementProps });
493
+ return cloneElement(element, {
494
+ ref: innerRef,
495
+ ...elementProps
496
+ });
494
497
  }
495
498
  if ([STATUS.UNSUPPORTED, STATUS.FAILED].includes(status)) {
496
499
  return children;
@@ -1 +1 @@
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 React, {\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,OAAO;AAAA,EACL;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,SA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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,WAAO,aAAa,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,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,oCAAC,kBAAgB,GAAG,OAAO;AACpC;","names":["useEffect","useRef","convert","previousState","useRef","convert","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 React, {\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<any>, {\n ref: innerRef,\n ...elementProps,\n });\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\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function canUseDOM(): boolean {\n return !!window?.document?.createElement;\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\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\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\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","import { CACHE_MAX_RETRIES, CACHE_NAME, STATUS } from '../config';\nimport { StorageItem } from '../types';\n\nimport { canUseDOM, request, sleep } from './helpers';\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 })\n .catch(error => {\n // eslint-disable-next-line no-console\n console.error(`Failed to open cache: ${error.message}`);\n })\n .finally(() => {\n this.isReady = true;\n this.subscribers.forEach(callback => callback());\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>(undefined);\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,OAAO;AAAA,EACL;AAAA,EACA;AAAA,EAEA;AAAA,EACA,aAAAA;AAAA,EACA;AAAA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AAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,SAAO,oCAAC,kBAAgB,GAAG,OAAO;AACpC;","names":["useEffect","useRef","convert","previousState","useRef","convert","useEffect"]}
package/dist/provider.js CHANGED
@@ -27,7 +27,7 @@ module.exports = __toCommonJS(provider_exports);
27
27
 
28
28
  // src/modules/helpers.ts
29
29
  function canUseDOM() {
30
- return !!(typeof window !== "undefined" && window.document && window.document.createElement);
30
+ return !!window?.document?.createElement;
31
31
  }
32
32
 
33
33
  // src/provider.tsx
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/provider.tsx","../src/modules/helpers.ts"],"sourcesContent":["import { ReactNode } from 'react';\n\nimport { canUseDOM } from './modules/helpers';\n\ninterface Props {\n children: ReactNode;\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 { ReactNode } from 'react';\n\nimport { canUseDOM } from './modules/helpers';\n\ninterface Props {\n children: ReactNode;\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\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function canUseDOM(): boolean {\n return !!window?.document?.createElement;\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\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\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\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMO,SAAS,YAAqB;AACnC,SAAO,CAAC,CAAC,QAAQ,UAAU;AAC7B;;;ADCe,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
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/modules/helpers.ts
4
4
  function canUseDOM() {
5
- return !!(typeof window !== "undefined" && window.document && window.document.createElement);
5
+ return !!window?.document?.createElement;
6
6
  }
7
7
 
8
8
  // src/provider.tsx
@@ -1 +1 @@
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 { ReactNode } from 'react';\n\nimport { canUseDOM } from './modules/helpers';\n\ninterface Props {\n children: ReactNode;\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\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function canUseDOM(): boolean {\n return !!window?.document?.createElement;\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\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\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\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","import { ReactNode } from 'react';\n\nimport { canUseDOM } from './modules/helpers';\n\ninterface Props {\n children: ReactNode;\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":";;;AAMO,SAAS,YAAqB;AACnC,SAAO,CAAC,CAAC,QAAQ,UAAU;AAC7B;;;ACCe,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.4",
3
+ "version": "4.1.6",
4
4
  "description": "An SVG loader for React",
5
5
  "author": "Gil Barbara <gilbarbara@gmail.com>",
6
6
  "contributors": [
@@ -48,41 +48,41 @@
48
48
  "types": "dist/index.d.ts",
49
49
  "sideEffects": false,
50
50
  "peerDependencies": {
51
- "react": "16.8 - 18"
51
+ "react": "16.8 - 19"
52
52
  },
53
53
  "dependencies": {
54
- "react-from-dom": "^0.7.3"
54
+ "react-from-dom": "^0.7.5"
55
55
  },
56
56
  "devDependencies": {
57
- "@arethetypeswrong/cli": "^0.16.4",
58
- "@gilbarbara/eslint-config": "^0.8.1",
57
+ "@arethetypeswrong/cli": "^0.17.3",
58
+ "@gilbarbara/eslint-config": "^0.8.4",
59
59
  "@gilbarbara/prettier-config": "^1.0.0",
60
60
  "@gilbarbara/tsconfig": "^0.2.3",
61
61
  "@size-limit/preset-small-lib": "^11.1.6",
62
- "@testing-library/jest-dom": "^6.6.2",
63
- "@testing-library/react": "^16.0.1",
64
- "@types/node": "^20.11.21",
65
- "@types/react": "^18.3.11",
66
- "@types/react-dom": "^18.3.1",
67
- "@vitejs/plugin-react": "^4.3.3",
68
- "@vitest/coverage-v8": "^2.1.3",
62
+ "@testing-library/jest-dom": "^6.6.3",
63
+ "@testing-library/react": "^16.1.0",
64
+ "@types/node": "^22.10.6",
65
+ "@types/react": "^19.0.7",
66
+ "@types/react-dom": "^19.0.3",
67
+ "@vitejs/plugin-react": "^4.3.4",
68
+ "@vitest/coverage-v8": "^2.1.8",
69
69
  "browser-cache-mock": "^0.1.7",
70
70
  "del-cli": "^6.0.0",
71
71
  "fix-tsup-cjs": "^1.2.0",
72
72
  "http-server": "^14.1.1",
73
- "husky": "^9.1.6",
73
+ "husky": "^9.1.7",
74
74
  "jest-extended": "^4.0.2",
75
- "jsdom": "^25.0.1",
76
- "react": "^18.3.1",
77
- "react-dom": "^18.3.1",
75
+ "jsdom": "^26.0.0",
76
+ "react": "^19.0.0",
77
+ "react-dom": "^19.0.0",
78
78
  "repo-tools": "^0.3.1",
79
79
  "size-limit": "^11.1.6",
80
- "start-server-and-test": "^2.0.8",
80
+ "start-server-and-test": "^2.0.10",
81
81
  "ts-node": "^10.9.2",
82
- "tsup": "^8.3.0",
83
- "typescript": "^5.6.3",
84
- "vitest": "^2.1.3",
85
- "vitest-fetch-mock": "^0.3.0"
82
+ "tsup": "^8.3.5",
83
+ "typescript": "^5.7.3",
84
+ "vitest": "^2.1.8",
85
+ "vitest-fetch-mock": "^0.4.3"
86
86
  },
87
87
  "scripts": {
88
88
  "build": "pnpm run clean && tsup && fix-tsup-cjs",
package/src/index.tsx CHANGED
@@ -243,7 +243,10 @@ function ReactInlineSVG(props: Props) {
243
243
  }
244
244
 
245
245
  if (element) {
246
- return cloneElement(element as ReactElement, { ref: innerRef, ...elementProps });
246
+ return cloneElement(element as ReactElement<any>, {
247
+ ref: innerRef,
248
+ ...elementProps,
249
+ });
247
250
  }
248
251
 
249
252
  if (([STATUS.UNSUPPORTED, STATUS.FAILED] as Status[]).includes(status)) {
@@ -1,8 +1,8 @@
1
- import { canUseDOM, request, sleep } from './helpers';
2
-
3
1
  import { CACHE_MAX_RETRIES, CACHE_NAME, STATUS } from '../config';
4
2
  import { StorageItem } from '../types';
5
3
 
4
+ import { canUseDOM, request, sleep } from './helpers';
5
+
6
6
  export default class CacheStore {
7
7
  private cacheApi: Cache | undefined;
8
8
  private readonly cacheStore: Map<string, StorageItem>;
@@ -25,15 +25,14 @@ export default class CacheStore {
25
25
  .open(cacheName)
26
26
  .then(cache => {
27
27
  this.cacheApi = cache;
28
- this.isReady = true;
29
-
30
- this.subscribers.forEach(callback => callback());
31
28
  })
32
29
  .catch(error => {
33
- this.isReady = true;
34
-
35
30
  // eslint-disable-next-line no-console
36
31
  console.error(`Failed to open cache: ${error.message}`);
32
+ })
33
+ .finally(() => {
34
+ this.isReady = true;
35
+ this.subscribers.forEach(callback => callback());
37
36
  });
38
37
  } else {
39
38
  this.isReady = true;
@@ -1,13 +1,51 @@
1
1
  import type { PlainObject } from '../types';
2
2
 
3
+ function randomCharacter(character: string) {
4
+ return character[Math.floor(Math.random() * character.length)];
5
+ }
6
+
3
7
  export function canUseDOM(): boolean {
4
- return !!(typeof window !== 'undefined' && window.document && window.document.createElement);
8
+ return !!window?.document?.createElement;
5
9
  }
6
10
 
7
11
  export function isSupportedEnvironment(): boolean {
8
12
  return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;
9
13
  }
10
14
 
15
+ /**
16
+ * Remove properties from an object
17
+ */
18
+ export function omit<T extends PlainObject, K extends keyof T>(
19
+ input: T,
20
+ ...filter: K[]
21
+ ): Omit<T, K> {
22
+ const output: any = {};
23
+
24
+ for (const key in input) {
25
+ if ({}.hasOwnProperty.call(input, key)) {
26
+ if (!filter.includes(key as unknown as K)) {
27
+ output[key] = input[key];
28
+ }
29
+ }
30
+ }
31
+
32
+ return output as Omit<T, K>;
33
+ }
34
+
35
+ export function randomString(length: number): string {
36
+ const letters = 'abcdefghijklmnopqrstuvwxyz';
37
+ const numbers = '1234567890';
38
+ const charset = `${letters}${letters.toUpperCase()}${numbers}`;
39
+
40
+ let R = '';
41
+
42
+ for (let index = 0; index < length; index++) {
43
+ R += randomCharacter(charset);
44
+ }
45
+
46
+ return R;
47
+ }
48
+
11
49
  export async function request(url: string, options?: RequestInit) {
12
50
  const response = await fetch(url, options);
13
51
  const contentType = response.headers.get('content-type');
@@ -43,41 +81,3 @@ export function supportsInlineSVG(): boolean {
43
81
 
44
82
  return !!svg && svg.namespaceURI === 'http://www.w3.org/2000/svg';
45
83
  }
46
-
47
- function randomCharacter(character: string) {
48
- return character[Math.floor(Math.random() * character.length)];
49
- }
50
-
51
- export function randomString(length: number): string {
52
- const letters = 'abcdefghijklmnopqrstuvwxyz';
53
- const numbers = '1234567890';
54
- const charset = `${letters}${letters.toUpperCase()}${numbers}`;
55
-
56
- let R = '';
57
-
58
- for (let index = 0; index < length; index++) {
59
- R += randomCharacter(charset);
60
- }
61
-
62
- return R;
63
- }
64
-
65
- /**
66
- * Remove properties from an object
67
- */
68
- export function omit<T extends PlainObject, K extends keyof T>(
69
- input: T,
70
- ...filter: K[]
71
- ): Omit<T, K> {
72
- const output: any = {};
73
-
74
- for (const key in input) {
75
- if ({}.hasOwnProperty.call(input, key)) {
76
- if (!filter.includes(key as unknown as K)) {
77
- output[key] = input[key];
78
- }
79
- }
80
- }
81
-
82
- return output as Omit<T, K>;
83
- }
@@ -1,7 +1,7 @@
1
1
  import { useEffect, useRef } from 'react';
2
2
 
3
3
  export function usePrevious<T>(state: T): T | undefined {
4
- const ref = useRef<T>();
4
+ const ref = useRef<T>(undefined);
5
5
 
6
6
  useEffect(() => {
7
7
  ref.current = state;
package/src/types.ts CHANGED
@@ -1,4 +1,4 @@
1
- import * as React from 'react';
1
+ import { ReactNode, RefObject, SVGProps } from 'react';
2
2
 
3
3
  import { STATUS } from './config';
4
4
 
@@ -8,14 +8,14 @@ export type PlainObject<T = unknown> = Record<string, T>;
8
8
  export type PreProcessorCallback = (code: string) => string;
9
9
 
10
10
  export type Props = Simplify<
11
- Omit<React.SVGProps<SVGElement>, 'onLoad' | 'onError' | 'ref'> & {
11
+ Omit<SVGProps<SVGElement>, 'onLoad' | 'onError' | 'ref'> & {
12
12
  baseURL?: string;
13
13
  cacheRequests?: boolean;
14
- children?: React.ReactNode;
14
+ children?: ReactNode;
15
15
  description?: string;
16
16
  fetchOptions?: RequestInit;
17
- innerRef?: React.Ref<SVGElement>;
18
- loader?: React.ReactNode;
17
+ innerRef?: RefObject<SVGElement | null>;
18
+ loader?: ReactNode;
19
19
  onError?: ErrorCallback;
20
20
  onLoad?: LoadCallback;
21
21
  preProcessor?: PreProcessorCallback;
@@ -26,12 +26,9 @@ export type Props = Simplify<
26
26
  }
27
27
  >;
28
28
 
29
- export interface State {
30
- content: string;
31
- element: React.ReactNode;
32
- isCached: boolean;
33
- status: Status;
34
- }
29
+ export type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};
30
+
31
+ export type Status = (typeof STATUS)[keyof typeof STATUS];
35
32
 
36
33
  export interface FetchError extends Error {
37
34
  code: string;
@@ -40,9 +37,12 @@ export interface FetchError extends Error {
40
37
  type: string;
41
38
  }
42
39
 
43
- export type Simplify<T> = { [KeyType in keyof T]: T[KeyType] } & {};
44
-
45
- export type Status = (typeof STATUS)[keyof typeof STATUS];
40
+ export interface State {
41
+ content: string;
42
+ element: ReactNode;
43
+ isCached: boolean;
44
+ status: Status;
45
+ }
46
46
 
47
47
  export interface StorageItem {
48
48
  content: string;