From e29220313b8e7f2ce9ff669293b00b8a31e32996 Mon Sep 17 00:00:00 2001 From: Christopher Biscardi Date: Sun, 5 Aug 2018 21:57:12 -0700 Subject: [PATCH] add headings from #31 --- .../gatsby-plugin-mdx/extend-node-type.js | 52 +++++++++++++++++++ packages/gatsby-plugin-mdx/package.json | 1 + 2 files changed, 53 insertions(+) diff --git a/packages/gatsby-plugin-mdx/extend-node-type.js b/packages/gatsby-plugin-mdx/extend-node-type.js index d670148c325eb..608e727787843 100644 --- a/packages/gatsby-plugin-mdx/extend-node-type.js +++ b/packages/gatsby-plugin-mdx/extend-node-type.js @@ -11,6 +11,7 @@ const remark = require("remark"); const retext = require("retext"); const visit = require("unist-util-visit"); const remove = require("unist-util-remove"); +const toString = require("mdast-util-to-string"); const stripMarkdown = require("strip-markdown"); const grayMatter = require("gray-matter"); const { createMdxAstCompiler } = require("@mdx-js/mdx"); @@ -62,6 +63,35 @@ import { MDXTag } from '@mdx-js/tag' ${code}`; } + const HeadingType = new GraphQLObjectType({ + name: `MdxHeading`, + fields: { + value: { + type: GraphQLString, + resolve(heading) { + return heading.value; + } + }, + depth: { + type: GraphQLInt, + resolve(heading) { + return heading.depth; + } + } + } + }); + const Headings = new GraphQLEnumType({ + name: `Headings`, + values: { + h1: { value: 1 }, + h2: { value: 2 }, + h3: { value: 3 }, + h4: { value: 4 }, + h5: { value: 5 }, + h6: { value: 6 } + } + }); + return resolve({ code: { type: GraphQLString, @@ -94,6 +124,28 @@ ${code}`; return prune(excerptNodes.join(" "), pruneLength, "…"); } }, + headings: { + type: new GraphQLList(HeadingType), + args: { + depth: { + type: Headings + } + }, + async resolve(mdxNode, { depth }) { + const ast = await getAST(mdxNode); + let headings = []; + visit(ast, "heading", heading => { + headings.push({ + value: toString(heading), + depth: heading.depth + }); + }); + if (typeof depth === `number`) { + headings = headings.filter(heading => heading.depth === depth); + } + return headings; + } + }, timeToRead: { type: GraphQLInt, async resolve(mdxNode) { diff --git a/packages/gatsby-plugin-mdx/package.json b/packages/gatsby-plugin-mdx/package.json index 86026f11cd7b4..5dd7572d76a58 100644 --- a/packages/gatsby-plugin-mdx/package.json +++ b/packages/gatsby-plugin-mdx/package.json @@ -16,6 +16,7 @@ "gray-matter": "^4.0.1", "json5": "^1.0.1", "lodash": "^4.17.10", + "mdast-util-to-string": "^1.0.4", "remark": "^9.0.0", "retext": "^5.0.0", "strip-markdown": "^3.0.1",