posthtml / posthtml-webp

Add webp supporting in your html
MIT License
6 stars 7 forks source link

Handle images already wrapped within a picture element #22

Open dmnsgn opened 3 years ago

dmnsgn commented 3 years ago

Is there any way the plugin could detect the parent node of the image for a <picture> element and:

Current behaviour

Input:

<picture>
  <source type="image/avif" srcset="images/my-image.avif 1x, images/my-image@2x.avif 2x">
  <img srcset="images/my-image.jpg 1x, images/my-image@2x.jpg 2x" alt="">
</picture>

Output:

<picture>
  <source type="image/avif" srcset="images/my-image.avif 1x, images/my-image@2x.avif 2x">
  <picture>
    <source type="image/webp" srcset="images/my-image.webp 1x, images/my-image@2x.webp 2x">
    <img srcset="images/my-image.jpg 1x, images/my-image@2x.jpg 2x" alt="">
  </picture>
</picture>

Expected behaviour

<picture>
  <source type="image/avif" srcset="images/my-image.avif 1x, images/my-image@2x.avif 2x">
  <source type="image/webp" srcset="images/my-image.webp 1x, images/my-image@2x.webp 2x">
  <img srcset="images/my-image.jpg 1x, images/my-image@2x.jpg 2x" alt="">
</picture>

Use case

This could also be useful when several different plugin are trying to add sources to a picture.

Thanks

Scrum commented 3 years ago

To do this, initially you need to go through all <picture> and look at the presence in it <source>. For example, you can add any attribute to such parents that means that it already contains <source>.

I think it would be better to make it a separate plugin !!! since this is beyond the logic of this plugin

dmnsgn commented 3 years ago

I see, the logic is a bit different indeed. Are there any documentation on parsing the html ast tree, parent and children nodes? Or is it just a cascade of tree.match ?

Scrum commented 3 years ago

Or is it just a cascade of tree.match ?

yep

ausir0726 commented 1 year ago

same problem here... I have some img use pictrue tag for meida query but plugin break it.

<picture>
  <source srcset="./images/index/cover-1-4k.jpg" media="(min-width: 2000px)">
  <source srcset="./images/index/photo-banner-mobile-1.jpg" media="(max-width: 767px)">
  <picture>
    <source type="image/webp" srcset="./images/index/cover-1-2k.jpg.webp">
    <img class="absolute left-0 top-0 w-full h-full object-cover object-center" src="./images/index/cover-1-2k.jpg">
  </picture>
</picture>