1 import fs from "fs"
2 import path from "path"
3 import { u } from "unist-builder"
4 import { visit } from "unist-util-visit"
5 import { Documentation } from "react-docgen"
6 import { ExampleRegistry, UnistNode, UnistTree } from "types"
7 import { workerCompatibleFetch } from "docs-utils"
8
9 type Options = {
10 exampleRegistry: ExampleRegistry
11 specsIndex: Record<string, string[]>
12 specsBaseUrl?: string
13 }
14
15 export function uiRehypePlugin({
16 exampleRegistry,
17 specsIndex,
18 specsBaseUrl,
19 }: Options) {
20 return async (tree: UnistTree) => {
21 const exampleNodes: UnistNode[] = []
22 const referenceNodes: UnistNode[] = []
23
24 visit(tree, (node: UnistNode) => {
25 if (node.name === "ComponentExample") {
26 exampleNodes.push(node)
27 } else if (node.name === "ComponentReference") {
28 referenceNodes.push(node)
29 }
30 })
31
32 for (const node of exampleNodes) {
33 const name = getNodeAttributeByName(node, "name")?.value as string
34 if (!name) {
35 continue
36 }
37
38 try {
39 const component = exampleRegistry[name]
40 const src = component.file
41
42 let source = await workerCompatibleFetch<string | null>({
43 url: `${specsBaseUrl}/${src}`,
44 responseTransformer: async (res) => {
45 return res.ok ? res.text() : null
46 },
47 fallbackAction: async () => {
48 const filePath = path.join(process.cwd(), src)
49 return fs.promises.readFile(filePath, "utf8")
50 },
51 useRemote: !!specsBaseUrl,
52 })
53
54 if (!source) {
55 continue
56 }
57
58 source = source.replaceAll("export default", "export")
59
60 // Trim newline at the end of file. It's correct, but it makes source display look off
61 if (source.endsWith("\n")) {
62 source = source.substring(0, source.length - 1)
63 }
64
65 node.children?.push(
66 u("element", {
67 tagName: "span",
68 properties: {
69 __src__: src,
70 codeLinesJSON: JSON.stringify(source.split("\n")),
71 },
72 })
73 )
74 } catch (error) {
75 console.error(error)
76 }
77 }
78
79 for (const node of referenceNodes) {
80 const mainComponent = getNodeAttributeByName(node, "mainComponent")
81 ?.value as string
82
83 if (!mainComponent) {
84 continue
85 }
86
87 const specs: Documentation[] = []
88 const specFiles = specsIndex[mainComponent] ?? []
89
90 if (specsBaseUrl) {
91 try {
92 const specResults = await Promise.all(
93 specFiles.map(async (fileName) => {
94 const r = await fetch(
95 `${specsBaseUrl}/specs/components/${mainComponent}/${fileName}`
96 )
97 return r.ok ? ((await r.json()) as Documentation) : null
98 })
99 )
100 specs.push(...(specResults.filter(Boolean) as Documentation[]))
101 } catch (error) {
102 console.error(error)
103 }
104 } else {
105 const componentSpecsDir = path.join(
106 process.cwd(),
107 "specs",
108 "components",
109 mainComponent
110 )
111 specFiles.forEach((specFileName) => {
112 const specFile = fs.readFileSync(
113 path.join(componentSpecsDir, specFileName),
114 "utf-8"
115 )
116 specs.push(JSON.parse(specFile) as Documentation)
117 })
118 }
119
120 node.attributes?.push({
121 name: "specsSrc",
122 value: JSON.stringify(specs),
123 type: "mdxJsxAttribute",
124 })
125 }
126 }
127 }
128
129 function getNodeAttributeByName(node: UnistNode, name: string) {
130 return node.attributes?.find((attribute) => attribute.name === name)
131 }