Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(icon): load base64 data urls #1172

Merged
merged 9 commits into from
Feb 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 6 additions & 25 deletions src/components/icon/icon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import { Build, Component, Element, Host, Prop, State, Watch, h } from '@stencil
import { getSvgContent, ioniconContent } from './request';
import { getName, getUrl, inheritAttributes, isRTL } from './utils';

let parser: DOMParser;

@Component({
tag: 'ion-icon',
assetsDirs: ['svg'],
Expand Down Expand Up @@ -82,7 +80,7 @@ export class Icon {
* @default true
*/
@Prop() sanitize = true;

componentWillLoad() {
this.inheritedAttributes = inheritAttributes(this.el, ['aria-label']);
}
Expand Down Expand Up @@ -124,12 +122,12 @@ export class Icon {
cb();
}
}

private hasAriaHidden = () => {
const { el } = this;

return el.hasAttribute('aria-hidden') && el.getAttribute('aria-hidden') === 'true';
}
};

@Watch('name')
@Watch('src')
Expand All @@ -138,35 +136,20 @@ export class Icon {
@Watch('md')
loadIcon() {
if (Build.isBrowser && this.isVisible) {
if (!parser) {
/**
* Create an instance of the DOM parser. This creates a single
* parser instance for the entire app, which is more efficient.
*/
parser = new DOMParser();
}
const url = getUrl(this);

if (url) {
if (ioniconContent.has(url)) {
// sync if it's already loaded
this.svgContent = ioniconContent.get(url);
} else if (url.startsWith('data:')) {
const doc = parser.parseFromString(url, 'text/html');
const svgEl = doc.body.querySelector('svg');
if (svgEl !== null) {
this.svgContent = svgEl.outerHTML;
} else {
this.svgContent = '';
}
} else {
// async if it hasn't been loaded
getSvgContent(url, this.sanitize).then(() => (this.svgContent = ioniconContent.get(url)));
}
}
}

const label = this.iconName = getName(this.name, this.icon, this.mode, this.ios, this.md);
const label = (this.iconName = getName(this.name, this.icon, this.mode, this.ios, this.md));

/**
* Come up with a default label
Expand All @@ -182,9 +165,7 @@ export class Icon {
const mode = this.mode || 'md';
const flipRtl =
this.flipRtl ||
(iconName &&
(iconName.indexOf('arrow') > -1 || iconName.indexOf('chevron') > -1) &&
this.flipRtl !== false);
(iconName && (iconName.indexOf('arrow') > -1 || iconName.indexOf('chevron') > -1) && this.flipRtl !== false);

/**
* Only set the aria-label if a) we have generated
Expand Down
50 changes: 36 additions & 14 deletions src/components/icon/request.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,51 @@
import { validateContent } from './validate';
import { isEncodedDataUrl, isSvgDataUrl, validateContent } from './validate';

export const ioniconContent = new Map<string, string>();
const requests = new Map<string, Promise<any>>();

let parser = new DOMParser();

export const getSvgContent = (url: string, sanitize: boolean) => {
// see if we already have a request for this url
let req = requests.get(url);

if (!req) {
if (typeof fetch !== 'undefined' && typeof document !== 'undefined') {
// we don't already have a request
req = fetch(url).then((rsp) => {
if (rsp.ok) {
return rsp.text().then((svgContent) => {
if (svgContent && sanitize !== false) {
svgContent = validateContent(svgContent);
}
ioniconContent.set(url, svgContent || '');
});
/**
* If the url is a data url of an svg, then try to parse it
* with the DOMParser. This works with content security policies enabled.
*/
if (isSvgDataUrl(url) && isEncodedDataUrl(url)) {
if (!parser) {
/**
* Create an instance of the DOM parser. This creates a single
* parser instance for the entire app, which is more efficient.
*/
parser = new DOMParser();
}
const doc = parser.parseFromString(url, 'text/html');
const svg = doc.querySelector('svg');
if (svg) {
ioniconContent.set(url, svg.outerHTML);
}
ioniconContent.set(url, '');
});
return Promise.resolve();
} else {
// we don't already have a request
req = fetch(url).then((rsp) => {
if (rsp.ok) {
return rsp.text().then((svgContent) => {
if (svgContent && sanitize !== false) {
svgContent = validateContent(svgContent);
}
ioniconContent.set(url, svgContent || '');
});
}
ioniconContent.set(url, '');
});
// cache for the same requests
requests.set(url, req);
}

// cache for the same requests
requests.set(url, req);
} else {
// set to empty for ssr scenarios and resolve promise
ioniconContent.set(url, '');
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
32 changes: 25 additions & 7 deletions src/components/icon/test/validate.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isValid } from '../validate';
import { isEncodedDataUrl, isSvgDataUrl, isValid } from '../validate';


describe('isValid', () => {
Expand All @@ -24,9 +24,11 @@ describe('isValid', () => {
});

it('invalid child SCRIPT elm', () => {
const el = { nodeType: 1, nodeName: 'svg', attributes: [], childNodes: [
{ nodeType: 1, nodeName: 'SCRIPT', attributes: [], childNodes: [] }
] } as any;
const el = {
nodeType: 1, nodeName: 'svg', attributes: [], childNodes: [
{ nodeType: 1, nodeName: 'SCRIPT', attributes: [], childNodes: [] }
]
} as any;
expect(isValid(el)).toBe(false);
});

Expand All @@ -41,9 +43,11 @@ describe('isValid', () => {
});

it('is valid SVG elm', () => {
const el = { nodeType: 1, nodeName: 'SVG', attributes: [], childNodes: [
{ nodeType: 1, nodeName: 'line', attributes: [], childNodes: [] }
] } as any;
const el = {
nodeType: 1, nodeName: 'SVG', attributes: [], childNodes: [
{ nodeType: 1, nodeName: 'line', attributes: [], childNodes: [] }
]
} as any;
expect(isValid(el)).toBe(true);
});

Expand All @@ -53,3 +57,17 @@ describe('isValid', () => {
});

});

it('isSvgDataUrl', () => {
expect(isSvgDataUrl('data:image/svg+xml;base64,xxx')).toBe(true);
expect(isSvgDataUrl('data:image/svg+xml;utf8,<svg></svg>')).toBe(true);
expect(isSvgDataUrl('https://example.com/icon.svg')).toBe(false);
expect(isSvgDataUrl('http://example.com/icon.svg')).toBe(false);
});

it('isEncodedDataUrl', () => {
expect(isEncodedDataUrl('data:image/svg+xml;base64,xxx')).toBe(false);
expect(isEncodedDataUrl('data:image/svg+xml;utf8,<svg></svg>')).toBe(true);
expect(isEncodedDataUrl('https://example.com/icon.svg')).toBe(false);
expect(isEncodedDataUrl('http://example.com/icon.svg')).toBe(false);
});
3 changes: 3 additions & 0 deletions src/components/icon/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
4 changes: 4 additions & 0 deletions src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,10 @@ <h2>Sanitized (shouldn't show)</h2>
<h2>Not Sanitized (should show)</h2>
<ion-icon sanitize="false" src="./assets/no-sanitize.svg"></ion-icon>

<h2>Base64 url</h2>
<ion-icon
src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBmaWxsPSJub25lIiBkPSJNMCAwaDI0djI0SDBWMHoiLz48cGF0aCBkPSJNMjAgMkg0Yy0xLjEgMC0yIC45LTIgMnYxOGw0LTRoMTRjMS4xIDAgMi0uOSAyLTJWNGMwLTEuMS0uOS0yLTItMnptMCAxNEg2bC0yIDJWNGgxNnYxMnoiLz48L3N2Zz4="></ion-icon>

<p>
<a href="./cheatsheet.html">Cheatsheet</a>
</p>
Expand Down