-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathonCreatePage.ts
More file actions
72 lines (63 loc) · 2.38 KB
/
onCreatePage.ts
File metadata and controls
72 lines (63 loc) · 2.38 KB
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
import { GatsbyNode } from 'gatsby';
import path from 'path';
import fs from 'fs';
export type LayoutOptions = {
leftSidebar: boolean;
rightSidebar: boolean;
template: string;
mdx: boolean;
};
const mdxWrapper = path.resolve('src/components/Layout/MDXWrapper.tsx');
const pageLayoutOptions: Record<string, LayoutOptions> = {
'/docs': { leftSidebar: false, rightSidebar: false, template: 'index', mdx: false },
'/docs/api/control-api': {
leftSidebar: false,
rightSidebar: false,
template: 'control-api',
mdx: false,
},
'/docs/sdks': { leftSidebar: false, rightSidebar: false, template: 'sdk', mdx: false },
'/examples': { leftSidebar: false, rightSidebar: false, template: 'examples', mdx: false },
'/docs/404': { leftSidebar: false, rightSidebar: false, template: '404', mdx: false },
};
// Function to extract code element classes from an MDX file
const extractCodeLanguages = async (filePath: string): Promise<Set<string>> => {
try {
// Check if the file exists
if (!fs.existsSync(filePath)) {
return new Set();
}
// Read the file content
const fileContent = fs.readFileSync(filePath, 'utf8');
// Find all instances of code blocks with language specifiers (```language)
const codeBlockRegex = /```(\w+)/g;
let match;
const languages = new Set<string>();
while ((match = codeBlockRegex.exec(fileContent)) !== null) {
if (match[1] && match[1].trim()) {
languages.add(match[1].trim());
}
}
return languages;
} catch (error) {
console.error(`Error extracting code element classes from ${filePath}:`, error);
return new Set();
}
};
export const onCreatePage: GatsbyNode['onCreatePage'] = async ({ page, actions }) => {
const { createPage } = actions;
const pathOptions = Object.entries(pageLayoutOptions).find(([path]) => page.path === path);
const isMDX = page.component.endsWith('.mdx');
const detectedLanguages = isMDX ? await extractCodeLanguages(page.component) : new Set();
if (pathOptions || isMDX) {
createPage({
...page,
context: {
...page.context,
layout: pathOptions ? pathOptions[1] : { leftSidebar: true, rightSidebar: true, template: 'base', mdx: isMDX },
...(isMDX ? { languages: Array.from(detectedLanguages) } : {}),
},
component: isMDX ? `${mdxWrapper}?__contentFilePath=${page.component}` : page.component,
});
}
};