Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(gatsby-remark-images): support markdownCaptions in mdx + fix for remark #21188

Merged
merged 7 commits into from Apr 22, 2020

Conversation

mathieudutour
Copy link
Contributor

@mathieudutour mathieudutour commented Feb 4, 2020

Description

Second part of #16574. In the previous PR, we pass down a compiler (in the gatsby-transformer-remark package) so that gatsby-remark plugins can use it to recursively parse a piece of content (in that case, the caption of an image). But when used in the gatsby-plugin-mdx, the remark plugins didn't get the compiler.
This PR fixes it.

Related Issues

Second part of #16574.
Fixes #14474 for the MDX case
Fixes #20000

@mathieudutour mathieudutour requested a review from a team as a code owner February 4, 2020 08:36
@mathieudutour
Copy link
Contributor Author

can't seem to be able to see why the build service failed

@mathieudutour mathieudutour requested a review from a team as a code owner April 16, 2020 13:12
@mathieudutour
Copy link
Contributor Author

we really should move this to TS. Happy to take on that if nobody started those packages yet

@vladar vladar self-assigned this Apr 16, 2020
@vladar
Copy link
Contributor

vladar commented Apr 16, 2020

Unfortunately, it didn't fix the #20000 issue. There is more about it:

async function getHTML(markdownNode) {
const shouldCache = markdownNode && markdownNode.internal
const cachedHTML =
shouldCache && (await cache.get(htmlCacheKey(markdownNode)))

As you see getHTML accepts Gatsby node, not markdown AST. So when you feed it with the result of parseString from here:

compiler: {
parseString: remark.parse.bind(remark),
generateHTML: getHTML,
},

It still fails with the same error:

UNHANDLED REJECTION Cannot read property 'contentDigest' of undefined

Because remark.parse returns AST and getHTML expects gatsby node. I think you actually need to change compiler in gatsby-transformer-remark to:

compiler: { 
  parseString: remark.parse.bind(remark), 
  generateHTML: ast => hastToHTML(toHAST(ast)), 
}

(then it all can stay sync?). But I didn't test it.

@mathieudutour
Copy link
Contributor Author

Oh you're right.

The issue with hastToHTML(toHAST(...)) is that you bypass all the remark plugins and the caches. So I'd be more tempted to change remark.parse.bind(remark) to something like

// returns a node-like object
(string) => ({
  internal: {
    contentDigest: digest(string),
    content: remark.parse(string)
  }
})

@vladar
Copy link
Contributor

vladar commented Apr 16, 2020

This looks like a hack that will one day shoot us in the foot (this happens more often than not).

Also how much benefit do we get from cache here? I doubt that it will be a significant boost (as far as I understand we don't have cache in MDX version anyway?)

If we still want cache we can just add a separate function similar to getHTML which will cache this (it should be simple enough to write).

Does it make sense?

@mathieudutour
Copy link
Contributor Author

It's mostly about the plugins and options for the users that would be ignored (might be really confusing if some part of the MD is parsed with some plugins while others aren't). I'm actually not too worried about the caches because the captions will always be small.

But I had it all wrong, not sure what I did last time. The issue is not about generateHTML but about parseString. Could you check my latest commit?

@vladar
Copy link
Contributor

vladar commented Apr 19, 2020

My best suggestion so far would be to exclude mutateSource part from parsing.

In other words, maybe worth extracting method parseString(string, markdownNode) from this piece:

const markdownAST = remark.parse(markdownNode.internal.content)
if (basePath) {
// Ensure relative links include `pathPrefix`
visit(markdownAST, [`link`, `definition`], node => {
if (
node.url &&
node.url.startsWith(`/`) &&
!node.url.startsWith(`//`)
) {
node.url = withPathPrefix(node.url, basePath)
}
})
}
if (process.env.NODE_ENV !== `production` || !fileNodes) {
fileNodes = getNodesByType(`File`)
}
// Use Bluebird's Promise function "each" to run remark plugins serially.
await Promise.each(pluginOptions.plugins, plugin => {
const requiredPlugin = require(plugin.resolve)
// Allow both exports = function(), and exports.default = function()
const defaultFunction = _.isFunction(requiredPlugin)
? requiredPlugin
: _.isFunction(requiredPlugin.default)
? requiredPlugin.default
: undefined
if (defaultFunction) {
return defaultFunction(
{
markdownAST,
markdownNode,
getNode,
files: fileNodes,
basePath,
reporter,
cache: getCache(plugin.name),
getCache,
compiler: {
parseString: remark.parse.bind(remark),
generateHTML: getHTML,
},
...rest,
},
plugin.pluginOptions
)
} else {
return Promise.resolve()
}
})
return markdownAST

And use this new method in both getMarkdownAST and in your compiler.parseString. Then mutateSource will be applied for the whole node once (in getMarkdownAST) and remark plugins will still work for captions parsing.

@pvdz
Copy link
Contributor

pvdz commented Apr 20, 2020

(You can ignore gatsby

@pvdz pvdz closed this Apr 20, 2020
@pvdz pvdz reopened this Apr 20, 2020
@pvdz
Copy link
Contributor

pvdz commented Apr 20, 2020

Sorry. I was going to say that you can ignore the "Gatsby Build Service" failures as they are unrelated to this PR and they are non-blocking. Then mid-way I managed to activate the close button :/ So anyways. Ignore those failures.

Co-authored-by: vladar
Copy link
Contributor

@vladar vladar left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, looks good to me now! Thanks for this work! Let's ship it 🚢

@vladar vladar changed the title pass compiler to gatsby-remark-* plugins in the mdx plugin feat(gatsby-remark-images): support markdownCaptions in mdx + fix for remark Apr 22, 2020
@vladar vladar added the bot: merge on green Gatsbot will merge these PRs automatically when all tests passes label Apr 22, 2020
@gatsbybot gatsbybot merged commit 82c05aa into master Apr 22, 2020
@delete-merged-branch delete-merged-branch bot deleted the f/pass-compiler-to-remark-plugins branch April 22, 2020 06:39
@vladar
Copy link
Contributor

vladar commented Apr 22, 2020

Published in:

  • gatsby-plugin-mdx@1.1.10
  • gatsby-remark-images@3.2.5
  • gatsby-transformer-remark@2.7.4

mxstbr added a commit that referenced this pull request Apr 22, 2020
* fix(gatsby): Throw error on default export in gatsby-ssr/brows… (#23133)

* fix: Handle default export case

* heh

* fix comment

* chore(release): Publish

 - gatsby-cli@2.11.12
 - gatsby-plugin-sitemap@2.3.5
 - gatsby-recipes@0.0.9
 - gatsby-remark-prismjs@3.4.4
 - gatsby-theme-blog-core@1.3.27
 - gatsby-theme-blog@1.4.27
 - gatsby-theme-notes@1.2.26
 - gatsby@2.20.26

* fix(docs): Using-MDX link (#23288)

* fix(docs): Link to apollo blog (#23290)

* fix(docs): change gatsby-config mention for global CSS import (#23245)

* fix `gatsby-config` mention

* chore: format

Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>

* docs: added details signifying that node fields can be arbitra… (#23106)

* added details signifying that node fields can be arbitrary

* Update docs/docs/data-fetching.md

Co-Authored-By: Kyle Gill <kylerobertgill@gmail.com>

* Update docs/docs/data-fetching.md

Co-Authored-By: Kyle Gill <kylerobertgill@gmail.com>

* removed empty line to fix failed linting tests

Co-Authored-By: Kyle Gill <kylerobertgill@gmail.com>

Co-authored-by: Kyle Gill <kylerobertgill@gmail.com>

* chore(gatsby): drop the the (#23295)

* chore(showcase): Add new sites built by Bejamas to showcase; c… (#23125)

* chore(sites): add new sites built by bejamas

* chore(creators): update bejamas cover

* chore(showcase):Add SofaScore Corporate web to showcase sites (#23128)

Co-authored-by: Mario Nikolaus <mario.nikolaus@sofascore.com>

* fix local links (#23149)

* chore(docs): Reference new ComponentModel component rather than generic LayerModel (#23241)

* Reference new ComponentModel component rather than generic LayerModel

* Remove use of t macro from layer models

* Half-fixing lingui code

* Revert "Half-fixing lingui code"

This reverts commit 64f052a.

* Remove Lingui from layer-model

* fix(www): fix sidebar (#23301)

* fix(www): fix sidebar

* Update sidebar.js

* fix(recipes): Fix shadow-file resource for scoped NPM packages & re-enable e2e testing for resources (#23274)

* fix(recipes): Fix shadow-file resource for scoped NPM packages

* WILL SLASH FIX WINDOWS???

* Add missing code block

* Try again

* hmmm joinPath maybe is the problem

* More fixes

* try reenabling tests

* disable colors in diffs

* Fix npm script test

* Why do these keep changing all the time??

* Use parsed value for the plan

* Disable Chalk colors on unit tests so match local ones

* Update packages/gatsby-recipes/src/providers/utils/get-diff.js

Co-Authored-By: John Otander <johnotander@gmail.com>

Co-authored-by: John Otander <johnotander@gmail.com>
Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>

* chore(release): Publish

 - gatsby-cli@2.11.13
 - gatsby-recipes@0.0.10
 - gatsby-theme-blog-core@1.3.28
 - gatsby-theme-blog@1.4.28
 - gatsby-theme-notes@1.2.27
 - gatsby@2.20.27

* chore(starters): add gatsby-starter-ecommerce (#23037)

* chore(starters): add gatsby-starter-ecommerce

* chore(starters): add gatsby-starter-ecommerce

Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>

* Add site Interficie Internet Services (#23130)

* Add site Interficie Internet Services

* Correct JavaScript cammelcase

* Prettier format

Co-authored-by: Obinna Ekwuno <obinnacodes@gmail.com>
Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>

* fix brand names (#23142)

* fix(blog): remove local domain (#23141)

* fix remove local domain

* fix local domain

* fix local domain

* fix remove local domain

* fix for linter

* Create paul scanlon 100 days of Gatsby blog post and add  assets (#23294)

* Create paul scanlon 100 days of Gatsby blog post and add  assets

* fix frontmatter

* fix frontmatter issue and ad relative links

* fix typos and spacing issues

* Update docs/blog/2020-04-20-paulie-scanlons-journey-of-100-days/index.md

Co-Authored-By: LB <laurie@gatsbyjs.com>

Co-authored-by: Laurie Barth <laurie@LauriesrkLaptop.fios-router.home>
Co-authored-by: LB <laurie@gatsbyjs.com>

* Clarify prefix-paths variable. (#23309)

The line (one line, two places) I'm editing was copied from a comment in #21627 without the surrounding context. This edit provides that context.

Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>

* chore(showcase):Add shreysachdeva.tech to showchase (#23032)

* Add shreysachdeva.tech to sites.yml

**Description**
Added the details of my personal website shreysachdeva.tech.

**Documentation**
No documentation

**Related Issues**
N/A

* chore: format

Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>
Co-authored-by: Obinna Ekwuno <obinnacodes@gmail.com>

* fix(www): Fix sidebar expansion behavior (#23325)

* [gatsby-plugin-manifest] Generate a 32x32 favicon instead of generating from first manifest icon (#23077)

* Decouple favicons from manifest icons

* Update packages/gatsby-plugin-manifest/README.md

* Replace include_favicon undefined check with nullish coalescing operator

Co-Authored-By: Alex Moon <moonmeister@users.noreply.github.com>

* Assert gatsby-plugin-manifest generates favicon PNG (unless include_favicon option is false)

* Don't mock createContentDigest in gatsby-plugin-manifest's gatsby-ssr tests (to be consistent with gatsby-node tests)

* Tweak a comment

Co-authored-by: LB <laurie@gatsbyjs.com>
Co-authored-by: Alex Moon <moonmeister@users.noreply.github.com>

* Use mutations in Gatsby Admin

* Remove stray console.logs

* chore(gatsby-recipes): Update README typo (#23333)

Fixed typo in README.md

* fix(gatsby): Check for files before delete action when using GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES (#23219)

* Check for files before delete action

* fix lint issues

* fix lint issues and add return type to checkFolderHasContent

* rename check function

Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>

* Install plugins as prod dependencies

* chore(release): Publish

 - gatsby-cli@2.11.14
 - gatsby-plugin-manifest@2.3.6
 - gatsby-recipes@0.0.11
 - gatsby-theme-blog-core@1.3.29
 - gatsby-theme-blog@1.4.29
 - gatsby-theme-notes@1.2.28
 - gatsby@2.20.28

* Add Besoegsvenner site to showcase (#23172)

* Add Besoegsvenner site to showcase

50.000 elderly people in Denmark feel lonely. This project seeks to inform people to become visitor friends ("Besøgsven" in Danish) to help fight loneliness and bring new friendships in to the world.

* Update sites.yml

Co-authored-by: Obinna Ekwuno <obinnacodes@gmail.com>
Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>

* chore(benchmarks): Add Drupal data updater script to update benchmark data (#23242)

* Add Drupal data updater script to update benchmark data

* Remove console.log statement

Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>

* Make TypeScript happy

* fix(gatsby): fix Uncaught TypeError in navigation.js (#23196)

* Add null check to address #21263

#21263 is an issue many people are arriving at for a variety of reasons.  Since the code contains this logic on the following line:

```
      if (pageHeadings && pageHeadings.length) {
```

There should be no issue in seeing if `document.getElementById(`gatsby-focus-wrapper`) exists first before attempting to look up `getElementsByTagName`.

* Update packages/gatsby/cache-dir/navigation.js

Co-Authored-By: Vladimir Razuvaev <vladimir.razuvaev@gmail.com>

* chore: format

Co-authored-by: Vladimir Razuvaev <vladimir.razuvaev@gmail.com>
Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>

* Add support for file argument in remark plugins for gatsby-plugin-mdx (#21489)

* chore(gatsby-cli) Migrate remaining files in reporters/logger/ink to Typscript (#22782)

* Migrate remaining files in gatsby-cli/reporters/logger/ink to TS

* Rename "IProps" to something more contextual
Extend interface parameter individually instead of using utility

* Clean up after merging the redux master changes

Co-authored-by: Blaine Kasten <blainekasten@gmail.com>

* Fix Drupal data update script (#23349)

* Add noop data update scripts for all benchmarks (#23352)

* Add noop data update scripts for all CMS benchmarks

* Add data update to remainder of benchmarks

* chore(babel-preset-gatsby): Convert dependencies to TS (#22038)

Co-authored-by: Blaine Kasten <blainekasten@gmail.com>

* fix(gatsby): Improve error message when calling useStaticQuery without graphql (#23189)

* Add warning message for a long queries (#23261)

* Add warning message for a long queries

* Change timeout to 15 seconds

* Replace console with report

* Print out queryJob.componentPath instead of page.internalComponentName

* Add new info in the warning message

Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>

* refactor(gatsby): Convert inference metadata to TypeScript (#23264)

* refactor(inference-metadata): Convert to TypeScript

* Remove unused variable

* Forgot some types

* refactor(type-conflict-reporter): Node description

After tightening the original util function to return a string only, it
seemed sensible to convert that to use nullish coalescing. At that
point, seeing the function is only used in a single place and not
exported, I inlined it.

* refactor(inference-metadata): Interface renaming

* fix: Extract ValueType type

* refactor: Change type from unknown to object

* Corrected types, but left the code alone

* Removed redundant comments

* Update README.md (#23357)

* feat(gatsby-remark-images): support markdownCaptions in mdx + fix for remark (#21188)

* pass compiler to gatsby-remark-* plugins in the mdx plugin

* make getImageCaption async

* use async mdx compiler

* fix for using compiler

* don't mutate the node multiple times

* convert markdown ast to html ast

Co-authored-by: vladar

* chore(release): Publish

 - babel-preset-gatsby@0.3.4
 - gatsby-cli@2.11.15
 - gatsby-plugin-mdx@1.1.10
 - gatsby-recipes@0.0.12
 - gatsby-remark-images@3.2.5
 - gatsby-theme-blog-core@1.3.30
 - gatsby-theme-blog@1.4.30
 - gatsby-theme-notes@1.2.29
 - gatsby-transformer-remark@2.7.4
 - gatsby@2.20.29

* Fix lint errors

* Fix TypeScript unused declaration error

* Fix linting

Co-authored-by: Lennart <lekoarts@gmail.com>
Co-authored-by: Jeremy Albright <1935258+Js-Brecht@users.noreply.github.com>
Co-authored-by: gatsbybot <mathews.kyle+gatsbybot@gmail.com>
Co-authored-by: Elijah <35966941+ElijahCano33@users.noreply.github.com>
Co-authored-by: Kyle Gill <kylerobertgill@gmail.com>
Co-authored-by: Peter van der Zee <209817+pvdz@users.noreply.github.com>
Co-authored-by: Michał Zieliński <zielinski-michal@outlook.com>
Co-authored-by: Mario Nikolaus <mnikolaus@users.noreply.github.com>
Co-authored-by: Mario Nikolaus <mario.nikolaus@sofascore.com>
Co-authored-by: Michael <184316+muescha@users.noreply.github.com>
Co-authored-by: Aisha Blake <aisha@gatsbyjs.com>
Co-authored-by: Ward Peeters <ward@coding-tech.com>
Co-authored-by: Kyle Mathews <mathews.kyle@gmail.com>
Co-authored-by: John Otander <johnotander@gmail.com>
Co-authored-by: Lorenzo GM <dev@lorenzogm.com>
Co-authored-by: aperacaula <36845488+aperacaula@users.noreply.github.com>
Co-authored-by: Obinna Ekwuno <obinnacodes@gmail.com>
Co-authored-by: Michelle Gienow <michellegienow@gmail.com>
Co-authored-by: Laurie Barth <laurie@LauriesrkLaptop.fios-router.home>
Co-authored-by: LB <laurie@gatsbyjs.com>
Co-authored-by: Alex Fornuto <github@alexf.co>
Co-authored-by: Shrey Sachdeva <shreysachdeva.2000@gmail.com>
Co-authored-by: Nat Alison <1278991+tesseralis@users.noreply.github.com>
Co-authored-by: Owen <owen@dangerfarms.com>
Co-authored-by: Alex Moon <moonmeister@users.noreply.github.com>
Co-authored-by: Marcus Lyons <10541922+marcuslyons@users.noreply.github.com>
Co-authored-by: Stuart Rayson <stuart.a.rayson@gmail.com>
Co-authored-by: Michal Piechowiak <misiek.piechowiak@gmail.com>
Co-authored-by: Jacob Packert <jacobpackert@gmail.com>
Co-authored-by: Shane Thomas <shane@codekarate.com>
Co-authored-by: nick shook <nick@shook.family>
Co-authored-by: Vladimir Razuvaev <vladimir.razuvaev@gmail.com>
Co-authored-by: Kai Hao <kevin830726@gmail.com>
Co-authored-by: Arthur <arthur@mediamonks.com>
Co-authored-by: Blaine Kasten <blainekasten@gmail.com>
Co-authored-by: Nicholas Duffy <duffn@outlook.com>
Co-authored-by: Michaël De Boey <info@michaeldeboey.be>
Co-authored-by: Rebenkov Aleksey <rebenkovaleksey@yandex.ru>
Co-authored-by: Ross Hendry <rhendry@googlemail.com>
Co-authored-by: Khaled Garbaya <khaled@contentful.com>
Co-authored-by: Mathieu Dutour <mathieu@dutour.me>
Co-authored-by: Sidhartha Chatterjee <me@sidharthachatterjee.com>
@afc163
Copy link
Contributor

afc163 commented Apr 22, 2020

afc163 added a commit to antvis/gatsby-theme-antv that referenced this pull request Apr 22, 2020
afc163 added a commit to antvis/gatsby-theme-antv that referenced this pull request Apr 22, 2020
* upgrade yarn.lock

* node 12

* 🔒 lock gatsby-transformer-remark version

gatsbyjs/gatsby#21188 (comment)
@mathieudutour
Copy link
Contributor Author

how so?

@chris-erickson
Copy link
Contributor

Now when I enable markdownCaptions: true I'm getting an unhandled promise rejection. The showCaptions: ['title'] option does work if markdownCaptions: false (but the MD is unprocessed!). How can I debug this particular issue?

@mathieudutour
Copy link
Contributor Author

  1. What the error of the rejected promise?
  2. What's your config?
  3. Do you have a repro somewhere?

@chris-erickson
Copy link
Contributor

So sorry, I forgot to include the error: UNHANDLED REJECTION Expected node, not '[object Promise]'

gatsby-config.json snippet.

    {
      resolve: `gatsby-transformer-remark`,
      options: {
        commonmark: true,
        footnotes: true,
        pedantic: true,
        gfm: true,
        plugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 960,
              quality: 90
              showCaptions: ['title', 'alt'],
              markdownCaptions: true,
              linkImagesToOriginal: false,
            },
          },
        ],
      },
    },

I don't have a reproduction at the moment, our site is quite expansive so it would take me a bit to do that. If this doesn't provide any useful leads, I can do that. FWIW, this seems to fail regardless of whether I have a "title" attribute in a MD image link, in other words, it seems like it's not a parsing issue at first glance.

@mathieudutour
Copy link
Contributor Author

found it: #23427

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bot: merge on green Gatsbot will merge these PRs automatically when all tests passes
Projects
None yet
6 participants