RafidMuhymin / astro-imagetools

Image Optimization tools for the Astro JS framework
astro-imagetools-docs.vercel.app
MIT License
400 stars 45 forks source link

I created a Svelte Img component #144

Open silveltman opened 1 year ago

silveltman commented 1 year ago

🎉 I created a svelte Img component 🎉

How to use

Use the renderImg() APIin a parent .Astro component/page/layout, to get the html for the img. Then pass the html as a prop to the component.

Advantages of this component

It allows you to set attributes directly on the component, instead of via the API. This means you can set classes and sizes in you svelte components, instead of the parent .Astro component/page/layout.

I think this is great because those 2 attributes are depended on the design.

As for the src and alt, I personally don't mind having to set these in the .Astro component/page/layout. I have all my website in markdown files anyway, since that integrates best with my git-based CMS (CloudCannon)

Any tips?

Please let me know :)

Parent.astro

---
import { renderImg } from 'astro-imagetools/api'
import Img from '@components/imagetools/Img.svelte'

const { img } = await renderImg({
  src: 'https://picsum.photos/1024/768',
  alt: 'A random image',
})
---

  <Img {img}   />

Img.svelte

<script lang="ts">
  export let img: String
  // export let link: String
  // export let style: String

  let className = ''
  export { className as class }
  export let sizes: String = ''

  function findBetween(str, start, end) {
    const startIndex = str.indexOf(start) + start.length
    const endIndex = str.indexOf(end, startIndex)
    return str.substring(startIndex, endIndex)
  }

  function replace(attribute, value) {
    const currentValue = findBetween(img, `${attribute}="`, '"')
    img = img.replace(currentValue, value)
  }

  if (className) replace('class', className)
  if (sizes) replace('sizes', sizes)
</script>

{@html img}
guttenbergovitz commented 11 months ago

That's actually sort of clever.