2
0
mirror of https://github.com/iconify/iconify.git synced 2024-11-09 23:00:56 +00:00

chore: auto fixed prettier rules in src and tests

npx eslint --fix src/**/*.ts
npx eslint --fix tests/**/*.ts
This commit is contained in:
Ramy Melo 2022-03-04 11:37:21 -05:00
parent 30826c33e0
commit 8f739807d5
10 changed files with 103 additions and 64 deletions

View File

@ -1,5 +1,9 @@
import createDebugger from 'debug'; import createDebugger from 'debug';
import type { CustomIconLoader, IconifyLoaderOptions, InlineCollection } from './types'; import type {
CustomIconLoader,
IconifyLoaderOptions,
InlineCollection,
} from './types';
import { mergeIconProps } from './utils'; import { mergeIconProps } from './utils';
const debug = createDebugger('@iconify-loader:custom'); const debug = createDebugger('@iconify-loader:custom');
@ -11,7 +15,7 @@ export async function getCustomIcon(
custom: CustomIconLoader | InlineCollection, custom: CustomIconLoader | InlineCollection,
collection: string, collection: string,
icon: string, icon: string,
options?: IconifyLoaderOptions, options?: IconifyLoaderOptions
): Promise<string | undefined> { ): Promise<string | undefined> {
let result: string | undefined | null; let result: string | undefined | null;
@ -37,7 +41,7 @@ export async function getCustomIcon(
collection, collection,
icon, icon,
options, options,
undefined, undefined
); );
} }
} }

View File

@ -1,12 +1,15 @@
import { promises as fs, Stats } from 'fs'; import { promises as fs, Stats } from 'fs';
import { isPackageExists, resolveModule } from 'local-pkg' import { isPackageExists, resolveModule } from 'local-pkg';
import type { IconifyJSON } from '@iconify/types' import type { IconifyJSON } from '@iconify/types';
import { tryInstallPkg } from './install-pkg'; import { tryInstallPkg } from './install-pkg';
const _collections: Record<string, Promise<IconifyJSON | undefined>> = {}; const _collections: Record<string, Promise<IconifyJSON | undefined>> = {};
const isLegacyExists = isPackageExists('@iconify/json'); const isLegacyExists = isPackageExists('@iconify/json');
export async function loadCollectionFromFS(name: string, autoInstall = false): Promise<IconifyJSON | undefined> { export async function loadCollectionFromFS(
name: string,
autoInstall = false
): Promise<IconifyJSON | undefined> {
if (!_collections[name]) { if (!_collections[name]) {
_collections[name] = task(); _collections[name] = task();
} }
@ -30,9 +33,10 @@ export async function loadCollectionFromFS(name: string, autoInstall = false): P
return undefined; return undefined;
} }
if (stat && stat.isFile()) { if (stat && stat.isFile()) {
return JSON.parse(await fs.readFile(jsonPath as string, 'utf8')) as IconifyJSON; return JSON.parse(
} await fs.readFile(jsonPath as string, 'utf8')
else { ) as IconifyJSON;
} else {
return undefined; return undefined;
} }
} }

View File

@ -3,7 +3,7 @@ import { searchForIcon } from './modern';
import { warnOnce } from './install-pkg'; import { warnOnce } from './install-pkg';
import type { IconifyLoaderOptions } from './types'; import type { IconifyLoaderOptions } from './types';
export const isNode = typeof process < 'u' && typeof process.stdout < 'u' export const isNode = typeof process < 'u' && typeof process.stdout < 'u';
export async function loadIcon( export async function loadIcon(
collection: string, collection: string,
@ -33,8 +33,7 @@ async function importFsModule(): Promise<typeof import('./fs') | undefined> {
try { try {
// cjs environments // cjs environments
return require('./fs.js'); return require('./fs.js');
} } catch {
catch {
return undefined; return undefined;
} }
} }
@ -44,12 +43,15 @@ async function loadNodeBuiltinIcon(
collection: string, collection: string,
icon: string, icon: string,
options?: IconifyLoaderOptions, options?: IconifyLoaderOptions,
warn = true, warn = true
): Promise<string | undefined> { ): Promise<string | undefined> {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore // @ts-ignore
const { loadCollectionFromFS } = await importFsModule(); const { loadCollectionFromFS } = await importFsModule();
const iconSet = await loadCollectionFromFS(collection, options?.autoInstall); const iconSet = await loadCollectionFromFS(
collection,
options?.autoInstall
);
if (iconSet) { if (iconSet) {
// possible icon names // possible icon names
const ids = [ const ids = [
@ -61,7 +63,8 @@ async function loadNodeBuiltinIcon(
} }
if (warn) { if (warn) {
warnOnce(`failed to load \`@iconify-json/${collection}\`, have you installed it?`); warnOnce(
`failed to load \`@iconify-json/${collection}\`, have you installed it?`
);
} }
} }

View File

@ -13,7 +13,7 @@ export async function searchForIcon(
iconSet: IconifyJSON, iconSet: IconifyJSON,
collection: string, collection: string,
ids: string[], ids: string[],
options?: IconifyLoaderOptions, options?: IconifyLoaderOptions
): Promise<string | undefined> { ): Promise<string | undefined> {
let iconData: FullIconifyIcon | null; let iconData: FullIconifyIcon | null;
const { customize } = options?.customizations ?? {}; const { customize } = options?.customizations ?? {};
@ -34,7 +34,7 @@ export async function searchForIcon(
collection, collection,
id, id,
options, options,
() => attributes, () => attributes
); );
} }
} }

View File

@ -80,36 +80,36 @@ export type IconifyLoaderOptions = {
* *
* @default false * @default false
*/ */
addXmlNs?: boolean addXmlNs?: boolean;
/** /**
* Scale of icons against 1em * Scale of icons against 1em
*/ */
scale?: number scale?: number;
/** /**
* Style to apply to icons by default * Style to apply to icons by default
* *
* @default '' * @default ''
*/ */
defaultStyle?: string defaultStyle?: string;
/** /**
* Class names to apply to icons by default * Class names to apply to icons by default
* *
* @default '' * @default ''
*/ */
defaultClass?: string defaultClass?: string;
/** /**
* Loader for custom loaders * Loader for custom loaders
*/ */
customCollections?: Record<string, CustomIconLoader | InlineCollection> customCollections?: Record<string, CustomIconLoader | InlineCollection>;
/** /**
* Icon customizer * Icon customizer
*/ */
customizations?: IconCustomizations customizations?: IconCustomizations;
/** /**
* Auto install icon sources package when the usages is detected * Auto install icon sources package when the usages is detected
@ -118,5 +118,5 @@ export type IconifyLoaderOptions = {
* *
* @default false * @default false
*/ */
autoInstall?: boolean autoInstall?: boolean;
} };

View File

@ -6,16 +6,21 @@ export async function mergeIconProps(
collection: string, collection: string,
icon: string, icon: string,
options?: IconifyLoaderOptions, options?: IconifyLoaderOptions,
propsProvider?: () => Awaitable<Record<string, string>>, propsProvider?: () => Awaitable<Record<string, string>>
): Promise<string> { ): Promise<string> {
const { scale, addXmlNs = false } = options ?? {} const { scale, addXmlNs = false } = options ?? {};
const { const { additionalProps = {}, iconCustomizer } =
additionalProps = {}, options?.customizations ?? {};
iconCustomizer,
} = options?.customizations ?? {};
const props: Record<string, string> = (await propsProvider?.()) ?? {}; const props: Record<string, string> = (await propsProvider?.()) ?? {};
if (!svg.includes(" width=") && !svg.includes(" height=") && typeof scale === 'number') { if (
if ((typeof props.width === 'undefined' || props.width === null) && (typeof props.height === 'undefined' || props.height === null)) { !svg.includes(' width=') &&
!svg.includes(' height=') &&
typeof scale === 'number'
) {
if (
(typeof props.width === 'undefined' || props.width === null) &&
(typeof props.height === 'undefined' || props.height === null)
) {
props.width = `${scale}em`; props.width = `${scale}em`;
props.height = `${scale}em`; props.height = `${scale}em`;
} }
@ -33,18 +38,24 @@ export async function mergeIconProps(
props['xmlns'] = 'http://www.w3.org/2000/svg'; props['xmlns'] = 'http://www.w3.org/2000/svg';
} }
// add xmlns:xlink if xlink present and the xmlns missing // add xmlns:xlink if xlink present and the xmlns missing
if (!svg.includes(' xmlns:xlink=') && svg.includes('xlink:') && !props['xmlns:xlink']) { if (
!svg.includes(' xmlns:xlink=') &&
svg.includes('xlink:') &&
!props['xmlns:xlink']
) {
props['xmlns:xlink'] = 'http://www.w3.org/1999/xlink'; props['xmlns:xlink'] = 'http://www.w3.org/1999/xlink';
} }
} }
svg = svg.replace( svg = svg.replace(
'<svg ', '<svg ',
`<svg ${Object.keys(props).map((p) => `${p}="${props[p]}"`).join(' ')}` `<svg ${Object.keys(props)
.map((p) => `${p}="${props[p]}"`)
.join(' ')}`
); );
if (svg && options) { if (svg && options) {
const { defaultStyle, defaultClass } = options const { defaultStyle, defaultClass } = options;
// additional props and iconCustomizer takes precedence // additional props and iconCustomizer takes precedence
if (defaultClass && !svg.includes(' class=')) { if (defaultClass && !svg.includes(' class=')) {
svg = svg.replace('<svg ', `<svg class="${defaultClass}" `); svg = svg.replace('<svg ', `<svg class="${defaultClass}" `);

View File

@ -2,12 +2,19 @@
export function encodeSvgForCss(svg: string): string { export function encodeSvgForCss(svg: string): string {
let useSvg = svg.startsWith('<svg>') ? svg.replace('<svg>', '<svg >') : svg; let useSvg = svg.startsWith('<svg>') ? svg.replace('<svg>', '<svg >') : svg;
if (!useSvg.includes(' xmlns:xlink=') && useSvg.includes(' xlink:')) { if (!useSvg.includes(' xmlns:xlink=') && useSvg.includes(' xlink:')) {
useSvg = useSvg.replace('<svg ', '<svg xmlns:xlink="http://www.w3.org/1999/xlink" '); useSvg = useSvg.replace(
'<svg ',
'<svg xmlns:xlink="http://www.w3.org/1999/xlink" '
);
} }
if (!useSvg.includes(' xmlns=')) { if (!useSvg.includes(' xmlns=')) {
useSvg = useSvg.replace('<svg ', '<svg xmlns="http://www.w3.org/2000/svg" '); useSvg = useSvg.replace(
'<svg ',
'<svg xmlns="http://www.w3.org/2000/svg" '
);
} }
return useSvg.replace(/"/g, '\'') return useSvg
.replace(/"/g, "'")
.replace(/%/g, '%25') .replace(/%/g, '%25')
.replace(/#/g, '%23') .replace(/#/g, '%23')
.replace(/{/g, '%7B') .replace(/{/g, '%7B')

View File

@ -15,9 +15,12 @@ describe('Testing getCustomIcon', () => {
const result = await getCustomIcon(() => svg, 'a', 'b', { const result = await getCustomIcon(() => svg, 'a', 'b', {
customizations: { customizations: {
transform(icon) { transform(icon) {
return icon.replace('<svg ', '<svg width="1em" height="1em" '); return icon.replace(
'<svg ',
'<svg width="1em" height="1em" '
);
}, },
} },
}); });
expect(result && result.indexOf('width="1em"') > -1).toBeTruthy(); expect(result && result.indexOf('width="1em"') > -1).toBeTruthy();
expect(result && result.indexOf('height="1em"') > -1).toBeTruthy(); expect(result && result.indexOf('height="1em"') > -1).toBeTruthy();

View File

@ -1,16 +1,17 @@
import { loadIcon } from '../lib'; import { loadIcon } from '../lib';
describe('Testing loadIcon with @iconify-json/flat-color-icons>', () => { describe('Testing loadIcon with @iconify-json/flat-color-icons>', () => {
test('loadIcon works', async () => { test('loadIcon works', async () => {
const result = await loadIcon('flat-color-icons', 'up-right'); const result = await loadIcon('flat-color-icons', 'up-right');
expect(result).toBeTruthy(); expect(result).toBeTruthy();
}); });
test('loadIcon adds xmlns:xlink', async () => { test('loadIcon adds xmlns:xlink', async () => {
const result = await loadIcon('flat-color-icons', 'up-right', { addXmlNs: true }); const result = await loadIcon('flat-color-icons', 'up-right', {
addXmlNs: true,
});
expect(result).toBeTruthy(); expect(result).toBeTruthy();
expect(result && result.indexOf('xmlns:xlink=') > - 1).toBeTruthy(); expect(result && result.indexOf('xmlns:xlink=') > -1).toBeTruthy();
}); });
test('loadIcon with customize with default style and class', async () => { test('loadIcon with customize with default style and class', async () => {
@ -23,13 +24,13 @@ describe('Testing loadIcon with @iconify-json/flat-color-icons>', () => {
props.height = '2em'; props.height = '2em';
return props; return props;
}, },
} },
}); });
expect(result).toBeTruthy(); expect(result).toBeTruthy();
expect(result && result.indexOf('margin-top: 1rem;') > - 1).toBeTruthy(); expect(result && result.indexOf('margin-top: 1rem;') > -1).toBeTruthy();
expect(result && result.indexOf('class="clazz"') > - 1).toBeTruthy(); expect(result && result.indexOf('class="clazz"') > -1).toBeTruthy();
expect(result && result.indexOf('width="2em"') > - 1).toBeTruthy(); expect(result && result.indexOf('width="2em"') > -1).toBeTruthy();
expect(result && result.indexOf('height="2em"') > - 1).toBeTruthy(); expect(result && result.indexOf('height="2em"') > -1).toBeTruthy();
}); });
test('loadIcon preserves customizations order', async () => { test('loadIcon preserves customizations order', async () => {
@ -39,16 +40,19 @@ describe('Testing loadIcon with @iconify-json/flat-color-icons>', () => {
defaultClass: 'clazz1', defaultClass: 'clazz1',
customizations: { customizations: {
additionalProps: { additionalProps: {
'width': '2em', width: '2em',
'height': '2em', height: '2em',
'style': 'color: blue;', style: 'color: blue;',
'class': 'clazz2', class: 'clazz2',
}, },
// it will never be called, it is not a custom icon // it will never be called, it is not a custom icon
transform(icon) { transform(icon) {
return icon.replace('<svg ', '<svg width="4em" height="4em" '); return icon.replace(
'<svg ',
'<svg width="4em" height="4em" '
);
}, },
} },
}); });
expect(result).toBeTruthy(); expect(result).toBeTruthy();
expect(result && result.includes('style="color: blue;"')).toBeTruthy(); expect(result && result.includes('style="color: blue;"')).toBeTruthy();

View File

@ -3,9 +3,9 @@ import { CustomIconLoader, loadIcon } from '../lib';
const fixturesDir = __dirname + '/fixtures'; const fixturesDir = __dirname + '/fixtures';
const loader: CustomIconLoader = async(name) => { const loader: CustomIconLoader = async (name) => {
return await fs.readFile(`${fixturesDir}/${name}.svg`, 'utf8'); return await fs.readFile(`${fixturesDir}/${name}.svg`, 'utf8');
} };
describe('Testing loadIcon', () => { describe('Testing loadIcon', () => {
test('CustomCollection', async () => { test('CustomCollection', async () => {
@ -13,8 +13,8 @@ describe('Testing loadIcon', () => {
expect(svg).toBeTruthy(); expect(svg).toBeTruthy();
const result = await loadIcon('a', 'circle', { const result = await loadIcon('a', 'circle', {
customCollections: { customCollections: {
'a': { a: {
'circle': svg as string, circle: svg as string,
}, },
}, },
}); });
@ -27,13 +27,16 @@ describe('Testing loadIcon', () => {
expect(svg).toBeTruthy(); expect(svg).toBeTruthy();
const result = await loadIcon('a', 'circle', { const result = await loadIcon('a', 'circle', {
customCollections: { customCollections: {
'a': { a: {
'circle': svg as string, circle: svg as string,
}, },
}, },
customizations: { customizations: {
transform(icon) { transform(icon) {
return icon.replace('<svg ', '<svg width="1em" height="1em" '); return icon.replace(
'<svg ',
'<svg width="1em" height="1em" '
);
}, },
}, },
}); });
@ -55,7 +58,7 @@ describe('Testing loadIcon', () => {
const result = await loadIcon('a', '1f3eb', { const result = await loadIcon('a', '1f3eb', {
customCollections: { customCollections: {
'a': { a: {
'1f3eb': svg as string, '1f3eb': svg as string,
}, },
}, },