2
0
mirror of https://github.com/iconify/iconify.git synced 2024-12-13 14:13:06 +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,
icon,
additionalProps,
options?.addXmlNs === true,
undefined,
iconCustomizer,
);

View File

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

View File

@ -76,9 +76,14 @@ export type CustomCollections = Record<
*/
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

View File

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