Created
August 17, 2024 18:54
-
-
Save ashnel3/c837aa3cabcfb944ed5000c30788d778 to your computer and use it in GitHub Desktop.
inline-svg w/ no dependencies in astro.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
export interface Props { | |
raw: string | |
title: string | |
class?: string | |
width?: number | |
height?: number | |
viewBox?: string | |
xmlns?: string | |
} | |
const { class: classNames, title, width, height, viewBox, xmlns, raw } = Astro.props | |
// parse svg | |
if (!raw.startsWith('<svg ')) { | |
throw new Error('invalid svg image data!') | |
} | |
const atribs: Record<string, string> = Array.from( | |
raw.substring(raw.indexOf('<svg ') + 5, raw.indexOf('>')).matchAll(/([\w-]+)="([^"]+)"/g), | |
).reduce((acc, [_full, k, v]) => ({ ...acc, [k]: v }), {}) | |
const paths = Astro.props.raw.match(/<path\s[^>]+\s?\/>/g) ?? [] | |
--- | |
<svg | |
set:html={paths.join('')} | |
class={classNames} | |
width={width} | |
height={height} | |
viewBox={viewBox ?? atribs.viewBox} | |
xmlns={xmlns ?? atribs.xmlns} | |
> | |
<title>{title}</title> | |
<slot /> | |
</svg> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment