react-inlinesvg 4.0.5 → 4.0.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.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4 -1
- package/dist/index.mjs.map +1 -1
- package/dist/provider.js.map +1 -1
- package/dist/provider.mjs.map +1 -1
- package/package.json +14 -18
- package/src/cache.ts +15 -7
- package/src/helpers.ts +1 -2
- package/src/index.tsx +0 -8
package/dist/index.js
CHANGED
|
@@ -124,13 +124,16 @@ var CacheStore = class {
|
|
|
124
124
|
let usePersistentCache = false;
|
|
125
125
|
if (canUseDOM()) {
|
|
126
126
|
cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;
|
|
127
|
-
usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE;
|
|
127
|
+
usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE && "caches" in window;
|
|
128
128
|
}
|
|
129
129
|
if (usePersistentCache) {
|
|
130
130
|
caches.open(cacheName).then((cache) => {
|
|
131
131
|
this.cacheApi = cache;
|
|
132
132
|
this.isReady = true;
|
|
133
133
|
this.subscribers.forEach((callback) => callback());
|
|
134
|
+
}).catch((error) => {
|
|
135
|
+
this.isReady = true;
|
|
136
|
+
console.error(`Failed to open cache: ${error.message}`);
|
|
134
137
|
});
|
|
135
138
|
} else {
|
|
136
139
|
this.isReady = true;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.tsx","../src/config.ts","../src/helpers.ts","../src/cache.ts"],"sourcesContent":["import * as React from 'react';\nimport convert from 'react-from-dom';\n\nimport CacheStore from './cache';\nimport { STATUS } from './config';\nimport { canUseDOM, isSupportedEnvironment, omit, randomString, request } from './helpers';\nimport { FetchError, Props, State, Status } from './types';\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let cacheStore: CacheStore;\n\nclass ReactInlineSVG extends React.PureComponent<Props, State> {\n private readonly hash: string;\n private isActive = false;\n private isInitialized = false;\n\n public static defaultProps = {\n cacheRequests: true,\n uniquifyIDs: false,\n };\n\n constructor(props: Props) {\n super(props);\n\n this.state = {\n content: '',\n element: null,\n isCached: !!props.cacheRequests && cacheStore.isCached(props.src),\n status: STATUS.IDLE,\n };\n\n this.hash = props.uniqueHash ?? randomString(8);\n }\n\n public componentDidMount(): void {\n this.isActive = true;\n\n if (!canUseDOM() || this.isInitialized) {\n return;\n }\n\n const { status } = this.state;\n const { src } = this.props;\n\n try {\n /* istanbul ignore else */\n if (status === STATUS.IDLE) {\n /* istanbul ignore else */\n if (!isSupportedEnvironment()) {\n throw new Error('Browser does not support SVG');\n }\n\n /* istanbul ignore else */\n if (!src) {\n throw new Error('Missing src');\n }\n\n this.load();\n }\n } catch (error: any) {\n this.handleError(error);\n }\n\n this.isInitialized = true;\n }\n\n public componentDidUpdate(previousProps: Props, previousState: State): void {\n if (!canUseDOM()) {\n return;\n }\n\n const { isCached, status } = this.state;\n const { description, onLoad, src, title } = this.props;\n\n if (previousState.status !== STATUS.READY && status === STATUS.READY) {\n /* istanbul ignore else */\n if (onLoad) {\n onLoad(src, isCached);\n }\n }\n\n if (previousProps.src !== src) {\n if (!src) {\n this.handleError(new Error('Missing src'));\n\n return;\n }\n\n this.load();\n }\n\n if (previousProps.title !== title || previousProps.description !== description) {\n this.getElement();\n }\n }\n\n public componentWillUnmount(): void {\n this.isActive = false;\n }\n\n private fetchContent = async () => {\n const { fetchOptions, src } = this.props;\n\n const content: string = await request(src, fetchOptions);\n\n this.handleLoad(content);\n };\n\n private getElement() {\n try {\n const node = this.getNode() as Node;\n const element = convert(node);\n\n if (!element || !React.isValidElement(element)) {\n throw new Error('Could not convert the src to a React element');\n }\n\n this.setState({\n element,\n status: STATUS.READY,\n });\n } catch (error: any) {\n this.handleError(new Error(error.message));\n }\n }\n\n private getNode() {\n const { description, title } = this.props;\n\n try {\n const svgText = this.processSVG();\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 = this.updateSVGAttributes(node);\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 this.handleError(error);\n }\n }\n\n private handleError = (error: Error | FetchError) => {\n const { onError } = this.props;\n const status =\n error.message === 'Browser does not support SVG' ? STATUS.UNSUPPORTED : STATUS.FAILED;\n\n /* istanbul ignore else */\n if (this.isActive) {\n this.setState({ status }, () => {\n /* istanbul ignore else */\n if (typeof onError === 'function') {\n onError(error);\n }\n });\n }\n };\n\n private handleLoad = (content: string, hasCache = false) => {\n /* istanbul ignore else */\n if (this.isActive) {\n this.setState(\n {\n content,\n isCached: hasCache,\n status: STATUS.LOADED,\n },\n this.getElement,\n );\n }\n };\n\n private load() {\n /* istanbul ignore else */\n if (this.isActive) {\n this.setState(\n {\n content: '',\n element: null,\n isCached: false,\n status: STATUS.LOADING,\n },\n async () => {\n const { cacheRequests, fetchOptions, src } = this.props;\n\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 this.handleLoad(inlineSrc);\n\n return;\n }\n\n try {\n if (cacheRequests) {\n const content = await cacheStore.get(src, fetchOptions);\n\n this.handleLoad(content, true);\n } else {\n await this.fetchContent();\n }\n } catch (error: any) {\n this.handleError(error);\n }\n },\n );\n }\n }\n\n private processSVG() {\n const { content } = this.state;\n const { preProcessor } = this.props;\n\n if (preProcessor) {\n return preProcessor(content);\n }\n\n return content;\n }\n\n private updateSVGAttributes(node: SVGSVGElement): SVGSVGElement {\n const { baseURL = '', uniquifyIDs } = this.props;\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]}__${this.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}__${this.hash}`;\n }\n });\n }\n\n if (d.children.length) {\n return this.updateSVGAttributes(d as SVGSVGElement);\n }\n\n return d;\n });\n\n return node;\n }\n\n public render(): React.ReactNode {\n const { element, status } = this.state;\n const { children = null, innerRef, loader = null } = this.props;\n const elementProps = omit(\n this.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 React.cloneElement(element as React.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}\n\nexport default function InlineSVG(props: Props) {\n if (!cacheStore) {\n cacheStore = new CacheStore();\n }\n\n const { loader } = props;\n const hasCallback = React.useRef(false);\n const [isReady, setReady] = React.useState(cacheStore.isReady);\n\n React.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 /* istanbul ignore next */\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 /* istanbul ignore else */\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n }\n\n return output as Omit<T, K>;\n}\n","import { CACHE_MAX_RETRIES, CACHE_NAME, STATUS } from './config';\nimport { canUseDOM, request, sleep } from './helpers';\nimport { StorageItem } from './types';\n\nexport default class CacheStore {\n private cacheApi: Cache | undefined;\n private readonly cacheStore: Map<string, StorageItem>;\n private readonly subscribers: Array<() => void> = [];\n public isReady = false;\n\n constructor() {\n this.cacheStore = new Map<string, StorageItem>();\n\n let cacheName = CACHE_NAME;\n let usePersistentCache = false;\n\n if (canUseDOM()) {\n cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;\n usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE;\n }\n\n if (usePersistentCache) {\n caches.open(cacheName).then(cache => {\n this.cacheApi = cache;\n this.isReady = true;\n\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 // eslint-disable-next-line no-await-in-loop\n while (this.cacheStore.get(url)?.status === STATUS.LOADING && retryCount < CACHE_MAX_RETRIES) {\n // eslint-disable-next-line no-await-in-loop\n await sleep(0.1);\n retryCount += 1;\n }\n\n if (retryCount >= CACHE_MAX_RETRIES) {\n await callback();\n }\n }\n\n public keys(): Array<string> {\n return [...this.cacheStore.keys()];\n }\n\n public data(): Array<Record<string, StorageItem>> {\n return [...this.cacheStore.entries()].map(([key, value]) => ({ [key]: value }));\n }\n\n public async delete(url: string) {\n if (this.cacheApi) {\n await this.cacheApi.delete(url);\n }\n\n this.cacheStore.delete(url);\n }\n\n public async clear() {\n if (this.cacheApi) {\n const keys = await this.cacheApi.keys();\n\n for (const key of keys) {\n // eslint-disable-next-line no-await-in-loop\n await this.cacheApi.delete(key);\n }\n }\n\n this.cacheStore.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YAAuB;AACvB,4BAAoB;;;ACDb,IAAM,aAAa;AACnB,IAAM,oBAAoB;AAE1B,IAAM,SAAS;AAAA,EACpB,MAAM;AAAA,EACN,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,aAAa;AACf;;;ACRO,SAAS,YAAqB;AACnC,SAAO,CAAC,EAAE,OAAO,WAAW,eAAe,OAAO,YAAY,OAAO,SAAS;AAChF;AAEO,SAAS,yBAAkC;AAChD,SAAO,kBAAkB,KAAK,OAAO,WAAW,eAAe,WAAW;AAC5E;AAEA,eAAsB,QAAQ,KAAa,SAAuB;AAChE,QAAM,WAAW,MAAM,MAAM,KAAK,OAAO;AACzC,QAAM,cAAc,SAAS,QAAQ,IAAI,cAAc;AACvD,QAAM,CAAC,QAAQ,KAAK,eAAe,IAAI,MAAM,OAAO;AAEpD,MAAI,SAAS,SAAS,KAAK;AACzB,UAAM,IAAI,MAAM,WAAW;AAAA,EAC7B;AAEA,MAAI,CAAC,CAAC,iBAAiB,YAAY,EAAE,KAAK,OAAK,SAAS,SAAS,CAAC,CAAC,GAAG;AACpE,UAAM,IAAI,MAAM,6BAA6B,QAAQ,EAAE;AAAA,EACzD;AAEA,SAAO,SAAS,KAAK;AACvB;AAEO,SAAS,MAAM,UAAU,GAAG;AACjC,SAAO,IAAI,QAAQ,aAAW;AAC5B,eAAW,SAAS,UAAU,GAAI;AAAA,EACpC,CAAC;AACH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UAAM,eAAe;AAAA,MACnB,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAEA,QAAI,CAAC,UAAU,GAAG;AAChB,aAAO;AAAA,IACT;AAEA,QAAI,SAAS;AACX,aAAa,mBAAa,SAA+B,EAAE,KAAK,UAAU,GAAG,aAAa,CAAC;AAAA,IAC7F;AAEA,QAAK,CAAC,OAAO,aAAa,OAAO,MAAM,EAAe,SAAS,MAAM,GAAG;AACtE,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AACF;AAhUE,cALI,gBAKU,gBAAe;AAAA,EAC3B,eAAe;AAAA,EACf,aAAa;AACf;AA+Ta,SAAR,UAA2B,OAAc;AAC9C,MAAI,CAAC,YAAY;AACf,iBAAa,IAAI,WAAW;AAAA,EAC9B;AAEA,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,cAAoB,aAAO,KAAK;AACtC,QAAM,CAAC,SAAS,QAAQ,IAAU,eAAS,WAAW,OAAO;AAE7D,EAAM,gBAAU,MAAM;AACpB,QAAI,CAAC,YAAY,SAAS;AACxB,iBAAW,QAAQ,MAAM;AACvB,iBAAS,IAAI;AAAA,MACf,CAAC;AAED,kBAAY,UAAU;AAAA,IACxB;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,SAAO,4CAAC,kBAAgB,GAAG,OAAO;AACpC;","names":["convert"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.tsx","../src/config.ts","../src/helpers.ts","../src/cache.ts"],"sourcesContent":["import * as React from 'react';\nimport convert from 'react-from-dom';\n\nimport CacheStore from './cache';\nimport { STATUS } from './config';\nimport { canUseDOM, isSupportedEnvironment, omit, randomString, request } from './helpers';\nimport { FetchError, Props, State, Status } from './types';\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let cacheStore: CacheStore;\n\nclass ReactInlineSVG extends React.PureComponent<Props, State> {\n private readonly hash: string;\n private isActive = false;\n private isInitialized = false;\n\n public static defaultProps = {\n cacheRequests: true,\n uniquifyIDs: false,\n };\n\n constructor(props: Props) {\n super(props);\n\n this.state = {\n content: '',\n element: null,\n isCached: !!props.cacheRequests && cacheStore.isCached(props.src),\n status: STATUS.IDLE,\n };\n\n this.hash = props.uniqueHash ?? randomString(8);\n }\n\n public componentDidMount(): void {\n this.isActive = true;\n\n if (!canUseDOM() || this.isInitialized) {\n return;\n }\n\n const { status } = this.state;\n const { src } = this.props;\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 this.load();\n }\n } catch (error: any) {\n this.handleError(error);\n }\n\n this.isInitialized = true;\n }\n\n public componentDidUpdate(previousProps: Props, previousState: State): void {\n if (!canUseDOM()) {\n return;\n }\n\n const { isCached, status } = this.state;\n const { description, onLoad, src, title } = this.props;\n\n if (previousState.status !== STATUS.READY && status === STATUS.READY) {\n if (onLoad) {\n onLoad(src, isCached);\n }\n }\n\n if (previousProps.src !== src) {\n if (!src) {\n this.handleError(new Error('Missing src'));\n\n return;\n }\n\n this.load();\n }\n\n if (previousProps.title !== title || previousProps.description !== description) {\n this.getElement();\n }\n }\n\n public componentWillUnmount(): void {\n this.isActive = false;\n }\n\n private fetchContent = async () => {\n const { fetchOptions, src } = this.props;\n\n const content: string = await request(src, fetchOptions);\n\n this.handleLoad(content);\n };\n\n private getElement() {\n try {\n const node = this.getNode() as Node;\n const element = convert(node);\n\n if (!element || !React.isValidElement(element)) {\n throw new Error('Could not convert the src to a React element');\n }\n\n this.setState({\n element,\n status: STATUS.READY,\n });\n } catch (error: any) {\n this.handleError(new Error(error.message));\n }\n }\n\n private getNode() {\n const { description, title } = this.props;\n\n try {\n const svgText = this.processSVG();\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 = this.updateSVGAttributes(node);\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 this.handleError(error);\n }\n }\n\n private handleError = (error: Error | FetchError) => {\n const { onError } = this.props;\n const status =\n error.message === 'Browser does not support SVG' ? STATUS.UNSUPPORTED : STATUS.FAILED;\n\n if (this.isActive) {\n this.setState({ status }, () => {\n if (typeof onError === 'function') {\n onError(error);\n }\n });\n }\n };\n\n private handleLoad = (content: string, hasCache = false) => {\n if (this.isActive) {\n this.setState(\n {\n content,\n isCached: hasCache,\n status: STATUS.LOADED,\n },\n this.getElement,\n );\n }\n };\n\n private load() {\n if (this.isActive) {\n this.setState(\n {\n content: '',\n element: null,\n isCached: false,\n status: STATUS.LOADING,\n },\n async () => {\n const { cacheRequests, fetchOptions, src } = this.props;\n\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 this.handleLoad(inlineSrc);\n\n return;\n }\n\n try {\n if (cacheRequests) {\n const content = await cacheStore.get(src, fetchOptions);\n\n this.handleLoad(content, true);\n } else {\n await this.fetchContent();\n }\n } catch (error: any) {\n this.handleError(error);\n }\n },\n );\n }\n }\n\n private processSVG() {\n const { content } = this.state;\n const { preProcessor } = this.props;\n\n if (preProcessor) {\n return preProcessor(content);\n }\n\n return content;\n }\n\n private updateSVGAttributes(node: SVGSVGElement): SVGSVGElement {\n const { baseURL = '', uniquifyIDs } = this.props;\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]}__${this.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}__${this.hash}`;\n }\n });\n }\n\n if (d.children.length) {\n return this.updateSVGAttributes(d as SVGSVGElement);\n }\n\n return d;\n });\n\n return node;\n }\n\n public render(): React.ReactNode {\n const { element, status } = this.state;\n const { children = null, innerRef, loader = null } = this.props;\n const elementProps = omit(\n this.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 React.cloneElement(element as React.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}\n\nexport default function InlineSVG(props: Props) {\n if (!cacheStore) {\n cacheStore = new CacheStore();\n }\n\n const { loader } = props;\n const hasCallback = React.useRef(false);\n const [isReady, setReady] = React.useState(cacheStore.isReady);\n\n React.useEffect(() => {\n if (!hasCallback.current) {\n cacheStore.onReady(() => {\n setReady(true);\n });\n\n hasCallback.current = true;\n }\n }, []);\n\n if (!isReady) {\n return loader;\n }\n\n return <ReactInlineSVG {...props} />;\n}\n\nexport * from './types';\n","export const CACHE_NAME = 'react-inlinesvg';\nexport const CACHE_MAX_RETRIES = 10;\n\nexport const STATUS = {\n IDLE: 'idle',\n LOADING: 'loading',\n LOADED: 'loaded',\n FAILED: 'failed',\n READY: 'ready',\n UNSUPPORTED: 'unsupported',\n} as const;\n","import type { PlainObject } from './types';\n\nexport function canUseDOM(): boolean {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\n\nexport async function request(url: string, options?: RequestInit) {\n const response = await fetch(url, options);\n const contentType = response.headers.get('content-type');\n const [fileType] = (contentType ?? '').split(/ ?; ?/);\n\n if (response.status > 299) {\n throw new Error('Not found');\n }\n\n if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {\n throw new Error(`Content type isn't valid: ${fileType}`);\n }\n\n return response.text();\n}\n\nexport function sleep(seconds = 1) {\n return new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n}\n\nexport function supportsInlineSVG(): boolean {\n /* c8 ignore next 3 */\n if (!document) {\n return false;\n }\n\n const div = document.createElement('div');\n\n div.innerHTML = '<svg />';\n const svg = div.firstChild as SVGSVGElement;\n\n return !!svg && svg.namespaceURI === 'http://www.w3.org/2000/svg';\n}\n\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function randomString(length: number): string {\n const letters = 'abcdefghijklmnopqrstuvwxyz';\n const numbers = '1234567890';\n const charset = `${letters}${letters.toUpperCase()}${numbers}`;\n\n let R = '';\n\n for (let index = 0; index < length; index++) {\n R += randomCharacter(charset);\n }\n\n return R;\n}\n\n/**\n * Remove properties from an object\n */\nexport function omit<T extends PlainObject, K extends keyof T>(\n input: T,\n ...filter: K[]\n): Omit<T, K> {\n const output: any = {};\n\n for (const key in input) {\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n }\n\n return output as Omit<T, K>;\n}\n","import { CACHE_MAX_RETRIES, CACHE_NAME, STATUS } from './config';\nimport { canUseDOM, request, sleep } from './helpers';\nimport { StorageItem } from './types';\n\nexport default class CacheStore {\n private cacheApi: Cache | undefined;\n private readonly cacheStore: Map<string, StorageItem>;\n private readonly subscribers: Array<() => void> = [];\n public isReady = false;\n\n constructor() {\n this.cacheStore = new Map<string, StorageItem>();\n\n let cacheName = CACHE_NAME;\n let usePersistentCache = false;\n\n if (canUseDOM()) {\n cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;\n usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE && 'caches' in window;\n }\n\n if (usePersistentCache) {\n caches\n .open(cacheName)\n .then(cache => {\n this.cacheApi = cache;\n this.isReady = true;\n\n this.subscribers.forEach(callback => callback());\n })\n .catch(error => {\n this.isReady = true;\n\n // eslint-disable-next-line no-console\n console.error(`Failed to open cache: ${error.message}`);\n });\n } else {\n this.isReady = true;\n }\n }\n\n public onReady(callback: () => void) {\n if (this.isReady) {\n callback();\n } else {\n this.subscribers.push(callback);\n }\n }\n\n public async get(url: string, fetchOptions?: RequestInit) {\n await (this.cacheApi\n ? this.fetchAndAddToPersistentCache(url, fetchOptions)\n : this.fetchAndAddToInternalCache(url, fetchOptions));\n\n return this.cacheStore.get(url)?.content ?? '';\n }\n\n public set(url: string, data: StorageItem) {\n this.cacheStore.set(url, data);\n }\n\n public isCached(url: string) {\n return this.cacheStore.get(url)?.status === STATUS.LOADED;\n }\n\n private async fetchAndAddToInternalCache(url: string, fetchOptions?: RequestInit) {\n const cache = this.cacheStore.get(url);\n\n if (cache?.status === STATUS.LOADING) {\n await this.handleLoading(url, async () => {\n this.cacheStore.set(url, { content: '', status: STATUS.IDLE });\n await this.fetchAndAddToInternalCache(url, fetchOptions);\n });\n\n return;\n }\n\n if (!cache?.content) {\n this.cacheStore.set(url, { content: '', status: STATUS.LOADING });\n\n try {\n const content = await request(url, fetchOptions);\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n } catch (error: any) {\n this.cacheStore.set(url, { content: '', status: STATUS.FAILED });\n throw error;\n }\n }\n }\n\n private async fetchAndAddToPersistentCache(url: string, fetchOptions?: RequestInit) {\n const cache = this.cacheStore.get(url);\n\n if (cache?.status === STATUS.LOADED) {\n return;\n }\n\n if (cache?.status === STATUS.LOADING) {\n await this.handleLoading(url, async () => {\n this.cacheStore.set(url, { content: '', status: STATUS.IDLE });\n await this.fetchAndAddToPersistentCache(url, fetchOptions);\n });\n\n return;\n }\n\n this.cacheStore.set(url, { content: '', status: STATUS.LOADING });\n\n const data = await this.cacheApi?.match(url);\n\n if (data) {\n const content = await data.text();\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n\n return;\n }\n\n try {\n await this.cacheApi?.add(new Request(url, fetchOptions));\n\n const response = await this.cacheApi?.match(url);\n const content = (await response?.text()) ?? '';\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n } catch (error: any) {\n this.cacheStore.set(url, { content: '', status: STATUS.FAILED });\n throw error;\n }\n }\n\n private async handleLoading(url: string, callback: () => Promise<void>) {\n let retryCount = 0;\n\n // eslint-disable-next-line no-await-in-loop\n while (this.cacheStore.get(url)?.status === STATUS.LOADING && retryCount < CACHE_MAX_RETRIES) {\n // eslint-disable-next-line no-await-in-loop\n await sleep(0.1);\n retryCount += 1;\n }\n\n if (retryCount >= CACHE_MAX_RETRIES) {\n await callback();\n }\n }\n\n public keys(): Array<string> {\n return [...this.cacheStore.keys()];\n }\n\n public data(): Array<Record<string, StorageItem>> {\n return [...this.cacheStore.entries()].map(([key, value]) => ({ [key]: value }));\n }\n\n public async delete(url: string) {\n if (this.cacheApi) {\n await this.cacheApi.delete(url);\n }\n\n this.cacheStore.delete(url);\n }\n\n public async clear() {\n if (this.cacheApi) {\n const keys = await this.cacheApi.keys();\n\n for (const key of keys) {\n // eslint-disable-next-line no-await-in-loop\n await this.cacheApi.delete(key);\n }\n }\n\n this.cacheStore.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YAAuB;AACvB,4BAAoB;;;ACDb,IAAM,aAAa;AACnB,IAAM,oBAAoB;AAE1B,IAAM,SAAS;AAAA,EACpB,MAAM;AAAA,EACN,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,aAAa;AACf;;;ACRO,SAAS,YAAqB;AACnC,SAAO,CAAC,EAAE,OAAO,WAAW,eAAe,OAAO,YAAY,OAAO,SAAS;AAChF;AAEO,SAAS,yBAAkC;AAChD,SAAO,kBAAkB,KAAK,OAAO,WAAW,eAAe,WAAW;AAC5E;AAEA,eAAsB,QAAQ,KAAa,SAAuB;AAChE,QAAM,WAAW,MAAM,MAAM,KAAK,OAAO;AACzC,QAAM,cAAc,SAAS,QAAQ,IAAI,cAAc;AACvD,QAAM,CAAC,QAAQ,KAAK,eAAe,IAAI,MAAM,OAAO;AAEpD,MAAI,SAAS,SAAS,KAAK;AACzB,UAAM,IAAI,MAAM,WAAW;AAAA,EAC7B;AAEA,MAAI,CAAC,CAAC,iBAAiB,YAAY,EAAE,KAAK,OAAK,SAAS,SAAS,CAAC,CAAC,GAAG;AACpE,UAAM,IAAI,MAAM,6BAA6B,QAAQ,EAAE;AAAA,EACzD;AAEA,SAAO,SAAS,KAAK;AACvB;AAEO,SAAS,MAAM,UAAU,GAAG;AACjC,SAAO,IAAI,QAAQ,aAAW;AAC5B,eAAW,SAAS,UAAU,GA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AAAA,EAEO,SAA0B;AAC/B,UAAM,EAAE,SAAS,OAAO,IAAI,KAAK;AACjC,UAAM,EAAE,WAAW,MAAM,UAAU,SAAS,KAAK,IAAI,KAAK;AAC1D,UAAM,eAAe;AAAA,MACnB,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAEA,QAAI,CAAC,UAAU,GAAG;AAChB,aAAO;AAAA,IACT;AAEA,QAAI,SAAS;AACX,aAAa,mBAAa,SAA+B,EAAE,KAAK,UAAU,GAAG,aAAa,CAAC;AAAA,IAC7F;AAEA,QAAK,CAAC,OAAO,aAAa,OAAO,MAAM,EAAe,SAAS,MAAM,GAAG;AACtE,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AACF;AAxTE,cALI,gBAKU,gBAAe;AAAA,EAC3B,eAAe;AAAA,EACf,aAAa;AACf;AAuTa,SAAR,UAA2B,OAAc;AAC9C,MAAI,CAAC,YAAY;AACf,iBAAa,IAAI,WAAW;AAAA,EAC9B;AAEA,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,cAAoB,aAAO,KAAK;AACtC,QAAM,CAAC,SAAS,QAAQ,IAAU,eAAS,WAAW,OAAO;AAE7D,EAAM,gBAAU,MAAM;AACpB,QAAI,CAAC,YAAY,SAAS;AACxB,iBAAW,QAAQ,MAAM;AACvB,iBAAS,IAAI;AAAA,MACf,CAAC;AAED,kBAAY,UAAU;AAAA,IACxB;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,SAAO,4CAAC,kBAAgB,GAAG,OAAO;AACpC;","names":["convert"]}
|
package/dist/index.mjs
CHANGED
|
@@ -91,13 +91,16 @@ var CacheStore = class {
|
|
|
91
91
|
let usePersistentCache = false;
|
|
92
92
|
if (canUseDOM()) {
|
|
93
93
|
cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;
|
|
94
|
-
usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE;
|
|
94
|
+
usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE && "caches" in window;
|
|
95
95
|
}
|
|
96
96
|
if (usePersistentCache) {
|
|
97
97
|
caches.open(cacheName).then((cache) => {
|
|
98
98
|
this.cacheApi = cache;
|
|
99
99
|
this.isReady = true;
|
|
100
100
|
this.subscribers.forEach((callback) => callback());
|
|
101
|
+
}).catch((error) => {
|
|
102
|
+
this.isReady = true;
|
|
103
|
+
console.error(`Failed to open cache: ${error.message}`);
|
|
101
104
|
});
|
|
102
105
|
} else {
|
|
103
106
|
this.isReady = true;
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.tsx","../src/config.ts","../src/helpers.ts","../src/cache.ts"],"sourcesContent":["import * as React from 'react';\nimport convert from 'react-from-dom';\n\nimport CacheStore from './cache';\nimport { STATUS } from './config';\nimport { canUseDOM, isSupportedEnvironment, omit, randomString, request } from './helpers';\nimport { FetchError, Props, State, Status } from './types';\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let cacheStore: CacheStore;\n\nclass ReactInlineSVG extends React.PureComponent<Props, State> {\n private readonly hash: string;\n private isActive = false;\n private isInitialized = false;\n\n public static defaultProps = {\n cacheRequests: true,\n uniquifyIDs: false,\n };\n\n constructor(props: Props) {\n super(props);\n\n this.state = {\n content: '',\n element: null,\n isCached: !!props.cacheRequests && cacheStore.isCached(props.src),\n status: STATUS.IDLE,\n };\n\n this.hash = props.uniqueHash ?? randomString(8);\n }\n\n public componentDidMount(): void {\n this.isActive = true;\n\n if (!canUseDOM() || this.isInitialized) {\n return;\n }\n\n const { status } = this.state;\n const { src } = this.props;\n\n try {\n /* istanbul ignore else */\n if (status === STATUS.IDLE) {\n /* istanbul ignore else */\n if (!isSupportedEnvironment()) {\n throw new Error('Browser does not support SVG');\n }\n\n /* istanbul ignore else */\n if (!src) {\n throw new Error('Missing src');\n }\n\n this.load();\n }\n } catch (error: any) {\n this.handleError(error);\n }\n\n this.isInitialized = true;\n }\n\n public componentDidUpdate(previousProps: Props, previousState: State): void {\n if (!canUseDOM()) {\n return;\n }\n\n const { isCached, status } = this.state;\n const { description, onLoad, src, title } = this.props;\n\n if (previousState.status !== STATUS.READY && status === STATUS.READY) {\n /* istanbul ignore else */\n if (onLoad) {\n onLoad(src, isCached);\n }\n }\n\n if (previousProps.src !== src) {\n if (!src) {\n this.handleError(new Error('Missing src'));\n\n return;\n }\n\n this.load();\n }\n\n if (previousProps.title !== title || previousProps.description !== description) {\n this.getElement();\n }\n }\n\n public componentWillUnmount(): void {\n this.isActive = false;\n }\n\n private fetchContent = async () => {\n const { fetchOptions, src } = this.props;\n\n const content: string = await request(src, fetchOptions);\n\n this.handleLoad(content);\n };\n\n private getElement() {\n try {\n const node = this.getNode() as Node;\n const element = convert(node);\n\n if (!element || !React.isValidElement(element)) {\n throw new Error('Could not convert the src to a React element');\n }\n\n this.setState({\n element,\n status: STATUS.READY,\n });\n } catch (error: any) {\n this.handleError(new Error(error.message));\n }\n }\n\n private getNode() {\n const { description, title } = this.props;\n\n try {\n const svgText = this.processSVG();\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 = this.updateSVGAttributes(node);\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 this.handleError(error);\n }\n }\n\n private handleError = (error: Error | FetchError) => {\n const { onError } = this.props;\n const status =\n error.message === 'Browser does not support SVG' ? STATUS.UNSUPPORTED : STATUS.FAILED;\n\n /* istanbul ignore else */\n if (this.isActive) {\n this.setState({ status }, () => {\n /* istanbul ignore else */\n if (typeof onError === 'function') {\n onError(error);\n }\n });\n }\n };\n\n private handleLoad = (content: string, hasCache = false) => {\n /* istanbul ignore else */\n if (this.isActive) {\n this.setState(\n {\n content,\n isCached: hasCache,\n status: STATUS.LOADED,\n },\n this.getElement,\n );\n }\n };\n\n private load() {\n /* istanbul ignore else */\n if (this.isActive) {\n this.setState(\n {\n content: '',\n element: null,\n isCached: false,\n status: STATUS.LOADING,\n },\n async () => {\n const { cacheRequests, fetchOptions, src } = this.props;\n\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 this.handleLoad(inlineSrc);\n\n return;\n }\n\n try {\n if (cacheRequests) {\n const content = await cacheStore.get(src, fetchOptions);\n\n this.handleLoad(content, true);\n } else {\n await this.fetchContent();\n }\n } catch (error: any) {\n this.handleError(error);\n }\n },\n );\n }\n }\n\n private processSVG() {\n const { content } = this.state;\n const { preProcessor } = this.props;\n\n if (preProcessor) {\n return preProcessor(content);\n }\n\n return content;\n }\n\n private updateSVGAttributes(node: SVGSVGElement): SVGSVGElement {\n const { baseURL = '', uniquifyIDs } = this.props;\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]}__${this.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}__${this.hash}`;\n }\n });\n }\n\n if (d.children.length) {\n return this.updateSVGAttributes(d as SVGSVGElement);\n }\n\n return d;\n });\n\n return node;\n }\n\n public render(): React.ReactNode {\n const { element, status } = this.state;\n const { children = null, innerRef, loader = null } = this.props;\n const elementProps = omit(\n this.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 React.cloneElement(element as React.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}\n\nexport default function InlineSVG(props: Props) {\n if (!cacheStore) {\n cacheStore = new CacheStore();\n }\n\n const { loader } = props;\n const hasCallback = React.useRef(false);\n const [isReady, setReady] = React.useState(cacheStore.isReady);\n\n React.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 /* istanbul ignore next */\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 /* istanbul ignore else */\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n }\n\n return output as Omit<T, K>;\n}\n","import { CACHE_MAX_RETRIES, CACHE_NAME, STATUS } from './config';\nimport { canUseDOM, request, sleep } from './helpers';\nimport { StorageItem } from './types';\n\nexport default class CacheStore {\n private cacheApi: Cache | undefined;\n private readonly cacheStore: Map<string, StorageItem>;\n private readonly subscribers: Array<() => void> = [];\n public isReady = false;\n\n constructor() {\n this.cacheStore = new Map<string, StorageItem>();\n\n let cacheName = CACHE_NAME;\n let usePersistentCache = false;\n\n if (canUseDOM()) {\n cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;\n usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE;\n }\n\n if (usePersistentCache) {\n caches.open(cacheName).then(cache => {\n this.cacheApi = cache;\n this.isReady = true;\n\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 // eslint-disable-next-line no-await-in-loop\n while (this.cacheStore.get(url)?.status === STATUS.LOADING && retryCount < CACHE_MAX_RETRIES) {\n // eslint-disable-next-line no-await-in-loop\n await sleep(0.1);\n retryCount += 1;\n }\n\n if (retryCount >= CACHE_MAX_RETRIES) {\n await callback();\n }\n }\n\n public keys(): Array<string> {\n return [...this.cacheStore.keys()];\n }\n\n public data(): Array<Record<string, StorageItem>> {\n return [...this.cacheStore.entries()].map(([key, value]) => ({ [key]: value }));\n }\n\n public async delete(url: string) {\n if (this.cacheApi) {\n await this.cacheApi.delete(url);\n }\n\n this.cacheStore.delete(url);\n }\n\n public async clear() {\n if (this.cacheApi) {\n const keys = await this.cacheApi.keys();\n\n for (const key of keys) {\n // eslint-disable-next-line no-await-in-loop\n await this.cacheApi.delete(key);\n }\n }\n\n this.cacheStore.clear();\n }\n}\n"],"mappings":";;;;;;;;AAAA,YAAY,WAAW;AACvB,OAAO,aAAa;;;ACDb,IAAM,aAAa;AACnB,IAAM,oBAAoB;AAE1B,IAAM,SAAS;AAAA,EACpB,MAAM;AAAA,EACN,SAAS;AAAA,EAC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,gBAAe;AAAA,EAC3B,eAAe;AAAA,EACf,aAAa;AACf;AA+Ta,SAAR,UAA2B,OAAc;AAC9C,MAAI,CAAC,YAAY;AACf,iBAAa,IAAI,WAAW;AAAA,EAC9B;AAEA,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,cAAoB,aAAO,KAAK;AACtC,QAAM,CAAC,SAAS,QAAQ,IAAU,eAAS,WAAW,OAAO;AAE7D,EAAM,gBAAU,MAAM;AACpB,QAAI,CAAC,YAAY,SAAS;AACxB,iBAAW,QAAQ,MAAM;AACvB,iBAAS,IAAI;AAAA,MACf,CAAC;AAED,kBAAY,UAAU;AAAA,IACxB;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,SAAO,oBAAC,kBAAgB,GAAG,OAAO;AACpC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.tsx","../src/config.ts","../src/helpers.ts","../src/cache.ts"],"sourcesContent":["import * as React from 'react';\nimport convert from 'react-from-dom';\n\nimport CacheStore from './cache';\nimport { STATUS } from './config';\nimport { canUseDOM, isSupportedEnvironment, omit, randomString, request } from './helpers';\nimport { FetchError, Props, State, Status } from './types';\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let cacheStore: CacheStore;\n\nclass ReactInlineSVG extends React.PureComponent<Props, State> {\n private readonly hash: string;\n private isActive = false;\n private isInitialized = false;\n\n public static defaultProps = {\n cacheRequests: true,\n uniquifyIDs: false,\n };\n\n constructor(props: Props) {\n super(props);\n\n this.state = {\n content: '',\n element: null,\n isCached: !!props.cacheRequests && cacheStore.isCached(props.src),\n status: STATUS.IDLE,\n };\n\n this.hash = props.uniqueHash ?? randomString(8);\n }\n\n public componentDidMount(): void {\n this.isActive = true;\n\n if (!canUseDOM() || this.isInitialized) {\n return;\n }\n\n const { status } = this.state;\n const { src } = this.props;\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 this.load();\n }\n } catch (error: any) {\n this.handleError(error);\n }\n\n this.isInitialized = true;\n }\n\n public componentDidUpdate(previousProps: Props, previousState: State): void {\n if (!canUseDOM()) {\n return;\n }\n\n const { isCached, status } = this.state;\n const { description, onLoad, src, title } = this.props;\n\n if (previousState.status !== STATUS.READY && status === STATUS.READY) {\n if (onLoad) {\n onLoad(src, isCached);\n }\n }\n\n if (previousProps.src !== src) {\n if (!src) {\n this.handleError(new Error('Missing src'));\n\n return;\n }\n\n this.load();\n }\n\n if (previousProps.title !== title || previousProps.description !== description) {\n this.getElement();\n }\n }\n\n public componentWillUnmount(): void {\n this.isActive = false;\n }\n\n private fetchContent = async () => {\n const { fetchOptions, src } = this.props;\n\n const content: string = await request(src, fetchOptions);\n\n this.handleLoad(content);\n };\n\n private getElement() {\n try {\n const node = this.getNode() as Node;\n const element = convert(node);\n\n if (!element || !React.isValidElement(element)) {\n throw new Error('Could not convert the src to a React element');\n }\n\n this.setState({\n element,\n status: STATUS.READY,\n });\n } catch (error: any) {\n this.handleError(new Error(error.message));\n }\n }\n\n private getNode() {\n const { description, title } = this.props;\n\n try {\n const svgText = this.processSVG();\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 = this.updateSVGAttributes(node);\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 this.handleError(error);\n }\n }\n\n private handleError = (error: Error | FetchError) => {\n const { onError } = this.props;\n const status =\n error.message === 'Browser does not support SVG' ? STATUS.UNSUPPORTED : STATUS.FAILED;\n\n if (this.isActive) {\n this.setState({ status }, () => {\n if (typeof onError === 'function') {\n onError(error);\n }\n });\n }\n };\n\n private handleLoad = (content: string, hasCache = false) => {\n if (this.isActive) {\n this.setState(\n {\n content,\n isCached: hasCache,\n status: STATUS.LOADED,\n },\n this.getElement,\n );\n }\n };\n\n private load() {\n if (this.isActive) {\n this.setState(\n {\n content: '',\n element: null,\n isCached: false,\n status: STATUS.LOADING,\n },\n async () => {\n const { cacheRequests, fetchOptions, src } = this.props;\n\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 this.handleLoad(inlineSrc);\n\n return;\n }\n\n try {\n if (cacheRequests) {\n const content = await cacheStore.get(src, fetchOptions);\n\n this.handleLoad(content, true);\n } else {\n await this.fetchContent();\n }\n } catch (error: any) {\n this.handleError(error);\n }\n },\n );\n }\n }\n\n private processSVG() {\n const { content } = this.state;\n const { preProcessor } = this.props;\n\n if (preProcessor) {\n return preProcessor(content);\n }\n\n return content;\n }\n\n private updateSVGAttributes(node: SVGSVGElement): SVGSVGElement {\n const { baseURL = '', uniquifyIDs } = this.props;\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]}__${this.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}__${this.hash}`;\n }\n });\n }\n\n if (d.children.length) {\n return this.updateSVGAttributes(d as SVGSVGElement);\n }\n\n return d;\n });\n\n return node;\n }\n\n public render(): React.ReactNode {\n const { element, status } = this.state;\n const { children = null, innerRef, loader = null } = this.props;\n const elementProps = omit(\n this.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 React.cloneElement(element as React.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}\n\nexport default function InlineSVG(props: Props) {\n if (!cacheStore) {\n cacheStore = new CacheStore();\n }\n\n const { loader } = props;\n const hasCallback = React.useRef(false);\n const [isReady, setReady] = React.useState(cacheStore.isReady);\n\n React.useEffect(() => {\n if (!hasCallback.current) {\n cacheStore.onReady(() => {\n setReady(true);\n });\n\n hasCallback.current = true;\n }\n }, []);\n\n if (!isReady) {\n return loader;\n }\n\n return <ReactInlineSVG {...props} />;\n}\n\nexport * from './types';\n","export const CACHE_NAME = 'react-inlinesvg';\nexport const CACHE_MAX_RETRIES = 10;\n\nexport const STATUS = {\n IDLE: 'idle',\n LOADING: 'loading',\n LOADED: 'loaded',\n FAILED: 'failed',\n READY: 'ready',\n UNSUPPORTED: 'unsupported',\n} as const;\n","import type { PlainObject } from './types';\n\nexport function canUseDOM(): boolean {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\n\nexport async function request(url: string, options?: RequestInit) {\n const response = await fetch(url, options);\n const contentType = response.headers.get('content-type');\n const [fileType] = (contentType ?? '').split(/ ?; ?/);\n\n if (response.status > 299) {\n throw new Error('Not found');\n }\n\n if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {\n throw new Error(`Content type isn't valid: ${fileType}`);\n }\n\n return response.text();\n}\n\nexport function sleep(seconds = 1) {\n return new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n}\n\nexport function supportsInlineSVG(): boolean {\n /* c8 ignore next 3 */\n if (!document) {\n return false;\n }\n\n const div = document.createElement('div');\n\n div.innerHTML = '<svg />';\n const svg = div.firstChild as SVGSVGElement;\n\n return !!svg && svg.namespaceURI === 'http://www.w3.org/2000/svg';\n}\n\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function randomString(length: number): string {\n const letters = 'abcdefghijklmnopqrstuvwxyz';\n const numbers = '1234567890';\n const charset = `${letters}${letters.toUpperCase()}${numbers}`;\n\n let R = '';\n\n for (let index = 0; index < length; index++) {\n R += randomCharacter(charset);\n }\n\n return R;\n}\n\n/**\n * Remove properties from an object\n */\nexport function omit<T extends PlainObject, K extends keyof T>(\n input: T,\n ...filter: K[]\n): Omit<T, K> {\n const output: any = {};\n\n for (const key in input) {\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n }\n\n return output as Omit<T, K>;\n}\n","import { CACHE_MAX_RETRIES, CACHE_NAME, STATUS } from './config';\nimport { canUseDOM, request, sleep } from './helpers';\nimport { StorageItem } from './types';\n\nexport default class CacheStore {\n private cacheApi: Cache | undefined;\n private readonly cacheStore: Map<string, StorageItem>;\n private readonly subscribers: Array<() => void> = [];\n public isReady = false;\n\n constructor() {\n this.cacheStore = new Map<string, StorageItem>();\n\n let cacheName = CACHE_NAME;\n let usePersistentCache = false;\n\n if (canUseDOM()) {\n cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;\n usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE && 'caches' in window;\n }\n\n if (usePersistentCache) {\n caches\n .open(cacheName)\n .then(cache => {\n this.cacheApi = cache;\n this.isReady = true;\n\n this.subscribers.forEach(callback => callback());\n })\n .catch(error => {\n this.isReady = true;\n\n // eslint-disable-next-line no-console\n console.error(`Failed to open cache: ${error.message}`);\n });\n } else {\n this.isReady = true;\n }\n }\n\n public onReady(callback: () => void) {\n if (this.isReady) {\n callback();\n } else {\n this.subscribers.push(callback);\n }\n }\n\n public async get(url: string, fetchOptions?: RequestInit) {\n await (this.cacheApi\n ? this.fetchAndAddToPersistentCache(url, fetchOptions)\n : this.fetchAndAddToInternalCache(url, fetchOptions));\n\n return this.cacheStore.get(url)?.content ?? '';\n }\n\n public set(url: string, data: StorageItem) {\n this.cacheStore.set(url, data);\n }\n\n public isCached(url: string) {\n return this.cacheStore.get(url)?.status === STATUS.LOADED;\n }\n\n private async fetchAndAddToInternalCache(url: string, fetchOptions?: RequestInit) {\n const cache = this.cacheStore.get(url);\n\n if (cache?.status === STATUS.LOADING) {\n await this.handleLoading(url, async () => {\n this.cacheStore.set(url, { content: '', status: STATUS.IDLE });\n await this.fetchAndAddToInternalCache(url, fetchOptions);\n });\n\n return;\n }\n\n if (!cache?.content) {\n this.cacheStore.set(url, { content: '', status: STATUS.LOADING });\n\n try {\n const content = await request(url, fetchOptions);\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n } catch (error: any) {\n this.cacheStore.set(url, { content: '', status: STATUS.FAILED });\n throw error;\n }\n }\n }\n\n private async fetchAndAddToPersistentCache(url: string, fetchOptions?: RequestInit) {\n const cache = this.cacheStore.get(url);\n\n if (cache?.status === STATUS.LOADED) {\n return;\n }\n\n if (cache?.status === STATUS.LOADING) {\n await this.handleLoading(url, async () => {\n this.cacheStore.set(url, { content: '', status: STATUS.IDLE });\n await this.fetchAndAddToPersistentCache(url, fetchOptions);\n });\n\n return;\n }\n\n this.cacheStore.set(url, { content: '', status: STATUS.LOADING });\n\n const data = await this.cacheApi?.match(url);\n\n if (data) {\n const content = await data.text();\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n\n return;\n }\n\n try {\n await this.cacheApi?.add(new Request(url, fetchOptions));\n\n const response = await this.cacheApi?.match(url);\n const content = (await response?.text()) ?? '';\n\n this.cacheStore.set(url, { content, status: STATUS.LOADED });\n } catch (error: any) {\n this.cacheStore.set(url, { content: '', status: STATUS.FAILED });\n throw error;\n }\n }\n\n private async handleLoading(url: string, callback: () => Promise<void>) {\n let retryCount = 0;\n\n // eslint-disable-next-line no-await-in-loop\n while (this.cacheStore.get(url)?.status === STATUS.LOADING && retryCount < CACHE_MAX_RETRIES) {\n // eslint-disable-next-line no-await-in-loop\n await sleep(0.1);\n retryCount += 1;\n }\n\n if (retryCount >= CACHE_MAX_RETRIES) {\n await callback();\n }\n }\n\n public keys(): Array<string> {\n return [...this.cacheStore.keys()];\n }\n\n public data(): Array<Record<string, StorageItem>> {\n return [...this.cacheStore.entries()].map(([key, value]) => ({ [key]: value }));\n }\n\n public async delete(url: string) {\n if (this.cacheApi) {\n await this.cacheApi.delete(url);\n }\n\n this.cacheStore.delete(url);\n }\n\n public async clear() {\n if (this.cacheApi) {\n const keys = await this.cacheApi.keys();\n\n for (const key of keys) {\n // eslint-disable-next-line no-await-in-loop\n await this.cacheApi.delete(key);\n }\n }\n\n this.cacheStore.clear();\n }\n}\n"],"mappings":";;;;;;;;AAAA,YAAY,WAAW;AACvB,OAAO,aAAa;;;ACDb,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,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ACT;AAEA,WAAO;AAAA,EACT;AACF;AAxTE,cALI,gBAKU,gBAAe;AAAA,EAC3B,eAAe;AAAA,EACf,aAAa;AACf;AAuTa,SAAR,UAA2B,OAAc;AAC9C,MAAI,CAAC,YAAY;AACf,iBAAa,IAAI,WAAW;AAAA,EAC9B;AAEA,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,cAAoB,aAAO,KAAK;AACtC,QAAM,CAAC,SAAS,QAAQ,IAAU,eAAS,WAAW,OAAO;AAE7D,EAAM,gBAAU,MAAM;AACpB,QAAI,CAAC,YAAY,SAAS;AACxB,iBAAW,QAAQ,MAAM;AACvB,iBAAS,IAAI;AAAA,MACf,CAAC;AAED,kBAAY,UAAU;AAAA,IACxB;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAEA,SAAO,oBAAC,kBAAgB,GAAG,OAAO;AACpC;","names":[]}
|
package/dist/provider.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/provider.tsx","../src/helpers.ts"],"sourcesContent":["import { JSX } from 'react';\n\nimport { canUseDOM } from './helpers';\n\ninterface Props {\n children: JSX.Element;\n name?: string;\n}\n\nexport default function CacheProvider({ children, name }: Props) {\n if (canUseDOM()) {\n window.REACT_INLINESVG_CACHE_NAME = name;\n window.REACT_INLINESVG_PERSISTENT_CACHE = true;\n }\n\n return children;\n}\n","import type { PlainObject } from './types';\n\nexport function canUseDOM(): boolean {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\n\nexport async function request(url: string, options?: RequestInit) {\n const response = await fetch(url, options);\n const contentType = response.headers.get('content-type');\n const [fileType] = (contentType ?? '').split(/ ?; ?/);\n\n if (response.status > 299) {\n throw new Error('Not found');\n }\n\n if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {\n throw new Error(`Content type isn't valid: ${fileType}`);\n }\n\n return response.text();\n}\n\nexport function sleep(seconds = 1) {\n return new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n}\n\nexport function supportsInlineSVG(): boolean {\n /*
|
|
1
|
+
{"version":3,"sources":["../src/provider.tsx","../src/helpers.ts"],"sourcesContent":["import { JSX } from 'react';\n\nimport { canUseDOM } from './helpers';\n\ninterface Props {\n children: JSX.Element;\n name?: string;\n}\n\nexport default function CacheProvider({ children, name }: Props) {\n if (canUseDOM()) {\n window.REACT_INLINESVG_CACHE_NAME = name;\n window.REACT_INLINESVG_PERSISTENT_CACHE = true;\n }\n\n return children;\n}\n","import type { PlainObject } from './types';\n\nexport function canUseDOM(): boolean {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\n\nexport async function request(url: string, options?: RequestInit) {\n const response = await fetch(url, options);\n const contentType = response.headers.get('content-type');\n const [fileType] = (contentType ?? '').split(/ ?; ?/);\n\n if (response.status > 299) {\n throw new Error('Not found');\n }\n\n if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {\n throw new Error(`Content type isn't valid: ${fileType}`);\n }\n\n return response.text();\n}\n\nexport function sleep(seconds = 1) {\n return new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n}\n\nexport function supportsInlineSVG(): boolean {\n /* c8 ignore next 3 */\n if (!document) {\n return false;\n }\n\n const div = document.createElement('div');\n\n div.innerHTML = '<svg />';\n const svg = div.firstChild as SVGSVGElement;\n\n return !!svg && svg.namespaceURI === 'http://www.w3.org/2000/svg';\n}\n\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function randomString(length: number): string {\n const letters = 'abcdefghijklmnopqrstuvwxyz';\n const numbers = '1234567890';\n const charset = `${letters}${letters.toUpperCase()}${numbers}`;\n\n let R = '';\n\n for (let index = 0; index < length; index++) {\n R += randomCharacter(charset);\n }\n\n return R;\n}\n\n/**\n * Remove properties from an object\n */\nexport function omit<T extends PlainObject, K extends keyof T>(\n input: T,\n ...filter: K[]\n): Omit<T, K> {\n const output: any = {};\n\n for (const key in input) {\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n }\n\n return output as Omit<T, K>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,SAAS,YAAqB;AACnC,SAAO,CAAC,EAAE,OAAO,WAAW,eAAe,OAAO,YAAY,OAAO,SAAS;AAChF;;;ADKe,SAAR,cAA+B,EAAE,UAAU,KAAK,GAAU;AAC/D,MAAI,UAAU,GAAG;AACf,WAAO,6BAA6B;AACpC,WAAO,mCAAmC;AAAA,EAC5C;AAEA,SAAO;AACT;","names":[]}
|
package/dist/provider.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/helpers.ts","../src/provider.tsx"],"sourcesContent":["import type { PlainObject } from './types';\n\nexport function canUseDOM(): boolean {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\n\nexport async function request(url: string, options?: RequestInit) {\n const response = await fetch(url, options);\n const contentType = response.headers.get('content-type');\n const [fileType] = (contentType ?? '').split(/ ?; ?/);\n\n if (response.status > 299) {\n throw new Error('Not found');\n }\n\n if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {\n throw new Error(`Content type isn't valid: ${fileType}`);\n }\n\n return response.text();\n}\n\nexport function sleep(seconds = 1) {\n return new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n}\n\nexport function supportsInlineSVG(): boolean {\n /*
|
|
1
|
+
{"version":3,"sources":["../src/helpers.ts","../src/provider.tsx"],"sourcesContent":["import type { PlainObject } from './types';\n\nexport function canUseDOM(): boolean {\n return !!(typeof window !== 'undefined' && window.document && window.document.createElement);\n}\n\nexport function isSupportedEnvironment(): boolean {\n return supportsInlineSVG() && typeof window !== 'undefined' && window !== null;\n}\n\nexport async function request(url: string, options?: RequestInit) {\n const response = await fetch(url, options);\n const contentType = response.headers.get('content-type');\n const [fileType] = (contentType ?? '').split(/ ?; ?/);\n\n if (response.status > 299) {\n throw new Error('Not found');\n }\n\n if (!['image/svg+xml', 'text/plain'].some(d => fileType.includes(d))) {\n throw new Error(`Content type isn't valid: ${fileType}`);\n }\n\n return response.text();\n}\n\nexport function sleep(seconds = 1) {\n return new Promise(resolve => {\n setTimeout(resolve, seconds * 1000);\n });\n}\n\nexport function supportsInlineSVG(): boolean {\n /* c8 ignore next 3 */\n if (!document) {\n return false;\n }\n\n const div = document.createElement('div');\n\n div.innerHTML = '<svg />';\n const svg = div.firstChild as SVGSVGElement;\n\n return !!svg && svg.namespaceURI === 'http://www.w3.org/2000/svg';\n}\n\nfunction randomCharacter(character: string) {\n return character[Math.floor(Math.random() * character.length)];\n}\n\nexport function randomString(length: number): string {\n const letters = 'abcdefghijklmnopqrstuvwxyz';\n const numbers = '1234567890';\n const charset = `${letters}${letters.toUpperCase()}${numbers}`;\n\n let R = '';\n\n for (let index = 0; index < length; index++) {\n R += randomCharacter(charset);\n }\n\n return R;\n}\n\n/**\n * Remove properties from an object\n */\nexport function omit<T extends PlainObject, K extends keyof T>(\n input: T,\n ...filter: K[]\n): Omit<T, K> {\n const output: any = {};\n\n for (const key in input) {\n if ({}.hasOwnProperty.call(input, key)) {\n if (!filter.includes(key as unknown as K)) {\n output[key] = input[key];\n }\n }\n }\n\n return output as Omit<T, K>;\n}\n","import { JSX } from 'react';\n\nimport { canUseDOM } from './helpers';\n\ninterface Props {\n children: JSX.Element;\n name?: string;\n}\n\nexport default function CacheProvider({ children, name }: Props) {\n if (canUseDOM()) {\n window.REACT_INLINESVG_CACHE_NAME = name;\n window.REACT_INLINESVG_PERSISTENT_CACHE = true;\n }\n\n return children;\n}\n"],"mappings":";AAEO,SAAS,YAAqB;AACnC,SAAO,CAAC,EAAE,OAAO,WAAW,eAAe,OAAO,YAAY,OAAO,SAAS;AAChF;;;ACKe,SAAR,cAA+B,EAAE,UAAU,KAAK,GAAU;AAC/D,MAAI,UAAU,GAAG;AACf,WAAO,6BAA6B;AACpC,WAAO,mCAAmC;AAAA,EAC5C;AAEA,SAAO;AACT;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-inlinesvg",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.6",
|
|
4
4
|
"description": "An SVG loader for React",
|
|
5
5
|
"author": "Gil Barbara <gilbarbara@gmail.com>",
|
|
6
6
|
"contributors": [
|
|
@@ -59,47 +59,43 @@
|
|
|
59
59
|
"@gilbarbara/prettier-config": "^1.0.0",
|
|
60
60
|
"@gilbarbara/tsconfig": "^0.2.3",
|
|
61
61
|
"@size-limit/preset-small-lib": "^9.0.0",
|
|
62
|
-
"@testing-library/jest-dom": "^6.1.
|
|
62
|
+
"@testing-library/jest-dom": "^6.1.4",
|
|
63
63
|
"@testing-library/react": "^14.0.0",
|
|
64
64
|
"@types/exenv": "^1.2.0",
|
|
65
65
|
"@types/fetch-mock": "^7.3.6",
|
|
66
|
-
"@types/jest": "^29.5.5",
|
|
67
66
|
"@types/node": "^20.8.2",
|
|
68
67
|
"@types/node-fetch": "^2.6.6",
|
|
69
68
|
"@types/react": "^18.2.24",
|
|
70
69
|
"@types/react-dom": "^18.2.8",
|
|
70
|
+
"@vitest/coverage-v8": "^0.34.6",
|
|
71
71
|
"browser-cache-mock": "^0.1.7",
|
|
72
|
-
"cross-fetch": "^4.0.0",
|
|
73
72
|
"del-cli": "^5.1.0",
|
|
74
73
|
"fix-tsup-cjs": "^1.2.0",
|
|
75
74
|
"http-server": "^14.1.1",
|
|
76
75
|
"husky": "^8.0.3",
|
|
77
|
-
"jest": "^
|
|
78
|
-
"
|
|
79
|
-
"jest-extended": "^4.0.1",
|
|
80
|
-
"jest-fetch-mock": "^3.0.3",
|
|
81
|
-
"jest-serializer-html": "^7.1.0",
|
|
82
|
-
"jest-watch-typeahead": "^2.2.2",
|
|
76
|
+
"jest-extended": "^4.0.2",
|
|
77
|
+
"jsdom": "^22.1.0",
|
|
83
78
|
"react": "^18.2.0",
|
|
84
79
|
"react-dom": "^18.2.0",
|
|
85
80
|
"repo-tools": "^0.2.2",
|
|
86
81
|
"size-limit": "^9.0.0",
|
|
87
82
|
"start-server-and-test": "^2.0.1",
|
|
88
|
-
"ts-jest": "^29.1.1",
|
|
89
83
|
"ts-node": "^10.9.1",
|
|
90
84
|
"tsup": "^7.2.0",
|
|
91
|
-
"typescript": "^5.2.2"
|
|
85
|
+
"typescript": "^5.2.2",
|
|
86
|
+
"vitest": "^0.34.6",
|
|
87
|
+
"vitest-fetch-mock": "^0.2.2"
|
|
92
88
|
},
|
|
93
89
|
"scripts": {
|
|
94
90
|
"build": "pnpm run clean && tsup && fix-tsup-cjs",
|
|
95
91
|
"watch": "tsup --watch",
|
|
96
92
|
"clean": "del dist/*",
|
|
97
|
-
"start": "http-server test/__fixtures__ -p 1337 --cors",
|
|
98
93
|
"lint": "eslint src test",
|
|
94
|
+
"start": "http-server test/__fixtures__ -p 1337 --cors",
|
|
99
95
|
"test": "start-server-and-test start http://127.0.0.1:1337 test:coverage",
|
|
100
|
-
"test:coverage": "
|
|
101
|
-
"test:watch": "
|
|
102
|
-
"typecheck": "tsc
|
|
96
|
+
"test:coverage": "vitest run --coverage",
|
|
97
|
+
"test:watch": "vitest watch",
|
|
98
|
+
"typecheck": "tsc -p test/tsconfig.json",
|
|
103
99
|
"size": "size-limit",
|
|
104
100
|
"validate": "pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run build && pnpm run size",
|
|
105
101
|
"format": "prettier \"**/*.{js,jsx,json,yml,yaml,css,less,scss,ts,tsx,md,graphql,mdx}\" --write",
|
|
@@ -142,12 +138,12 @@
|
|
|
142
138
|
{
|
|
143
139
|
"name": "commonjs",
|
|
144
140
|
"path": "./dist/index.js",
|
|
145
|
-
"limit": "
|
|
141
|
+
"limit": "10 KB"
|
|
146
142
|
},
|
|
147
143
|
{
|
|
148
144
|
"name": "esm",
|
|
149
145
|
"path": "./dist/index.mjs",
|
|
150
|
-
"limit": "
|
|
146
|
+
"limit": "10 KB"
|
|
151
147
|
}
|
|
152
148
|
]
|
|
153
149
|
}
|
package/src/cache.ts
CHANGED
|
@@ -16,16 +16,24 @@ export default class CacheStore {
|
|
|
16
16
|
|
|
17
17
|
if (canUseDOM()) {
|
|
18
18
|
cacheName = window.REACT_INLINESVG_CACHE_NAME ?? CACHE_NAME;
|
|
19
|
-
usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE;
|
|
19
|
+
usePersistentCache = !!window.REACT_INLINESVG_PERSISTENT_CACHE && 'caches' in window;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
if (usePersistentCache) {
|
|
23
|
-
caches
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
23
|
+
caches
|
|
24
|
+
.open(cacheName)
|
|
25
|
+
.then(cache => {
|
|
26
|
+
this.cacheApi = cache;
|
|
27
|
+
this.isReady = true;
|
|
28
|
+
|
|
29
|
+
this.subscribers.forEach(callback => callback());
|
|
30
|
+
})
|
|
31
|
+
.catch(error => {
|
|
32
|
+
this.isReady = true;
|
|
33
|
+
|
|
34
|
+
// eslint-disable-next-line no-console
|
|
35
|
+
console.error(`Failed to open cache: ${error.message}`);
|
|
36
|
+
});
|
|
29
37
|
} else {
|
|
30
38
|
this.isReady = true;
|
|
31
39
|
}
|
package/src/helpers.ts
CHANGED
|
@@ -31,7 +31,7 @@ export function sleep(seconds = 1) {
|
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
export function supportsInlineSVG(): boolean {
|
|
34
|
-
/*
|
|
34
|
+
/* c8 ignore next 3 */
|
|
35
35
|
if (!document) {
|
|
36
36
|
return false;
|
|
37
37
|
}
|
|
@@ -72,7 +72,6 @@ export function omit<T extends PlainObject, K extends keyof T>(
|
|
|
72
72
|
const output: any = {};
|
|
73
73
|
|
|
74
74
|
for (const key in input) {
|
|
75
|
-
/* istanbul ignore else */
|
|
76
75
|
if ({}.hasOwnProperty.call(input, key)) {
|
|
77
76
|
if (!filter.includes(key as unknown as K)) {
|
|
78
77
|
output[key] = input[key];
|
package/src/index.tsx
CHANGED
|
@@ -43,14 +43,11 @@ class ReactInlineSVG extends React.PureComponent<Props, State> {
|
|
|
43
43
|
const { src } = this.props;
|
|
44
44
|
|
|
45
45
|
try {
|
|
46
|
-
/* istanbul ignore else */
|
|
47
46
|
if (status === STATUS.IDLE) {
|
|
48
|
-
/* istanbul ignore else */
|
|
49
47
|
if (!isSupportedEnvironment()) {
|
|
50
48
|
throw new Error('Browser does not support SVG');
|
|
51
49
|
}
|
|
52
50
|
|
|
53
|
-
/* istanbul ignore else */
|
|
54
51
|
if (!src) {
|
|
55
52
|
throw new Error('Missing src');
|
|
56
53
|
}
|
|
@@ -73,7 +70,6 @@ class ReactInlineSVG extends React.PureComponent<Props, State> {
|
|
|
73
70
|
const { description, onLoad, src, title } = this.props;
|
|
74
71
|
|
|
75
72
|
if (previousState.status !== STATUS.READY && status === STATUS.READY) {
|
|
76
|
-
/* istanbul ignore else */
|
|
77
73
|
if (onLoad) {
|
|
78
74
|
onLoad(src, isCached);
|
|
79
75
|
}
|
|
@@ -176,10 +172,8 @@ class ReactInlineSVG extends React.PureComponent<Props, State> {
|
|
|
176
172
|
const status =
|
|
177
173
|
error.message === 'Browser does not support SVG' ? STATUS.UNSUPPORTED : STATUS.FAILED;
|
|
178
174
|
|
|
179
|
-
/* istanbul ignore else */
|
|
180
175
|
if (this.isActive) {
|
|
181
176
|
this.setState({ status }, () => {
|
|
182
|
-
/* istanbul ignore else */
|
|
183
177
|
if (typeof onError === 'function') {
|
|
184
178
|
onError(error);
|
|
185
179
|
}
|
|
@@ -188,7 +182,6 @@ class ReactInlineSVG extends React.PureComponent<Props, State> {
|
|
|
188
182
|
};
|
|
189
183
|
|
|
190
184
|
private handleLoad = (content: string, hasCache = false) => {
|
|
191
|
-
/* istanbul ignore else */
|
|
192
185
|
if (this.isActive) {
|
|
193
186
|
this.setState(
|
|
194
187
|
{
|
|
@@ -202,7 +195,6 @@ class ReactInlineSVG extends React.PureComponent<Props, State> {
|
|
|
202
195
|
};
|
|
203
196
|
|
|
204
197
|
private load() {
|
|
205
|
-
/* istanbul ignore else */
|
|
206
198
|
if (this.isActive) {
|
|
207
199
|
this.setState(
|
|
208
200
|
{
|