Skip to content

Commit ed9d3c1

Browse files
hyriousantfu
andauthored
feat: return shorter data url if possible (#326)
Co-authored-by: Anthony Fu <github@antfu.me>
1 parent 84c29f2 commit ed9d3c1

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

src/utils/icons.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { buildIcon, loadIcon } from 'iconify-icon'
2+
import { encodeSvgForCss } from '@iconify/utils'
23
import { getTransformedId } from '../store'
34
import Base64 from './base64'
45
import { HtmlToJSX } from './htmlToJsx'
@@ -211,6 +212,13 @@ export function ${name}(props) {
211212
return prettierCode(code, 'babel-ts')
212213
}
213214

215+
export function SvgToDataURL(svg: string) {
216+
const base64 = `data:image/svg+xml;base64,${Base64.encode(svg)}`
217+
const plain = `data:image/svg+xml,${encodeSvgForCss(svg)}`
218+
// Return the shorter of the two data URLs
219+
return base64.length < plain.length ? base64 : plain
220+
}
221+
214222
export async function getIconSnippet(icon: string, type: string, snippet = true, color = 'currentColor'): Promise<string | undefined> {
215223
if (!icon)
216224
return
@@ -235,7 +243,7 @@ export async function getIconSnippet(icon: string, type: string, snippet = true,
235243
case 'svg-symbol':
236244
return await getSvgSymbol(icon, '32', color)
237245
case 'data_url':
238-
return `data:image/svg+xml;base64,${Base64.encode(await getSvg(icon, undefined, color))}`
246+
return SvgToDataURL(await getSvg(icon, undefined, color))
239247
case 'pure-jsx':
240248
return ClearSvg(await getSvg(icon, undefined, color))
241249
case 'jsx':

0 commit comments

Comments
 (0)