Skip to content

Instantly share code, notes, and snippets.

@ashnel3
Created August 17, 2024 18:54
Show Gist options
  • Save ashnel3/c837aa3cabcfb944ed5000c30788d778 to your computer and use it in GitHub Desktop.
Save ashnel3/c837aa3cabcfb944ed5000c30788d778 to your computer and use it in GitHub Desktop.
inline-svg w/ no dependencies in astro.
---
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