diff --git a/src/components/pds-icon/request.ts b/src/components/pds-icon/request.ts index 0cbcd98..bb48ec1 100644 --- a/src/components/pds-icon/request.ts +++ b/src/components/pds-icon/request.ts @@ -1,31 +1,49 @@ -import { validateContent } from './validate'; +import { isEncodedDataUrl, isSvgDataUrl, validateContent } from './validate'; export const pdsIconContent = new Map(); const requests = new Map>(); // eslint-disable-line @typescript-eslint/no-explicit-any +let parser: DOMParser; + export const getSvgContent = (url: string, sanitize = false) => { let req = requests.get(url); if(!req) { if (typeof fetch != 'undefined' && typeof document !== 'undefined') { - // we don't have a request - req = fetch(url).then((rsp) => { - if (rsp.ok) { - return rsp.text().then((svgContent) => { - if (svgContent && sanitize !== false) { - svgContent = validateContent(svgContent); - } - pdsIconContent.set(url, svgContent || ''); - }); + if (isSvgDataUrl(url) && isEncodedDataUrl(url)) { + if (!parser) { + parser = new DOMParser(); + } + + const doc = parser.parseFromString(url, 'text/html'); + const svg = doc.querySelector('svg'); + + if (svg) { + pdsIconContent.set(url, svg.outerHTML); } - pdsIconContent.set(url, ''); - }); - requests.set(url, req); + return Promise.resolve(); + } else { + // we don't have a request + req = fetch(url).then((rsp) => { + if (rsp.ok) { + return rsp.text().then((svgContent) => { + if (svgContent && sanitize !== false) { + svgContent = validateContent(svgContent); + } + pdsIconContent.set(url, svgContent || ''); + }); + } + pdsIconContent.set(url, ''); + }); + + requests.set(url, req); + } } else { pdsIconContent.set(url, ''); return Promise.resolve(); } } + return req; } diff --git a/src/components/pds-icon/validate.ts b/src/components/pds-icon/validate.ts index 6452b9e..780eadc 100644 --- a/src/components/pds-icon/validate.ts +++ b/src/components/pds-icon/validate.ts @@ -15,7 +15,7 @@ export const validateContent = (svgContent: string) => { const svgElm = div.firstElementChild; if (svgElm && svgElm.nodeName.toLowerCase() === 'svg') { const svgClass = svgElm.getAttribute('class') || ''; - svgElm.setAttribute('class', (svgClass + ' s-ion-icon').trim()); + svgElm.setAttribute('class', (svgClass + ' s-pds-icon').trim()); // root element must be an svg // lets double check we've got valid elements @@ -48,3 +48,6 @@ export const isValid = (elm: HTMLElement) => { } return true; }; + +export const isSvgDataUrl = (url: string) => url.startsWith('data:image/svg+xml'); +export const isEncodedDataUrl = (url: string) => url.indexOf(';utf8,') !== -1;