Skip to content

Commit

Permalink
feat: add iconFontTypes to get all iconfont types
Browse files Browse the repository at this point in the history
use fetch to load scriptUrl and match all iconfont types
  • Loading branch information
mrlmx committed Feb 25, 2021
1 parent e4c3364 commit c035969
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion packages/icons-react/src/components/IconFont.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as React from 'react';
import Icon, { IconBaseProps } from './Icon';

const customCache = new Set<string>();
const iconFontTypes = new Set<string>();

export interface CustomIconOptions {
scriptUrl?: string | string[];
Expand All @@ -12,6 +13,13 @@ export interface IconFontProps extends IconBaseProps {
type: string;
}

interface CompoundedComponent
extends React.ForwardRefExoticComponent<
IconFontProps & React.RefAttributes<HTMLSpanElement>
> {
iconFontTypes: Set<string>;
}

function isValidCustomScriptUrl(scriptUrl: string): boolean {
return Boolean(
typeof scriptUrl === 'string'
Expand All @@ -20,6 +28,21 @@ function isValidCustomScriptUrl(scriptUrl: string): boolean {
);
}

function getIconFontTypes(scriptUrl: string): void {
try {
// will load scriptUrl form disk cache
fetch(scriptUrl)
.then((r) => r.text())
.then((result) => {
// Since Safari doesn't support trailing assertion, matchAll is used here. See here for details:https://stackoverflow.com/a/51568859
const matches = result.matchAll(/(?:<symbol id=")(\S*)(?=")/g);
[...matches].forEach((match) => iconFontTypes.add(match[1]))
});
} catch (e) {
console.log("iconfont types load failed", e);
}
}

function createScriptUrlElements(scriptUrls: string[], index: number = 0): void {
const currentScriptUrl = scriptUrls[index];
if (isValidCustomScriptUrl(currentScriptUrl)) {
Expand All @@ -28,6 +51,7 @@ function createScriptUrlElements(scriptUrls: string[], index: number = 0): void
script.setAttribute('data-namespace', currentScriptUrl);
if (scriptUrls.length > index + 1) {
script.onload = () => {
getIconFontTypes(currentScriptUrl);
createScriptUrlElements(scriptUrls, index + 1);
};
script.onerror = () => {
Expand Down Expand Up @@ -78,9 +102,10 @@ export default function create(options: CustomIconOptions = {}): React.SFC<IconF
{content}
</Icon>
);
});
}) as CompoundedComponent;

Iconfont.displayName = 'Iconfont';
Iconfont.iconFontTypes = iconFontTypes;

return Iconfont;
}

0 comments on commit c035969

Please sign in to comment.