forked from graphql/graphql.github.io
-
Notifications
You must be signed in to change notification settings - Fork 51
/
gatsby-node.js
369 lines (341 loc) · 10.7 KB
/
gatsby-node.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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
const path = require("path")
const sortLibs = require("./scripts/sort-libraries")
const globby = require("globby")
const frontmatterParser = require("parser-front-matter")
const { readFile } = require("fs-extra")
const { promisify } = require("util")
exports.onCreatePage = async ({ page, actions }) => {
const { createPage, deletePage } = actions
deletePage(page)
let context = {
...page.context,
sourcePath: path.relative(__dirname, page.componentPath),
}
if (page.path === "/code" || page.path === "/code/") {
const markdownFilePaths = await globby("src/content/code/**/*.md")
const codeData = {}
const slugMap = require("./src/content/code/slug-map.json")
const parse$ = promisify(frontmatterParser.parse)
await Promise.all(
markdownFilePaths.map(async markdownFilePath => {
const markdownFileContent = await readFile(markdownFilePath, "utf-8")
let {
data: { name, description, url, github, npm, gem },
content: howto,
} = await parse$(markdownFileContent, undefined)
howto = howto.trim()
const pathArr = markdownFilePath.split("/")
if (markdownFilePath.includes("language-support")) {
const languageSupportDirIndex = pathArr.indexOf("language-support")
const languageNameSlugIndex = languageSupportDirIndex + 1
const languageNameSlug = pathArr[languageNameSlugIndex]
const languageName = slugMap[languageNameSlug]
codeData.Languages = codeData.Languages || {}
codeData.Languages[languageName] =
codeData.Languages[languageName] || {}
const categoryNameSlugIndex = languageSupportDirIndex + 2
const categoryNameSlug = pathArr[categoryNameSlugIndex]
const categoryName = slugMap[categoryNameSlug]
codeData.Languages[languageName][categoryName] =
codeData.Languages[languageName][categoryName] || []
codeData.Languages[languageName][categoryName].push({
name,
description,
howto,
url,
github,
npm,
gem,
sourcePath: markdownFilePath,
})
} else {
const codeDirIndex = pathArr.indexOf("code")
const categoryNameSlugIndex = codeDirIndex + 1
const categoryNameSlug = pathArr[categoryNameSlugIndex]
const categoryName = slugMap[categoryNameSlug]
codeData[categoryName] = codeData[categoryName] || []
codeData[categoryName].push({
name,
description,
howto,
url,
github,
npm,
gem,
sourcePath: markdownFilePath,
})
}
})
)
const languageList = []
let sortedTools = []
await Promise.all([
Promise.all(
Object.keys(codeData.Languages).map(async languageName => {
const libraryCategoryMap = codeData.Languages[languageName]
let languageTotalStars = 0
await Promise.all(
Object.keys(libraryCategoryMap).map(async libraryCategoryName => {
const libraries = libraryCategoryMap[libraryCategoryName]
const { sortedLibs, totalStars } = await sortLibs(libraries)
libraryCategoryMap[libraryCategoryName] = sortedLibs
languageTotalStars += totalStars || 0
})
)
languageList.push({
name: languageName,
totalStars: languageTotalStars,
categoryMap: libraryCategoryMap,
})
})
),
sortLibs(codeData.Tools).then(({ sortedLibs }) => {
sortedTools = sortedLibs
}),
])
context = {
...context,
otherLibraries: {
Services: codeData.Services,
Tools: sortedTools,
"More Stuff": codeData["More Stuff"],
},
languageList: languageList.sort((a, b) => {
if (a.totalStars > b.totalStars) {
return -1
} else if (a.totalStars < b.totalStars) {
return 1
}
return 0
}),
}
}
createPage({
...page,
context,
})
}
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const result = await graphql(/* GraphQL */ `
query {
allMarkdownRemark {
edges {
node {
fileAbsolutePath
parent {
... on File {
relativeDirectory
sourceInstanceName
}
}
frontmatter {
title
permalink
next
category
sublinks
sidebarTitle
date
tags
}
id
}
}
}
tagsGroup: allMarkdownRemark {
group(field: frontmatter___tags) {
fieldValue
}
}
}
`)
const docTemplate = path.resolve("./src/templates/doc.tsx")
if (result.errors) {
// eslint-disable-next-line no-console
console.error(result.errors)
throw result.errors
}
const markdownPages = result.data.allMarkdownRemark.edges
// foundation: [
// {
// fileAbsolutePath: '/graphql/graphql.github.io/src/content/foundation/About.md',
// parent: {},
// frontmatter: {},
// id: '1d502d5e-3453-56cf-ad9a-7f6bfb68d9ba'
// },
// ...
// ]
// }
let pagesGroupedByFolder = {}
// {
// foundation: [
// { name: 'foundation', links: [{"fileAbsolutePath":"/graphql/graphql.github.io/src/content/foundation/About.md","parent":{"relativeDirectory":"foundation","sourceInstanceName":"content"},"frontmatter":{"title":"What is the GraphQL Foundation?","permalink":"/foundation/","next":"/foundation/join/","category":"GraphQL Foundation","sublinks":null,"sidebarTitle":"About the Foundation","date":null},"id":"1d502d5e-3453-56cf-ad9a-7f6bfb68d9ba"}] },
// { name: 'GraphQL Foundation', links: [Array] }
// ],
// Note that this is mutated
let sideBardata = {}
// Sidebar items to add which don't come from markdown
const additionalSidebarItems = {
foundation: [
{
name: "GraphQL Foundation",
links: [
{
frontmatter: {
sidebarTitle: "Foundation Members",
title: "Foundation Members",
permalink: "/foundation/members/",
date: null,
category: "GraphQL Foundation",
},
},
],
},
],
}
// E.g.
// {
// permalink: '/learn/best-practices/',
// relativeDirectory: 'learn',
// sidebarTitle: 'Introduction',
// nextPermalink: '/learn/thinking-in-graphs/',
// sourcePath: 'src/content/learn/BestPractice-Introduction.md'
// }
const allPages = []
// Loop through all *.md files in the repo, setting up both pagesGroupedByFolder
// and allPages.
markdownPages.map(({ node }) => {
const {
frontmatter: { permalink, next, sidebarTitle },
parent: { relativeDirectory, sourceInstanceName },
} = node
if (
sourceInstanceName !== "content" ||
relativeDirectory.includes("code/")
) {
return
}
if (!pagesGroupedByFolder[relativeDirectory]) {
pagesGroupedByFolder = {
...pagesGroupedByFolder,
[relativeDirectory]: [node],
}
} else {
pagesGroupedByFolder = {
...pagesGroupedByFolder,
[relativeDirectory]: [...pagesGroupedByFolder[relativeDirectory], node],
}
}
allPages.push({
permalink,
relativeDirectory,
sidebarTitle,
nextPermalink: next,
sourcePath: path.relative(__dirname, node.fileAbsolutePath),
})
})
// Loop through the sections in the sidebar, mutating the
// next and previous objects for different
Object.entries(pagesGroupedByFolder).map(([folder, pages]) => {
let pagesByUrl = {}
let previousPagesMap = {}
let pagesByDate = pages.sort((a, b) => {
const aDate = new Date(a.frontmatter.date || Date.now())
const bDate = new Date(b.frontmatter.date || Date.now())
if (aDate > bDate) {
return -1
} else if (aDate < bDate) {
return 1
}
return 0
})
pagesByDate.forEach(page => {
const next = page.frontmatter.next
const permalink = page.frontmatter.permalink
if (next) {
previousPagesMap[next] = permalink
}
pagesByUrl[permalink] = page
})
let firstPage = null
pagesByDate.forEach(page => {
const permalink = page.frontmatter.permalink
if (!previousPagesMap[permalink] && !firstPage) {
firstPage = page
return
}
})
if (!firstPage) {
throw new Error(`First page not found in ${folder}`)
}
let categoriesMap = {}
let currentCategory = null
let page = firstPage
let i = 0
while (page && i++ < 1000) {
const { frontmatter } = page
const {
category: definedCategory,
next: definedNextPageUrl,
} = frontmatter
let category = definedCategory || folder
if (!currentCategory || category !== currentCategory.name) {
if (currentCategory) {
if (!(currentCategory.name in categoriesMap)) {
categoriesMap[currentCategory.name] = currentCategory
}
}
currentCategory = {
name: category,
links: [],
}
}
currentCategory.links.push(page)
if (definedNextPageUrl) {
page = pagesByUrl[definedNextPageUrl]
} else {
page = pagesByDate[pagesByDate.indexOf(page) + 1]
}
if (currentCategory.links.includes(page)) {
page = null
}
}
if (!(currentCategory.name in categoriesMap)) {
categoriesMap[currentCategory.name] = currentCategory
}
sideBardata[folder] = Object.values(categoriesMap)
})
Object.entries(additionalSidebarItems).map(([folder, sections]) => {
sections.forEach(s => {
const originalLinks = sideBardata[folder].find(l => l.name === s.name)
originalLinks.links = [...originalLinks.links, ...s.links]
})
})
// Use all the set up data to now tell Gatsby to create pages
// on the site
allPages.forEach(page => {
createPage({
path: `${page.permalink}`,
component: docTemplate,
context: {
permalink: page.permalink,
nextPermalink: page.nextPermalink,
sideBarData: sideBardata[page.relativeDirectory],
sourcePath: page.sourcePath,
},
})
})
// Create tag pages
const tagTemplate = path.resolve("src/templates/tags.tsx")
const tags = result.data.tagsGroup.group
tags.forEach(tag => {
createPage({
path: `/tags/${tag.fieldValue}/`,
component: tagTemplate,
context: {
tag: tag.fieldValue,
},
})
})
}