2022-02-26 14:12:13 +00:00
|
|
|
import type { Awaitable } from '@antfu/utils';
|
2022-01-10 12:43:35 +00:00
|
|
|
import type { IconCustomizer } from './types';
|
2021-12-09 21:12:00 +00:00
|
|
|
|
2022-02-26 14:12:13 +00:00
|
|
|
export const isNode = typeof process < 'u' && typeof process.stdout < 'u'
|
2021-12-09 21:12:00 +00:00
|
|
|
|
2022-01-10 12:43:35 +00:00
|
|
|
export async function mergeIconProps(
|
|
|
|
svg: string,
|
|
|
|
collection: string,
|
|
|
|
icon: string,
|
|
|
|
additionalProps: Record<string, string | undefined>,
|
|
|
|
propsProvider?: () => Awaitable<Record<string, string>>,
|
2022-02-26 15:27:20 +00:00
|
|
|
iconCustomizer?: IconCustomizer,
|
2022-01-10 12:43:35 +00:00
|
|
|
): Promise<string> {
|
2022-02-26 15:44:24 +00:00
|
|
|
const props: Record<string, string> = (await propsProvider?.()) ?? {};
|
2022-01-10 16:08:40 +00:00
|
|
|
await iconCustomizer?.(collection, icon, props);
|
2022-01-10 12:43:35 +00:00
|
|
|
Object.keys(additionalProps).forEach((p) => {
|
2022-01-10 16:08:40 +00:00
|
|
|
const v = additionalProps[p];
|
|
|
|
if (v !== undefined && v !== null) props[p] = v;
|
|
|
|
});
|
2022-02-26 14:12:13 +00:00
|
|
|
// add svg xmlns if missing
|
|
|
|
if (!svg.includes(' xmlns=') && !additionalProps['xmlns']) {
|
|
|
|
additionalProps['xmlns'] = 'http://www.w3.org/2000/svg';
|
|
|
|
}
|
|
|
|
// add xmlns:xlink if xlink present and the xmlns missing
|
|
|
|
if (!svg.includes('xmlns:xlink') && svg.includes('xlink:') && !additionalProps['xmlns:xlink']) {
|
|
|
|
additionalProps['xmlns:xlink'] = 'http://www.w3.org/1999/xlink';
|
|
|
|
}
|
2022-01-10 16:08:40 +00:00
|
|
|
const replacement = svg.startsWith('<svg ') ? '<svg ' : '<svg';
|
|
|
|
return svg.replace(
|
|
|
|
replacement,
|
2022-02-26 14:12:13 +00:00
|
|
|
`${replacement}${Object.keys(props).map((p) => `${p}="${props[p]}"`).join(' ')}`
|
2022-01-10 16:08:40 +00:00
|
|
|
);
|
2022-01-10 12:43:35 +00:00
|
|
|
}
|