2022-02-26 14:12:13 +00:00
|
|
|
import { getCustomIcon } from './custom';
|
|
|
|
import { searchForIcon } from './modern';
|
|
|
|
import { warnOnce } from './install-pkg';
|
|
|
|
import type { IconifyLoaderOptions } from './types';
|
|
|
|
|
2022-03-04 16:37:21 +00:00
|
|
|
export const isNode = typeof process < 'u' && typeof process.stdout < 'u';
|
2022-02-26 16:49:13 +00:00
|
|
|
|
2022-02-26 14:12:13 +00:00
|
|
|
export async function loadIcon(
|
|
|
|
collection: string,
|
|
|
|
icon: string,
|
|
|
|
options?: IconifyLoaderOptions
|
|
|
|
): Promise<string | undefined> {
|
|
|
|
const custom = options?.customCollections?.[collection];
|
|
|
|
|
|
|
|
if (custom) {
|
|
|
|
const result = await getCustomIcon(custom, collection, icon, options);
|
|
|
|
if (result) {
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-26 16:49:13 +00:00
|
|
|
if (!isNode) {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
|
2022-02-26 17:31:45 +00:00
|
|
|
return await loadNodeBuiltinIcon(collection, icon, options);
|
2022-02-26 14:12:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function importFsModule(): Promise<typeof import('./fs') | undefined> {
|
|
|
|
try {
|
|
|
|
return await import('./fs');
|
|
|
|
} catch {
|
|
|
|
try {
|
|
|
|
// cjs environments
|
|
|
|
return require('./fs.js');
|
2022-03-04 16:37:21 +00:00
|
|
|
} catch {
|
2022-02-26 14:12:13 +00:00
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async function loadNodeBuiltinIcon(
|
|
|
|
collection: string,
|
|
|
|
icon: string,
|
|
|
|
options?: IconifyLoaderOptions,
|
2022-03-04 16:37:21 +00:00
|
|
|
warn = true
|
2022-02-26 14:12:13 +00:00
|
|
|
): Promise<string | undefined> {
|
2022-02-26 16:49:13 +00:00
|
|
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
|
|
// @ts-ignore
|
|
|
|
const { loadCollectionFromFS } = await importFsModule();
|
2022-03-04 16:37:21 +00:00
|
|
|
const iconSet = await loadCollectionFromFS(
|
|
|
|
collection,
|
|
|
|
options?.autoInstall
|
|
|
|
);
|
2022-02-26 16:49:13 +00:00
|
|
|
if (iconSet) {
|
|
|
|
// possible icon names
|
|
|
|
const ids = [
|
|
|
|
icon,
|
|
|
|
icon.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(),
|
|
|
|
icon.replace(/([a-z])(\d+)/g, '$1-$2'),
|
|
|
|
];
|
|
|
|
return await searchForIcon(iconSet, collection, ids, options);
|
|
|
|
}
|
2022-02-26 14:12:13 +00:00
|
|
|
|
2022-02-26 16:49:13 +00:00
|
|
|
if (warn) {
|
2022-03-04 16:37:21 +00:00
|
|
|
warnOnce(
|
|
|
|
`failed to load \`@iconify-json/${collection}\`, have you installed it?`
|
|
|
|
);
|
2022-02-26 14:12:13 +00:00
|
|
|
}
|
|
|
|
}
|