laurentpayot / minidenticons

Super lightweight SVG identicon (pixelated avatar) generator
https://laurentpayot.github.io/minidenticons
MIT License
401 stars 18 forks source link

Svelte component example #10

Open Joshimello opened 3 weeks ago

Joshimello commented 3 weeks ago

Awesome library! Just wanted to share a component method for anyone using svelte :D Only the username prop is required.

Component:

<script lang="ts">
  import { minidenticon } from "minidenticons"

  export let username: string
  export let saturation: number = 95
  export let lightness: number = 45

  $: svgURI = 
    'data:image/svg+xml;utf8,' + 
    encodeURIComponent(minidenticon(username, saturation, lightness))

</script>

<img
  src={svgURI} 
  alt={username} 
  {...$$restProps}  
/>

Example usage with class props:

<Minidenticon username={USERNAME} class="h-12 w-12" />
laurentpayot commented 3 weeks ago

Thanks @Joshimello! I’d love to add your example to the readme, but if I’m right Svelte 5 will be released soon with the new "runes" syntax that makes $: svgURI = ... and other stuff obsolete. Last time I used Svelte it was still in version 3 so I’m not a Svelte expert :wink: Do you think you could rewrite your example with the new runes syntax?

Joshimello commented 3 weeks ago

Sure! No problem!

Heres a typed version

<script lang="ts">
  import { minidenticon } from "minidenticons"

  let { 
    username,
    saturation = 95,
    lightness = 45,
    ...others
  } : {
    username: string,
    saturation?: number | string,
    lightness?: number | string,
    [key: string]: any
  } = $props()

  let svgURI: string = $derived(
    'data:image/svg+xml;utf8,' +
    encodeURIComponent(minidenticon(username, saturation, lightness))
  )

</script>

<img
  src={svgURI} 
  alt={username} 
  {...others}
/>

And an untyped version


<script>
  import { minidenticon } from "minidenticons"

  let { 
    username,
    saturation = 95,
    lightness = 45,
    ...others
  } = $props()

  let svgURI = $derived(
    'data:image/svg+xml;utf8,' +
    encodeURIComponent(minidenticon(username, saturation, lightness))
  )

</script>

<img
  src={svgURI} 
  alt={username} 
  {...others}
/>
laurentpayot commented 3 weeks ago

Thanks again @Joshimello :+1: I will probably add this in the docs in not too distant future. Hopefully before Svelte 6 is released :wink: