gatsby-uc / plugins

Monorepo for plugins in the Gatsby User Collective.
https://gatsbyuc.dev
MIT License
59 stars 34 forks source link

feat(gatsby-source-strapi): Transform markdown images in-place #422

Open Undistraction opened 1 year ago

Undistraction commented 1 year ago

Is your feature request related to a problem? Please describe.

Usually (when using remark with local markdown files), if an image is encountered in the markdown, gatsby-remark-images transforms that image into html that can then be rendered using GatsbyImage.

For example if the following is encountered in markdown:

[Example alt](../../../static/uploads/example.png)

When I query using htmlAst I get a node back representing the <img> as a picture tag with full sourceset etc. his contains all the necessary formats to be picked up and transformed into a <GatsbyImage />.

However for images inside Markdown content from Strapi, no transformation takes place, and the AST node looks like this. This makes sense as gatsby-remark-images doesn't handle images with remote URLs:

This is an example of an un-replaced image tag in the htmlAst:

 {
  "type": "element",
  "tagName": "img",
  "properties": {
      "src": "/uploads/example_large_3c066db0fa.png",
      "alt": "Example",
      ...
   }
}

This plugin does add a medias node to the markdown field which stores data about the images parsed out of the markdown, but the actual images within the markdown are not updated.

Describe the solution you'd like

I'd like to see images in markdown transformed in-place, as happens to images in markdown for local markdown files. I think the simplest way to do this is to swap out the image URLs with the URLs of the downloaded images.

Describe alternatives you've considered

I don't see any alternative here. The image paths need to be local so that gatsby-remark-images can parse them into the relevant tags.

Undistraction commented 1 year ago

Note that I've had a pretty good look through the source. On first glance it looked like it would be easy to do as part of of the file download which already uses createRemoteFileNode to download the remote image files to the local filesystem. I was thinking it would just be a matter of walking back through the relevant markdown and switching out the remote path for the new local path. However, although the new local publicURL fields are exposed on medias items via GraphQL, this happens though a resolver and no information about the local path is stored on the file nodes that are returned by createRemoteFileNode, so I can't see any way of getting this value in the JS.

There is a PR related to this topic here that was never merged, then another discussion here which provides a solution to swap out the image at point of use. This latter suggestion appears to be what was implemented. However I think replacing the URLs in the markdown is a much more intuitive solution.