Skip to content

Commit

Permalink
fix(gatsby-plugin-mdx): Truncate non-latin language excerpts correctly (
Browse files Browse the repository at this point in the history
#22638)

* Truncate option for non-latin languages

* Add mention of truncate to docs
  • Loading branch information
jlkiri authored Apr 10, 2020
1 parent 84a37d2 commit ec80671
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
16 changes: 16 additions & 0 deletions packages/gatsby-plugin-mdx/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,22 @@ export const pageQuery = graphql`
`
```

## Troubleshooting

### Excerpts for non-latin languages

By default, `excerpt` uses `underscore.string/prune` which doesn't handle non-latin characters ([https://github.com/epeli/underscore.string/issues/418](https://github.com/epeli/underscore.string/issues/418)).

If that is the case, you can set `truncate` option on `excerpt` field, like:

```graphql
{
markdownRemark {
excerpt(truncate: true)
}
}
```

## License

MIT
16 changes: 14 additions & 2 deletions packages/gatsby-plugin-mdx/gatsby/source-nodes.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const _ = require(`lodash`)
const { GraphQLBoolean } = require(`gatsby/graphql`)
const remark = require(`remark`)
const english = require(`retext-english`)
const remark2retext = require(`remark-retext`)
Expand Down Expand Up @@ -151,8 +152,12 @@ module.exports = (
type: `Int`,
defaultValue: 140,
},
truncate: {
type: GraphQLBoolean,
defaultValue: false,
},
},
async resolve(mdxNode, { pruneLength }) {
async resolve(mdxNode, { pruneLength, truncate }) {
if (mdxNode.excerpt) {
return Promise.resolve(mdxNode.excerpt)
}
Expand All @@ -166,7 +171,14 @@ module.exports = (
return
})

return prune(excerptNodes.join(` `), pruneLength, `…`)
if (!truncate) {
return prune(excerptNodes.join(` `), pruneLength, `…`)
}

return _.truncate(excerptNodes.join(` `), {
length: pruneLength,
omission: `…`,
})
},
},
headings: {
Expand Down

0 comments on commit ec80671

Please sign in to comment.