generated from nisabmohd/Aria-Docs
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmarkdown.ts
291 lines (264 loc) · 8.04 KB
/
markdown.ts
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
import { compileMDX } from "next-mdx-remote/rsc";
import path from "path";
import { promises as fs } from "fs";
import remarkGfm from "remark-gfm";
import rehypePrism from "rehype-prism-plus";
import rehypeAutolinkHeadings from "rehype-autolink-headings";
import rehypeSlug from "rehype-slug";
import rehypeCodeTitles from "rehype-code-titles";
import { page_routes, example_page_routes, ROUTES, EXAMPLE_ROUTES } from "./routes-config";
import { visit } from "unist-util-visit";
import matter from "gray-matter";
// custom components imports
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import Pre from "@/components/markdown/pre";
import Note from "@/components/markdown/note";
import { Stepper, StepperItem } from "@/components/markdown/stepper";
import Image from "@/components/markdown/image";
import Link from "@/components/markdown/link";
import Outlet from "@/components/markdown/outlet";
// add custom components
const components = {
Tabs,
TabsContent,
TabsList,
TabsTrigger,
pre: Pre,
Note,
Stepper,
StepperItem,
img: Image,
a: Link,
Outlet,
};
// can be used for other pages like blogs, Guides etc
async function parseMdx<Frontmatter>(rawMdx: string) {
return await compileMDX<Frontmatter>({
source: rawMdx,
options: {
parseFrontmatter: true,
mdxOptions: {
rehypePlugins: [
preProcess,
rehypeCodeTitles,
rehypePrism,
rehypeSlug,
rehypeAutolinkHeadings,
postProcess,
],
remarkPlugins: [remarkGfm],
},
},
components,
});
}
// logic for docs
export type BaseMdxFrontmatter = {
title: string;
description: string;
};
export async function getDocsForSlug(slug: string) {
try {
const contentPath = getDocsContentPath(slug);
const rawMdx = await fs.readFile(contentPath, "utf-8");
return await parseMdx<BaseMdxFrontmatter>(rawMdx);
} catch (err) {
console.log(err);
}
}
export async function getExamplsForSlug(slug: string) {
try {
const contentPath = getExamplesContentPath(slug);
const rawMdx = await fs.readFile(contentPath, "utf-8");
return await parseMdx<BaseMdxFrontmatter>(rawMdx);
} catch (err) {
console.log(err);
}
}
export async function getDocsTocs(slug: string) {
const contentPath = getDocsContentPath(slug);
const rawMdx = await fs.readFile(contentPath, "utf-8");
// captures between ## - #### can modify accordingly
const headingsRegex = /^(#{2,4})\s(.+)$/gm;
let match;
const extractedHeadings = [];
while ((match = headingsRegex.exec(rawMdx)) !== null) {
const headingLevel = match[1].length;
const headingText = match[2].trim();
const slug = sluggify(headingText);
extractedHeadings.push({
level: headingLevel,
text: headingText,
href: `#${slug}`,
});
}
return extractedHeadings;
}
export async function getExamplesTocs(slug: string) {
const contentPath = getExamplesContentPath(slug);
const rawMdx = await fs.readFile(contentPath, "utf-8");
// captures between ## - #### can modify accordingly
const headingsRegex = /^(#{2,4})\s(.+)$/gm;
let match;
const extractedHeadings = [];
while ((match = headingsRegex.exec(rawMdx)) !== null) {
const headingLevel = match[1].length;
const headingText = match[2].trim();
const slug = sluggify(headingText);
extractedHeadings.push({
level: headingLevel,
text: headingText,
href: `#${slug}`,
});
}
return extractedHeadings;
}
export function getPreviousNext(path: string) {
const index = page_routes.findIndex(({ href }) => href == `/${path}`);
return {
prev: page_routes[index - 1],
next: page_routes[index + 1],
};
}
export function getExamplePrevoiusNext(path: string) {
const index = example_page_routes.findIndex(({ href }) => href == `/${path}`);
return {
prev: example_page_routes[index - 1],
next: example_page_routes[index + 1],
};
}
function sluggify(text: string) {
const slug = text.toLowerCase().replace(/\s+/g, "-");
return slug.replace(/[^a-z0-9-]/g, "");
}
function getDocsContentPath(slug: string) {
return path.join(process.cwd(), "/contents/docs/", `${slug}/index.mdx`);
}
function getExamplesContentPath(slug: string) {
return path.join(process.cwd(), "/contents/examples/", `${slug}/index.mdx`);
}
function justGetFrontmatterFromMD<Frontmatter>(rawMd: string): Frontmatter {
return matter(rawMd).data as Frontmatter;
}
export async function getAllChilds(pathString: string) {
const items = pathString.split("/").filter((it) => it != "");
let page_routes_copy = ROUTES;
let prevHref = "";
for (const it of items) {
const found = page_routes_copy.find((innerIt) => innerIt.href == `/${it}`);
if (!found) break;
prevHref += found.href;
page_routes_copy = found.items ?? [];
}
if (!prevHref) return [];
return await Promise.all(
page_routes_copy.map(async (it) => {
const totalPath = path.join(
process.cwd(),
"/contents/docs/",
prevHref,
it.href,
"index.mdx",
);
const raw = await fs.readFile(totalPath, "utf-8");
return {
...justGetFrontmatterFromMD<BaseMdxFrontmatter>(raw),
href: `/docs${prevHref}${it.href}`,
};
}),
);
}
export async function getAllExampleChilds(pathString: string) {
const items = pathString.split("/").filter((it) => it != "");
let page_routes_copy = EXAMPLE_ROUTES;
let prevHref = "";
for (const it of items) {
const found = page_routes_copy.find((innerIt) => innerIt.href == `/${it}`);
if (!found) break;
prevHref += found.href;
page_routes_copy = found.items ?? [];
}
if (!prevHref) return [];
return await Promise.all(
page_routes_copy.map(async (it) => {
const totalPath = path.join(
process.cwd(),
"/contents/docs/",
prevHref,
it.href,
"index.mdx",
);
const raw = await fs.readFile(totalPath, "utf-8");
return {
...justGetFrontmatterFromMD<BaseMdxFrontmatter>(raw),
href: `/docs${prevHref}${it.href}`,
};
}),
);
}
// for copying the code in pre
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const preProcess = () => (tree: any) => {
visit(tree, (node) => {
if (node?.type === "element" && node?.tagName === "pre") {
const [codeEl] = node.children;
if (codeEl.tagName !== "code") return;
node.raw = codeEl.children?.[0].value;
}
});
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const postProcess = () => (tree: any) => {
visit(tree, "element", (node) => {
if (node?.type === "element" && node?.tagName === "pre") {
node.properties["raw"] = node.raw;
}
});
};
export type Author = {
avatar?: string;
handle: string;
username: string;
handleUrl: string;
};
export type BlogMdxFrontmatter = BaseMdxFrontmatter & {
date: string;
authors: Author[];
cover: string;
};
export async function getAllBlogStaticPaths() {
try {
const blogFolder = path.join(process.cwd(), "/contents/blogs/");
const res = await fs.readdir(blogFolder);
return res.map((file) => file.split(".")[0]);
} catch (err) {
console.log(err);
}
}
export async function getAllBlogs() {
const blogFolder = path.join(process.cwd(), "/contents/blogs/");
const files = await fs.readdir(blogFolder);
const uncheckedRes = await Promise.all(
files.map(async (file) => {
if (!file.endsWith(".mdx")) return undefined;
const filepath = path.join(process.cwd(), `/contents/blogs/${file}`);
const rawMdx = await fs.readFile(filepath, "utf-8");
return {
...justGetFrontmatterFromMD<BlogMdxFrontmatter>(rawMdx),
slug: file.split(".")[0],
};
}),
);
return uncheckedRes.filter((it) => !!it) as (BlogMdxFrontmatter & {
slug: string;
})[];
}
export async function getBlogForSlug(slug: string) {
const blogFile = path.join(process.cwd(), "/contents/blogs/", `${slug}.mdx`);
try {
const rawMdx = await fs.readFile(blogFile, "utf-8");
return await parseMdx<BlogMdxFrontmatter>(rawMdx);
} catch {
return undefined;
}
}