-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
create-schema-customization.js
319 lines (297 loc) · 8.31 KB
/
create-schema-customization.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
const _ = require(`lodash`)
const { GraphQLBoolean } = require(`gatsby/graphql`)
const remark = require(`remark`)
const english = require(`retext-english`)
const remark2retext = require(`remark-retext`)
const unified = require(`unified`)
const visit = require(`unist-util-visit`)
const remove = require(`unist-util-remove`)
const toString = require(`mdast-util-to-string`)
const generateTOC = require(`mdast-util-toc`)
const prune = require(`underscore.string/prune`)
const slugify = require(`slugify`)
const path = require(`path`)
const debug = require(`debug`)(`gatsby-plugin-mdx:extend-node-type`)
const getTableOfContents = require(`../utils/get-table-of-content`)
const defaultOptions = require(`../utils/default-options`)
const genMDX = require(`../utils/gen-mdx`)
const { mdxHTMLLoader: loader } = require(`../utils/render-html`)
async function getCounts({ mdast }) {
const counts = {}
// convert the mdxast to back to mdast
remove(mdast, `import`)
remove(mdast, `export`)
visit(mdast, `jsx`, node => {
node.type = `html`
})
await remark()
.use(remark2retext, unified().use(english).use(count))
.run(mdast)
function count() {
return counter
function counter(tree) {
visit(tree, visitor)
function visitor(node) {
counts[node.type] = (counts[node.type] || 0) + 1
}
}
}
return {
paragraphs: counts.ParagraphNode || 0,
sentences: counts.SentenceNode || 0,
words: counts.WordNode || 0,
}
}
module.exports = function createSchemaCustomization(
{
store,
pathPrefix,
getNode,
getNodes,
cache,
reporter,
actions,
schema,
...helpers
},
pluginOptions
) {
let mdxHTMLLoader
const { createTypes } = actions
const options = defaultOptions(pluginOptions)
const headingsMdx = [`h1`, `h2`, `h3`, `h4`, `h5`, `h6`]
/**
* Support gatsby-remark parser plugins
*/
for (const plugin of options.gatsbyRemarkPlugins) {
debug(`requiring`, plugin.resolve)
const requiredPlugin = plugin.module
debug(`required`, plugin)
if (_.isFunction(requiredPlugin.setParserPlugins)) {
for (const parserPlugin of requiredPlugin.setParserPlugins(
plugin.pluginOptions || {}
)) {
if (_.isArray(parserPlugin)) {
const [parser, parserPluginOptions] = parserPlugin
debug(`adding remarkPlugin with options`, plugin, parserPluginOptions)
options.remarkPlugins.push([parser, parserPluginOptions])
} else {
debug(`adding remarkPlugin`, plugin)
options.remarkPlugins.push(parserPlugin)
}
}
}
}
const pendingPromises = new WeakMap()
const processMDX = ({ node }) => {
let promise = pendingPromises.get(node)
if (!promise) {
promise = genMDX({
node,
options,
store,
pathPrefix,
getNode,
getNodes,
cache,
reporter,
actions,
schema,
...helpers,
})
pendingPromises.set(node, promise)
promise.then(() => {
pendingPromises.delete(node)
})
}
return promise
}
// New Code // Schema
const MdxType = schema.buildObjectType({
name: `Mdx`,
fields: {
rawBody: { type: `String!` },
fileAbsolutePath: { type: `String!` },
frontmatter: { type: `MdxFrontmatter` },
slug: {
type: `String`,
async resolve(mdxNode, args, context) {
const nodeWithContext = context.nodeModel.findRootNodeAncestor(
mdxNode,
node => node.internal && node.internal.type === `File`
)
if (!nodeWithContext) {
return null
}
const fileRelativePath = nodeWithContext.relativePath
const parsedPath = path.parse(fileRelativePath)
let relevantPath
if (parsedPath.name === `index`) {
relevantPath = fileRelativePath.replace(parsedPath.base, ``)
} else {
relevantPath = fileRelativePath.replace(parsedPath.ext, ``)
}
return slugify(relevantPath, {
remove: /[^\w\s$*_+~.()'"!\-:@/]/g, // this is the set of allowable characters
})
},
},
body: {
type: `String!`,
async resolve(mdxNode) {
const { body } = await processMDX({ node: mdxNode })
return body
},
},
excerpt: {
type: `String!`,
args: {
pruneLength: {
type: `Int`,
defaultValue: 140,
},
truncate: {
type: GraphQLBoolean,
defaultValue: false,
},
},
async resolve(mdxNode, { pruneLength, truncate }) {
if (mdxNode.excerpt) {
return Promise.resolve(mdxNode.excerpt)
}
const { mdast } = await processMDX({ node: mdxNode })
const excerptNodes = []
visit(mdast, node => {
if (node.type === `text` || node.type === `inlineCode`) {
excerptNodes.push(node.value)
}
return
})
if (!truncate) {
return prune(excerptNodes.join(` `), pruneLength, `…`)
}
return _.truncate(excerptNodes.join(` `), {
length: pruneLength,
omission: `…`,
})
},
},
headings: {
type: `[MdxHeadingMdx]`,
args: {
depth: {
type: `HeadingsMdx`,
},
},
async resolve(mdxNode, { depth }) {
// TODO: change this to operate on html instead of mdast
const { mdast } = await processMDX({ node: mdxNode })
let headings = []
visit(mdast, `heading`, heading => {
headings.push({
value: toString(heading),
depth: heading.depth,
})
})
if (headingsMdx.includes(depth)) {
headings = headings.filter(heading => `h${heading.depth}` === depth)
}
return headings
},
},
html: {
type: `String`,
async resolve(mdxNode) {
if (mdxNode.html) {
return Promise.resolve(mdxNode.html)
}
const { body } = await processMDX({ node: mdxNode })
try {
if (!mdxHTMLLoader) {
mdxHTMLLoader = loader({ reporter, cache, store })
}
const html = await mdxHTMLLoader.load({ ...mdxNode, body })
return html
} catch (e) {
reporter.error(
`gatsby-plugin-mdx: Error querying the \`html\` field.
This field is intended for use with RSS feed generation.
If you're trying to use it in application-level code, try querying for \`Mdx.body\` instead.
Original error:
${e}`
)
return undefined
}
},
},
mdxAST: {
type: `JSON`,
async resolve(mdxNode) {
const { mdast } = await processMDX({ node: mdxNode })
return mdast
},
},
tableOfContents: {
type: `JSON`,
args: {
maxDepth: {
type: `Int`,
default: 6,
},
},
async resolve(mdxNode, { maxDepth }) {
const { mdast } = await processMDX({ node: mdxNode })
const toc = generateTOC(mdast, { maxDepth })
return getTableOfContents(toc.map, {})
},
},
timeToRead: {
type: `Int`,
async resolve(mdxNode) {
const { mdast } = await processMDX({ node: mdxNode })
const { words } = await getCounts({ mdast })
let timeToRead = 0
const avgWPM = 265
timeToRead = Math.round(words / avgWPM)
if (timeToRead === 0) {
timeToRead = 1
}
return timeToRead
},
},
wordCount: {
type: `MdxWordCount`,
async resolve(mdxNode) {
const { mdast } = await processMDX({ node: mdxNode })
return getCounts({ mdast })
},
},
},
interfaces: [`Node`],
extensions: {
childOf: {
mimeTypes: options.mediaTypes,
},
},
})
createTypes([
`
type MdxFrontmatter {
title: String!
}
type MdxHeadingMdx {
value: String
depth: Int
}
enum HeadingsMdx {
${headingsMdx}
}
type MdxWordCount {
paragraphs: Int
sentences: Int
words: Int
}
`,
MdxType,
])
}