2
0
mirror of https://github.com/iconify/iconify.git synced 2024-11-13 00:06:29 +00:00

chore: add option to add svg and xlink xml namespaces

This commit is contained in:
Joaquín Sánchez Jiménez 2022-02-26 17:20:16 +01:00
parent 7b5ccb13b6
commit 1e854f74ee
4 changed files with 23 additions and 12 deletions

View File

@ -41,6 +41,7 @@ export async function getCustomIcon(
collection, collection,
icon, icon,
additionalProps, additionalProps,
options?.addXmlNs === true,
undefined, undefined,
iconCustomizer, iconCustomizer,
); );

View File

@ -38,6 +38,7 @@ export async function searchForIcon(
collection, collection,
id, id,
additionalProps, additionalProps,
options?.addXmlNs === true,
() => attributes, () => attributes,
iconCustomizer iconCustomizer
); );

View File

@ -76,9 +76,14 @@ export type CustomCollections = Record<
*/ */
export type IconifyLoaderOptions = { export type IconifyLoaderOptions = {
/** /**
* Scale of icons against 1em * Add svg and xlink xml namespace when necessary.
* *
* @default 1.2 * @default false
*/
addXmlNs?: boolean
/**
* Scale of icons against 1em
*/ */
scale?: number scale?: number

View File

@ -8,6 +8,7 @@ export async function mergeIconProps(
collection: string, collection: string,
icon: string, icon: string,
additionalProps: Record<string, string | undefined>, additionalProps: Record<string, string | undefined>,
addXmlNs: boolean,
propsProvider?: () => Awaitable<Record<string, string>>, propsProvider?: () => Awaitable<Record<string, string>>,
iconCustomizer?: IconCustomizer, iconCustomizer?: IconCustomizer,
): Promise<string> { ): Promise<string> {
@ -17,17 +18,20 @@ export async function mergeIconProps(
const v = additionalProps[p]; const v = additionalProps[p];
if (v !== undefined && v !== null) props[p] = v; if (v !== undefined && v !== null) props[p] = v;
}); });
// add svg xmlns if missing // add xml namespaces if necessary
if (!svg.includes(' xmlns=') && !additionalProps['xmlns']) { if (addXmlNs) {
additionalProps['xmlns'] = 'http://www.w3.org/2000/svg'; // add svg xmlns if missing
if (!svg.includes(' xmlns=') && !props['xmlns']) {
props['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:') && !props['xmlns:xlink']) {
props['xmlns:xlink'] = 'http://www.w3.org/1999/xlink';
}
} }
// 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';
}
const replacement = svg.startsWith('<svg ') ? '<svg ' : '<svg';
return svg.replace( return svg.replace(
replacement, '<svg ',
`${replacement}${Object.keys(props).map((p) => `${p}="${props[p]}"`).join(' ')}` `<svg ${Object.keys(props).map((p) => `${p}="${props[p]}"`).join(' ')}`
); );
} }