asciidoctor/asciidoctor.js

Adding srcset attr to an image block

benjaminleonard opened this issue · 3 comments

I'm working on a responsive image component extension – as we're using asciidoc for our blog. What I can't figure out is how to apply srcset and have it stick. It lets me update alt and src through target but srcset doesn't persist.

const src = isProd
  ? {
      target: small,
      srcset: `${small} 640w, ${medium} 1080w, ${large} 1920w`,
      sizes: '100vw',
    }
  : { target }

return this.createImageBlock(parent, { ...attrs, ...src })

Any ideas on how I can apply an attribute that isn't src or alt?

Thanks!

You should extend the built-in HTML5 converter and more specifically override the convert_image method:

https://github.com/asciidoctor/asciidoctor/blob/75350c4ad7d6401f95308b0ade391e5895fff44d/lib/asciidoctor/converter/html5.rb#L626-L657

As you can see, the built-in HTML 5 converter does not set the HTML attributes srcset nor sizes. An Asciidoctor attribute is not equivalent to an HTML attribute but in your extended converter you can do something like:

const target = node.getAttribute('target')
if (target.endsWith('.svg')) {
  return this.baseConverter.convert(node, transform)
}
const role = node.getRole()
return `<div class="imageblock${role ? ' ' + role : ''}">
  <img srcset="${node.getAttribute('srcset')}" sizes="${node.getAttribute('sizes')}" src="${node.getImageUri(target)}" alt="${encodeAttributeValue(node.getAlt())}"/>
</div>`

In the future, please ask usage questions about Asciidoctor.js in the #users/asciidoctor.js stream of the project chat at chat.asciidoctor.org. The issue tracker is reserved for reporting confirmed bugs and new feature proposals. Thanks!

I can follow-up in the project chat to help you get started.

Thank you! Working perfectly now. Good to know about the project chat

Perfect, feel free to join the community chat if have any additional questions 🤗