Skip to content

Commit

Permalink
add headings from gatsbyjs#31
Browse files Browse the repository at this point in the history
  • Loading branch information
ChristopherBiscardi committed Jun 27, 2019
1 parent 82da5b6 commit e292203
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
52 changes: 52 additions & 0 deletions packages/gatsby-plugin-mdx/extend-node-type.js
Expand Up @@ -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");
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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) {
Expand Down
1 change: 1 addition & 0 deletions packages/gatsby-plugin-mdx/package.json
Expand Up @@ -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",
Expand Down

0 comments on commit e292203

Please sign in to comment.