Raw
1 import {
2 ExpressionJsVar,
3 Sidebar,
4 UnistNode,
5 UnistNodeWithData,
6 UnistTree,
7 } from "types"
8 import { SKIP, VisitorResult } from "unist-util-visit"
9 import { estreeToJs } from "../estree-to-js.js"
10 import {
11 isExpressionJsVarLiteral,
12 isExpressionJsVarObj,
13 } from "../expression-is-utils.js"
14 import path from "path"
15 import { readFileSync } from "fs"
16 import type { Documentation } from "react-docgen"
17 import { workerCompatibleFetch } from "../worker-compatible-fetch.js"
18
19 export type ComponentParser<TOptions = any> = (
20 node: UnistNodeWithData,
21 index: number,
22 parent: UnistTree,
23 options?: TOptions
24 ) => VisitorResult | Promise<VisitorResult>
25
26 export const parseCard: ComponentParser = (
27 node: UnistNodeWithData,
28 index: number,
29 parent: UnistTree
30 ): VisitorResult => {
31 let title: string | undefined,
32 text: string | undefined,
33 href: string | undefined
34 node.attributes?.some((attr) => {
35 if (title && text && href) {
36 return true
37 }
38 if (attr.name === "title") {
39 title = attr.value as string
40 } else if (attr.name === "text") {
41 text = attr.value as string
42 } else if (attr.name === "href") {
43 href = attr.value as string
44 }
45 return false
46 })
47 if (!title || !href) {
48 return
49 }
50 parent?.children.splice(index, 1, {
51 type: "paragraph",
52 children: [
53 {
54 type: "link",
55 url: href,
56 children: [
57 {
58 type: "text",
59 value: title,
60 },
61 ],
62 },
63 {
64 type: "text",
65 value: `: ${text}`,
66 },
67 ],
68 })
69 return [SKIP, index]
70 }
71
72 export const parseCardList: ComponentParser = (
73 node: UnistNodeWithData,
74 index: number,
75 parent: UnistTree
76 ): VisitorResult => {
77 const items = node.attributes?.find((attr) => attr.name === "items")
78 if (!items || typeof items.value === "string" || !items.value.data?.estree) {
79 return
80 }
81
82 const itemsJsVar = estreeToJs(items.value.data.estree)
83
84 if (!itemsJsVar || !Array.isArray(itemsJsVar)) {
85 return
86 }
87
88 const listItems = itemsJsVar
89 .map((item) => {
90 if (
91 !isExpressionJsVarObj(item) ||
92 !("title" in item) ||
93 !("href" in item) ||
94 !isExpressionJsVarLiteral(item.title) ||
95 !isExpressionJsVarLiteral(item.href)
96 ) {
97 return null
98 }
99 const description = isExpressionJsVarLiteral(item.text)
100 ? (item.text.data as string)
101 : ""
102 const children: UnistNode[] = [
103 {
104 type: "link",
105 url: `${item.href.data}`,
106 children: [
107 {
108 type: "text",
109 value: item.title.data as string,
110 },
111 ],
112 },
113 ]
114 if (description.length) {
115 children.push({
116 type: "text",
117 value: `: ${description}`,
118 })
119 }
120 return {
121 type: "listItem",
122 children: [
123 {
124 type: "paragraph",
125 children,
126 },
127 ],
128 }
129 })
130 .filter(Boolean) as UnistNode[]
131
132 parent?.children.splice(index, 1, {
133 type: "list",
134 ordered: false,
135 spread: false,
136 children: listItems,
137 })
138 return [SKIP, index]
139 }
140
141 export const parseCodeTabs: ComponentParser = (
142 node: UnistNodeWithData,
143 index: number,
144 parent: UnistTree
145 ): VisitorResult => {
146 const tabs = node.children?.filter((child) => child.name === "CodeTab")
147 if (!tabs) {
148 return
149 }
150
151 const children: UnistNode[] = []
152
153 tabs.forEach((tab) => {
154 const label = tab.attributes?.find((attr) => attr.name === "label")
155 const code = tab.children?.find((child) => child.type === "code")
156
157 if (!label || !code) {
158 return
159 }
160
161 children.push(
162 {
163 type: "heading",
164 depth: 3,
165 children: [
166 {
167 type: "text",
168 value: label.value as string,
169 },
170 ],
171 },
172 code
173 )
174 })
175
176 parent?.children.splice(index, 1, ...children)
177 return [SKIP, index]
178 }
179
180 export const parseDetails: ComponentParser = (
181 node: UnistNodeWithData,
182 index: number,
183 parent: UnistTree
184 ): VisitorResult => {
185 const summary = node.attributes?.find(
186 (attr) => attr.name === "summaryContent"
187 )
188
189 const children: UnistNode[] = []
190
191 if (summary?.value) {
192 children.push({
193 type: "heading",
194 depth: 3,
195 children: [
196 {
197 type: "text",
198 value: (summary?.value as string) || "Details",
199 },
200 ],
201 })
202 }
203
204 children.push(...(node.children || []))
205
206 parent?.children.splice(index, 1, ...children)
207 return [SKIP, index]
208 }
209
210 export const parseNote: ComponentParser = (
211 node: UnistNodeWithData,
212 index: number,
213 parent: UnistTree
214 ): VisitorResult => {
215 parent.children?.splice(index, 1, ...(node.children || []))
216 return [SKIP, index]
217 }
218
219 export const parsePrerequisites: ComponentParser = (
220 node: UnistNodeWithData,
221 index: number,
222 parent: UnistTree
223 ): VisitorResult => {
224 const items = node.attributes?.find((attr) => attr.name === "items")
225 if (!items || typeof items.value === "string" || !items.value.data?.estree) {
226 return
227 }
228
229 const itemsJsVar = estreeToJs(items.value.data.estree)
230
231 if (!itemsJsVar || !Array.isArray(itemsJsVar)) {
232 return
233 }
234
235 const listItems = itemsJsVar
236 .map((item) => {
237 if (
238 !isExpressionJsVarObj(item) ||
239 !("text" in item) ||
240 !("link" in item) ||
241 !isExpressionJsVarLiteral(item.text) ||
242 !isExpressionJsVarLiteral(item.link)
243 ) {
244 return null
245 }
246 return {
247 type: "listItem",
248 children: [
249 {
250 type: "paragraph",
251 children: [
252 {
253 type: "link",
254 url: `${item.link.data}`,
255 children: [
256 {
257 type: "text",
258 value: item.text.data,
259 },
260 ],
261 },
262 ],
263 },
264 ],
265 }
266 })
267 .filter(Boolean) as UnistNode[]
268
269 parent?.children.splice(
270 index,
271 1,
272 {
273 type: "heading",
274 depth: 3,
275 children: [
276 {
277 type: "text",
278 value: "Prerequisites",
279 },
280 ],
281 },
282 {
283 type: "list",
284 ordered: false,
285 spread: false,
286 children: listItems,
287 }
288 )
289 return [SKIP, index]
290 }
291
292 export const parseSourceCodeLink: ComponentParser = (
293 node: UnistNodeWithData,
294 index: number,
295 parent: UnistTree
296 ): VisitorResult => {
297 const link = node.attributes?.find((attr) => attr.name === "link")
298 if (!link) {
299 return
300 }
301
302 parent?.children.splice(index, 1, {
303 type: "paragraph",
304 children: [
305 {
306 type: "link",
307 url: link?.value as string,
308 children: [
309 {
310 type: "text",
311 value: "Source code",
312 },
313 ],
314 },
315 ],
316 })
317 return [SKIP, index]
318 }
319
320 export const parseTable: ComponentParser = (
321 node: UnistNodeWithData,
322 index: number,
323 parent: UnistTree
324 ): VisitorResult => {
325 const headerNode = node.children?.find(
326 (child) => child.name === "Table.Header"
327 )
328 const bodyNode = node.children?.find((child) => child.name === "Table.Body")
329
330 let nodeText = ``
331 let headerCellsCount = 0
332
333 headerNode?.children?.forEach((headerRow, rowIndex) => {
334 if (rowIndex > 0) {
335 nodeText += `\n`
336 }
337 const childCells =
338 headerRow.children?.length === 1 &&
339 headerRow.children[0].type === "paragraph"
340 ? headerRow.children[0].children
341 : headerRow.children
342 headerCellsCount = childCells?.length || 0
343 childCells?.forEach((headerCell) => {
344 if (headerCell.name !== "Table.HeaderCell") {
345 return
346 }
347 nodeText += `|`
348 nodeText += formatNodeText(getTextNode(headerCell))
349 })
350 nodeText += `|`
351 })
352
353 nodeText += `\n|${new Array(headerCellsCount).fill(`---`).join(`|`)}|`
354
355 bodyNode?.children?.forEach((bodyRow) => {
356 nodeText += `\n`
357 bodyRow.children?.forEach((bodyCell) => {
358 nodeText += `|`
359 nodeText += formatNodeText(getTextNode(bodyCell))
360 })
361 nodeText += `|`
362 })
363
364 parent.children?.splice(index, 1, {
365 type: "paragraph",
366 children: [
367 {
368 type: "text",
369 value: nodeText,
370 },
371 ],
372 })
373 }
374
375 export const parseTabs: ComponentParser = (
376 node: UnistNodeWithData,
377 index: number,
378 parent: UnistTree
379 ): VisitorResult => {
380 if ((node.children?.length || 0) < 2) {
381 return
382 }
383
384 const tabs: UnistNode[] = []
385
386 node.children![0].children?.forEach((tabList) => {
387 tabList.children?.forEach((tabTrigger, index) => {
388 const tabContentNode = node.children?.[1].children?.[index]
389 const tabLabel = formatNodeText(getTextNode(tabTrigger))
390 const tabContent = tabContentNode?.children || []
391 if (!tabLabel || !tabContent) {
392 return
393 }
394
395 tabs.push(
396 {
397 type: "heading",
398 depth: 3,
399 children: [
400 {
401 type: "text",
402 value: tabLabel,
403 },
404 ],
405 },
406 ...tabContent
407 )
408 })
409 })
410
411 parent.children?.splice(index, 1, ...tabs)
412 return [SKIP, index]
413 }
414
415 export const parseTypeList: ComponentParser = (
416 node: UnistNodeWithData,
417 index: number,
418 parent: UnistTree
419 ): VisitorResult => {
420 const types = node.attributes?.find((attr) => attr.name === "types")
421 if (!types || typeof types.value === "string" || !types.value.data?.estree) {
422 return
423 }
424
425 const typesJsVar = estreeToJs(types.value.data.estree)
426
427 if (!typesJsVar || !Array.isArray(typesJsVar)) {
428 return
429 }
430
431 const generateTypeListItems = (
432 typesJsVar: ExpressionJsVar[]
433 ): UnistNode[] => {
434 const listItems: UnistNode[] = []
435
436 typesJsVar.forEach((item) => {
437 if (!isExpressionJsVarObj(item)) {
438 return
439 }
440
441 const typeName = isExpressionJsVarLiteral(item.name) ? item.name.data : ""
442 const itemType = isExpressionJsVarLiteral(item.type) ? item.type.data : ""
443 const itemDescription = isExpressionJsVarLiteral(item.description)
444 ? item.description.data
445 : ""
446
447 if (!typeName || !itemType) {
448 return
449 }
450
451 const itemListChildren = item.children || []
452 const children: UnistNode[] = [
453 {
454 type: "paragraph",
455 children: [
456 {
457 type: "text",
458 value: `${typeName}: (${itemType}) ${itemDescription}`.trim(),
459 },
460 ],
461 },
462 ]
463
464 if (Array.isArray(itemListChildren) && itemListChildren.length) {
465 children.push(...generateTypeListItems(itemListChildren))
466 }
467
468 listItems.push({
469 type: "listItem",
470 children,
471 })
472 })
473
474 return listItems
475 }
476
477 const listItems = generateTypeListItems(typesJsVar)
478
479 parent?.children.splice(index, 1, {
480 type: "list",
481 ordered: false,
482 spread: false,
483 children: listItems,
484 })
485 return [SKIP, index]
486 }
487
488 export const parseWorkflowDiagram: ComponentParser = (
489 node: UnistNodeWithData,
490 index: number,
491 parent: UnistTree
492 ): VisitorResult => {
493 const worflowItems = node.attributes?.find((attr) => attr.name === "workflow")
494 if (
495 !worflowItems ||
496 typeof worflowItems.value === "string" ||
497 !worflowItems.value.data?.estree
498 ) {
499 return
500 }
501
502 const workflowJsVar = estreeToJs(worflowItems.value.data.estree)
503
504 if (
505 !isExpressionJsVarObj(workflowJsVar) ||
506 !("steps" in workflowJsVar) ||
507 !Array.isArray(workflowJsVar.steps)
508 ) {
509 return
510 }
511
512 const generateWorkflowItems = (
513 jsVarItems: ExpressionJsVar[]
514 ): UnistNode[] => {
515 const listItems: UnistNode[] = []
516
517 jsVarItems.forEach((item) => {
518 if (!isExpressionJsVarObj(item)) {
519 return
520 }
521
522 const stepName = isExpressionJsVarLiteral(item.name) ? item.name.data : ""
523 const stepDescription = isExpressionJsVarLiteral(item.description)
524 ? item.description.data
525 : ""
526 const stepLink = isExpressionJsVarLiteral(item.link)
527 ? (item.link.data as string)
528 : `#${stepName}`
529
530 if (!stepName) {
531 return
532 }
533
534 const stepChildren = item.steps || []
535 const children: UnistNode[] = [
536 {
537 type: "paragraph",
538 children: [
539 {
540 type: "link",
541 url: stepLink,
542 children: [
543 {
544 type: "text",
545 value: `${stepName}`,
546 },
547 ],
548 },
549 {
550 type: "text",
551 value: `: ${stepDescription}`,
552 },
553 ],
554 },
555 ]
556
557 if (Array.isArray(stepChildren) && stepChildren.length) {
558 children.push(...generateWorkflowItems(stepChildren))
559 }
560
561 listItems.push({
562 type: "listItem",
563 children,
564 })
565 })
566
567 return listItems
568 }
569
570 const listItems = generateWorkflowItems(workflowJsVar.steps)
571
572 parent?.children.splice(index, 1, {
573 type: "list",
574 ordered: false,
575 spread: false,
576 children: listItems,
577 })
578 return [SKIP, index]
579 }
580
581 export const parseComponentExample: ComponentParser<{
582 examplesBasePath: string
583 }> = async (
584 node: UnistNodeWithData,
585 index: number,
586 parent: UnistTree,
587 options
588 ): Promise<VisitorResult> => {
589 if (!options?.examplesBasePath) {
590 return
591 }
592
593 const exampleName = node.attributes?.find((attr) => attr.name === "name")
594 if (!exampleName) {
595 return
596 }
597
598 const name = exampleName.value as string
599 const fileContent = await workerCompatibleFetch<string | null>({
600 url: `${options.examplesBasePath}/${name}.tsx`,
601 responseTransformer: async (res) => {
602 return res.ok ? res.text() : null
603 },
604 fallbackAction: async () => {
605 try {
606 return readFileSync(
607 path.join(options.examplesBasePath, `${name}.tsx`),
608 "utf-8"
609 )
610 } catch {
611 return null
612 }
613 },
614 })
615
616 if (!fileContent) {
617 return
618 }
619
620 parent.children?.splice(index, 1, {
621 type: "code",
622 lang: "tsx",
623 value: fileContent,
624 })
625 return [SKIP, index]
626 }
627
628 export const parseComponentReference: ComponentParser<{
629 specsPath: string
630 }> = async (
631 node: UnistNodeWithData,
632 index: number,
633 parent: UnistTree,
634 options
635 ): Promise<VisitorResult> => {
636 if (!options?.specsPath) {
637 return
638 }
639
640 const mainComponent = node.attributes?.find(
641 (attr) => attr.name === "mainComponent"
642 )?.value as string
643 if (!mainComponent) {
644 return
645 }
646
647 const componentNames: string[] = []
648
649 const componentsToShowAttr = node.attributes?.find(
650 (attr) => attr.name === "componentsToShow"
651 )
652
653 if (
654 componentsToShowAttr &&
655 typeof componentsToShowAttr.value !== "string" &&
656 componentsToShowAttr.value.data?.estree
657 ) {
658 const componentsToShowJsVar = estreeToJs(
659 componentsToShowAttr.value.data.estree
660 )
661
662 if (componentsToShowAttr && Array.isArray(componentsToShowJsVar)) {
663 componentNames.push(
664 ...componentsToShowJsVar
665 .map((item) => {
666 return isExpressionJsVarLiteral(item) ? (item.data as string) : ""
667 })
668 .filter((name) => name.length > 0)
669 )
670 }
671 }
672
673 if (!componentNames.length) {
674 componentNames.push(mainComponent)
675 }
676
677 const getComponentNodes = async (
678 componentName: string
679 ): Promise<UnistNode[]> => {
680 const componentSpecs = await workerCompatibleFetch<Documentation | null>({
681 url: `${options.specsPath}/${mainComponent}/${componentName}.json`,
682 responseTransformer: async (res) => {
683 return res.ok ? ((await res.json()) as Documentation) : null
684 },
685 fallbackAction: async () => {
686 try {
687 const componentSpecsFile = path.join(
688 options.specsPath,
689 mainComponent,
690 `${componentName}.json`
691 )
692 return JSON.parse(
693 readFileSync(componentSpecsFile, "utf-8")
694 ) as Documentation
695 } catch {
696 return null
697 }
698 },
699 })
700
701 if (!componentSpecs) {
702 return []
703 }
704
705 const componentNodes: UnistNode[] = [
706 {
707 type: "heading",
708 depth: 3,
709 children: [
710 {
711 type: "text",
712 value: `${componentName} Props`,
713 },
714 ],
715 },
716 ]
717
718 if (componentSpecs.description) {
719 componentNodes.push({
720 type: "paragraph",
721 children: [
722 {
723 type: "text",
724 value: componentSpecs.description,
725 },
726 ],
727 })
728 }
729
730 if (componentSpecs.props) {
731 const listNode: UnistNode = {
732 type: "list",
733 ordered: false,
734 spread: false,
735 children: [],
736 }
737
738 Object.entries(componentSpecs.props).forEach(([propName, propData]) => {
739 listNode.children?.push({
740 type: "listItem",
741 children: [
742 {
743 type: "paragraph",
744 children: [
745 {
746 type: "text",
747 value:
748 `${propName}: (${propData.type?.name || propData.tsType?.name}) ${propData.description || ""}${propData.defaultValue ? ` Default: ${propData.defaultValue.value}` : ""}`.trim(),
749 },
750 ],
751 },
752 ],
753 })
754 })
755
756 componentNodes.push(listNode)
757 }
758
759 return componentNodes
760 }
761
762 const nodeArrays = await Promise.all(componentNames.map(getComponentNodes))
763 parent.children?.splice(index, 1, ...nodeArrays.flat())
764 }
765
766 export const parsePackageInstall: ComponentParser = (
767 node: UnistNodeWithData,
768 index: number,
769 parent: UnistTree
770 ): VisitorResult => {
771 const packageName = node.attributes?.find(
772 (attr) => attr.name === "packageName"
773 )
774 if (!packageName) {
775 return
776 }
777
778 parent.children?.splice(index, 1, {
779 type: "code",
780 lang: "bash",
781 value: `npm install ${packageName.value}`,
782 })
783 return [SKIP, index]
784 }
785
786 export const parseIconSearch: ComponentParser<{ iconNames: string[] }> = (
787 node: UnistNodeWithData,
788 index: number,
789 parent: UnistTree,
790 options
791 ): VisitorResult => {
792 if (!options?.iconNames) {
793 return
794 }
795
796 parent.children?.splice(index, 1, {
797 type: "list",
798 ordered: false,
799 spread: false,
800 children: options.iconNames.map((iconName) => ({
801 type: "listItem",
802 children: [
803 {
804 type: "paragraph",
805 children: [
806 {
807 type: "text",
808 value: iconName,
809 },
810 ],
811 },
812 ],
813 })),
814 })
815 return [SKIP, index]
816 }
817
818 export const parseHookValues: ComponentParser<{
819 hooksData: {
820 [k: string]: {
821 value: string
822 type?: {
823 type: string
824 }
825 description?: string
826 }[]
827 }
828 }> = (
829 node: UnistNodeWithData,
830 index: number,
831 parent: UnistTree,
832 options
833 ): VisitorResult => {
834 if (!options?.hooksData) {
835 return
836 }
837
838 const hookName = node.attributes?.find((attr) => attr.name === "hook")
839
840 if (
841 !hookName ||
842 !hookName.value ||
843 typeof hookName.value !== "string" ||
844 !options.hooksData[hookName.value]
845 ) {
846 return
847 }
848
849 const hookData = options.hooksData[hookName.value]
850
851 const listItems = hookData.map((item) => {
852 return {
853 type: "listItem",
854 children: [
855 {
856 type: "paragraph",
857 children: [
858 {
859 type: "text",
860 value:
861 `${item.value}: (${item.type?.type}) ${item.description || ""}`.trim(),
862 },
863 ],
864 },
865 ],
866 }
867 })
868
869 parent.children?.splice(index, 1, {
870 type: "list",
871 ordered: false,
872 spread: false,
873 children: listItems,
874 })
875 return [SKIP, index]
876 }
877
878 export const parseColors: ComponentParser<{
879 colors: {
880 [k: string]: Record<string, string>
881 }
882 }> = (
883 node: UnistNodeWithData,
884 index: number,
885 parent: UnistTree,
886 options
887 ): VisitorResult => {
888 if (!options?.colors) {
889 return
890 }
891
892 parent.children?.splice(index, 1, {
893 type: "list",
894 ordered: false,
895 spread: false,
896 children: Object.entries(options.colors).flatMap(([section, colors]) => [
897 {
898 type: "heading",
899 depth: 3,
900 children: [
901 {
902 type: "text",
903 value: section,
904 },
905 ],
906 },
907 ...Object.entries(colors).map(([name, value]) => ({
908 type: "listItem",
909 children: [
910 {
911 type: "paragraph",
912 children: [
913 {
914 type: "text",
915 value: name,
916 },
917 {
918 type: "text",
919 value: `: ${value}`,
920 },
921 ],
922 },
923 ],
924 })),
925 ]),
926 })
927 }
928
929 export const parseSplitList: ComponentParser = (
930 node: UnistNodeWithData,
931 index: number,
932 parent: UnistTree
933 ): VisitorResult => {
934 const items = node.attributes?.find((attr) => attr.name === "items")
935
936 if (!items || typeof items.value === "string" || !items.value.data?.estree) {
937 return
938 }
939
940 const itemsJsVar = estreeToJs(items.value.data.estree)
941
942 if (!itemsJsVar || !Array.isArray(itemsJsVar)) {
943 return
944 }
945
946 const listItems = itemsJsVar
947 .map((item) => {
948 if (
949 !isExpressionJsVarObj(item) ||
950 !("title" in item) ||
951 !("link" in item) ||
952 !isExpressionJsVarLiteral(item.title) ||
953 !isExpressionJsVarLiteral(item.link)
954 ) {
955 return null
956 }
957 const description = isExpressionJsVarLiteral(item.description)
958 ? (item.description.data as string)
959 : ""
960 return {
961 type: "listItem",
962 children: [
963 {
964 type: "paragraph",
965 children: [
966 {
967 type: "link",
968 url: `${item.link.data}`,
969 children: [
970 {
971 type: "text",
972 value: `${item.title.data}${description ? `: ${description}` : ""}`,
973 },
974 ],
975 },
976 ],
977 },
978 ],
979 }
980 })
981 .filter(Boolean) as UnistNode[]
982 if (!listItems.length) {
983 return
984 }
985 parent?.children.splice(index, 1, {
986 type: "list",
987 ordered: false,
988 spread: false,
989 children: listItems,
990 })
991 return [SKIP, index]
992 }
993
994 export const parseEventHeader: ComponentParser = (
995 node: UnistNodeWithData,
996 index: number,
997 parent: UnistTree
998 ): VisitorResult => {
999 const headerContent = node.attributes?.find(
1000 (attr) => attr.name === "headerProps"
1001 )
1002 const headerLvl = node.attributes?.find((attr) => attr.name === "headerLvl")
1003
1004 if (
1005 !headerContent ||
1006 typeof headerContent.value === "string" ||
1007 !headerContent.value.data?.estree ||
1008 !headerLvl ||
1009 typeof headerLvl.value !== "string" ||
1010 !headerLvl.value
1011 ) {
1012 return
1013 }
1014
1015 const headerPropsJsVar = estreeToJs(headerContent.value.data.estree)
1016
1017 if (
1018 !isExpressionJsVarObj(headerPropsJsVar) ||
1019 !("children" in headerPropsJsVar) ||
1020 !isExpressionJsVarLiteral(headerPropsJsVar.children)
1021 ) {
1022 return
1023 }
1024
1025 const headerLevel = parseInt(headerLvl.value, 10)
1026 const headerChildren = headerPropsJsVar.children.data as string
1027
1028 const headerChildrenNode = {
1029 type: "text",
1030 value: headerChildren,
1031 }
1032 const headerNode = {
1033 type: "heading",
1034 depth: headerLevel,
1035 children: [headerChildrenNode],
1036 }
1037
1038 parent?.children.splice(index, 1, headerNode)
1039 return [SKIP, index]
1040 }
1041
1042 /**
1043 * `ChildDocs` renders cards/links for the child items of a sidebar or a
1044 * sidebar item, so it has no `items` prop to read from the node. Instead, the
1045 * sidebar to render and the current page's path are passed as parser options
1046 * (resolved by the consuming app), and this parser mirrors the rendering logic
1047 * of the `useChildDocs` hook in `docs-ui`, producing headings + link lists.
1048 */
1049 export type ChildDocsParserOptions = {
1050 sidebar?: Sidebar.Sidebar
1051 activePath?: string
1052 }
1053
1054 const isChildDocsLink = (
1055 item: Sidebar.SidebarItem | undefined
1056 ): item is Sidebar.SidebarItemLink =>
1057 item !== undefined &&
1058 (item.type === "link" || item.type === "ref" || item.type === "external")
1059
1060 const getChildDocsAttr = (node: UnistNodeWithData, name: string) =>
1061 node.attributes?.find((attr) => attr.name === name)
1062
1063 const readChildDocsExpression = (attr: { value: unknown } | undefined) => {
1064 const value = attr?.value
1065 if (!value || typeof value === "string") {
1066 return undefined
1067 }
1068 const estree = (value as { data?: { estree?: unknown } }).data?.estree
1069 if (!estree) {
1070 return undefined
1071 }
1072 return estreeToJs(estree as Parameters<typeof estreeToJs>[0])
1073 }
1074
1075 const readChildDocsStringProp = (
1076 node: UnistNodeWithData,
1077 name: string
1078 ): string | undefined => {
1079 const attr = getChildDocsAttr(node, name)
1080 if (!attr) {
1081 return undefined
1082 }
1083 if (typeof attr.value === "string") {
1084 return attr.value
1085 }
1086 const js = readChildDocsExpression(attr)
1087 return isExpressionJsVarLiteral(js) ? String(js.data) : undefined
1088 }
1089
1090 const readChildDocsBooleanProp = (
1091 node: UnistNodeWithData,
1092 name: string
1093 ): boolean | undefined => {
1094 const attr = getChildDocsAttr(node, name)
1095 if (!attr) {
1096 return undefined
1097 }
1098 // a bare attribute (e.g. `hideTitle`) has no value and means `true`
1099 if (attr.value === null || attr.value === undefined) {
1100 return true
1101 }
1102 if (typeof attr.value === "string") {
1103 return attr.value !== "false"
1104 }
1105 const js = readChildDocsExpression(attr)
1106 return isExpressionJsVarLiteral(js) ? Boolean(js.data) : true
1107 }
1108
1109 const readChildDocsNumberProp = (
1110 node: UnistNodeWithData,
1111 name: string
1112 ): number | undefined => {
1113 const js = readChildDocsExpression(getChildDocsAttr(node, name))
1114 if (!isExpressionJsVarLiteral(js)) {
1115 return undefined
1116 }
1117 const num = Number(js.data)
1118 return isNaN(num) ? undefined : num
1119 }
1120
1121 const readChildDocsStringArrayProp = (
1122 node: UnistNodeWithData,
1123 name: string
1124 ): string[] | undefined => {
1125 const js = readChildDocsExpression(getChildDocsAttr(node, name))
1126 if (!Array.isArray(js)) {
1127 return undefined
1128 }
1129 return js.filter(isExpressionJsVarLiteral).map((item) => String(item.data))
1130 }
1131
1132 const filterNonInteractiveChildDocsItems = (
1133 items: Sidebar.SidebarItem[] | undefined
1134 ): Sidebar.InteractiveSidebarItem[] =>
1135 (items?.filter(
1136 (item) => item.type !== "separator" && !item.hideFromChildItems
1137 ) as Sidebar.InteractiveSidebarItem[]) || []
1138
1139 // Depth-first search for the first descendant link, mirroring
1140 // `getFirstLinkChild` in `docs-ui` (only `link`-type items are matched).
1141 const getChildDocsFirstLink = (
1142 items: Sidebar.SidebarItem[] | undefined
1143 ): Sidebar.SidebarItemLink | undefined => {
1144 let found: Sidebar.SidebarItemLink | undefined
1145 items?.some((item) => {
1146 if (item.type === "link") {
1147 found = item
1148 } else if ("children" in item && item.children) {
1149 found = getChildDocsFirstLink(item.children)
1150 }
1151 return found !== undefined
1152 })
1153 return found
1154 }
1155
1156 // `link` items hold an app-relative path (the base URL/path is added later by
1157 // the consuming pipeline); `ref`/external items already hold a full URL.
1158 const resolveChildDocsHref = (
1159 item: Sidebar.InteractiveSidebarItem
1160 ): string | undefined =>
1161 isChildDocsLink(item) ? item.path : getChildDocsFirstLink(item.children)?.path
1162
1163 type ChildDocsRenderContext = {
1164 hideTitle: boolean
1165 hideDescription: boolean
1166 titleLevel: number
1167 startChildLevel: number
1168 endChildLevel: number
1169 }
1170
1171 const getChildDocsChildrenForLevel = (
1172 item: Sidebar.InteractiveSidebarItem,
1173 currentLevel: number,
1174 ctx: ChildDocsRenderContext
1175 ): Sidebar.InteractiveSidebarItem[] | undefined => {
1176 if (
1177 (ctx.endChildLevel > 0 && currentLevel > ctx.endChildLevel) ||
1178 !item.children ||
1179 item.hideFromChildItems
1180 ) {
1181 return undefined
1182 }
1183 if (currentLevel >= ctx.startChildLevel) {
1184 return filterNonInteractiveChildDocsItems(item.children)
1185 }
1186 const result: Sidebar.InteractiveSidebarItem[] = []
1187 filterNonInteractiveChildDocsItems(item.children).forEach((child) => {
1188 const childChildren = getChildDocsChildrenForLevel(
1189 child,
1190 currentLevel + 1,
1191 ctx
1192 )
1193 if (childChildren) {
1194 result.push(...childChildren)
1195 }
1196 })
1197 return result
1198 }
1199
1200 const buildChildDocsLinkList = (
1201 items: Sidebar.InteractiveSidebarItem[],
1202 ctx: ChildDocsRenderContext
1203 ): UnistNode | undefined => {
1204 const listItems = items
1205 .map((item) => {
1206 const href = resolveChildDocsHref(item)
1207 if (!href) {
1208 return undefined
1209 }
1210 const children: UnistNode[] = [
1211 {
1212 type: "link",
1213 url: href,
1214 children: [{ type: "text", value: item.title }],
1215 },
1216 ]
1217 if (item.description) {
1218 children.push({ type: "text", value: `: ${item.description}` })
1219 }
1220 return {
1221 type: "listItem",
1222 children: [{ type: "paragraph", children }],
1223 }
1224 })
1225 .filter(Boolean) as UnistNode[]
1226
1227 if (!listItems.length) {
1228 return undefined
1229 }
1230 return { type: "list", ordered: false, spread: false, children: listItems }
1231 }
1232
1233 const buildChildDocsAllLevels = (
1234 items: Sidebar.InteractiveSidebarItem[],
1235 headerLevel: number,
1236 currentLevel: number,
1237 ctx: ChildDocsRenderContext
1238 ): UnistNode[] => {
1239 const nodes: UnistNode[] = []
1240 items.forEach((item, key) => {
1241 const itemChildren = getChildDocsChildrenForLevel(item, currentLevel, ctx)
1242 const hasHeading = !!itemChildren?.length
1243 const linkChildren = (itemChildren || []).filter(
1244 (child) => isChildDocsLink(child) || child.type === "sidebar"
1245 )
1246 const categoryChildren = (itemChildren || []).filter(
1247 (child) => child.type === "category" || child.type === "sub-category"
1248 )
1249 const showLinkAsCard = !hasHeading && isChildDocsLink(item)
1250
1251 if (hasHeading) {
1252 if (!ctx.hideTitle) {
1253 nodes.push({
1254 type: "heading",
1255 depth: Math.min(Math.max(headerLevel, 1), 6),
1256 children: [{ type: "text", value: item.title }],
1257 })
1258 if (!ctx.hideDescription && item.description) {
1259 nodes.push({
1260 type: "paragraph",
1261 children: [{ type: "text", value: item.description }],
1262 })
1263 }
1264 }
1265 if (linkChildren.length) {
1266 const list = buildChildDocsLinkList(linkChildren, ctx)
1267 if (list) {
1268 nodes.push(list)
1269 }
1270 }
1271 if (categoryChildren.length) {
1272 nodes.push(
1273 ...buildChildDocsAllLevels(
1274 categoryChildren,
1275 headerLevel + 1,
1276 currentLevel + 1,
1277 ctx
1278 )
1279 )
1280 }
1281 if (key !== items.length - 1 && headerLevel === 2) {
1282 nodes.push({ type: "thematicBreak" })
1283 }
1284 }
1285
1286 if (showLinkAsCard) {
1287 const href = resolveChildDocsHref(item)
1288 if (href) {
1289 const children: UnistNode[] = [
1290 {
1291 type: "link",
1292 url: href,
1293 children: [{ type: "text", value: item.title }],
1294 },
1295 ]
1296 if (item.description) {
1297 children.push({ type: "text", value: `: ${item.description}` })
1298 }
1299 nodes.push({ type: "paragraph", children })
1300 }
1301 }
1302 })
1303 return nodes
1304 }
1305
1306 const findChildDocsActiveItem = (
1307 items: Sidebar.SidebarItem[] | undefined,
1308 activePath: string
1309 ): Sidebar.InteractiveSidebarItem | undefined => {
1310 const normalized = activePath.replace(/\/$/, "")
1311 for (const item of items || []) {
1312 if (item.type === "separator") {
1313 continue
1314 }
1315 if (isChildDocsLink(item) && item.path.replace(/\/$/, "") === normalized) {
1316 return item
1317 }
1318 const found = findChildDocsActiveItem(item.children, activePath)
1319 if (found) {
1320 return found
1321 }
1322 }
1323 return undefined
1324 }
1325
1326 export const parseChildDocs: ComponentParser<ChildDocsParserOptions> = (
1327 node: UnistNodeWithData,
1328 index: number,
1329 parent: UnistTree,
1330 options
1331 ): VisitorResult => {
1332 const sidebar = options?.sidebar
1333 if (!sidebar) {
1334 // no sidebar available: drop the component so no broken output remains
1335 parent?.children.splice(index, 1)
1336 return [SKIP, index]
1337 }
1338
1339 const type = readChildDocsStringProp(node, "type") ?? "sidebar"
1340 const showItems = readChildDocsStringArrayProp(node, "showItems")
1341 const hideItems = readChildDocsStringArrayProp(node, "hideItems") ?? []
1342 const onlyTopLevel = readChildDocsBooleanProp(node, "onlyTopLevel") ?? false
1343 const ctx: ChildDocsRenderContext = {
1344 hideTitle: readChildDocsBooleanProp(node, "hideTitle") ?? false,
1345 hideDescription: readChildDocsBooleanProp(node, "hideDescription") ?? false,
1346 titleLevel: readChildDocsNumberProp(node, "titleLevel") ?? 2,
1347 startChildLevel: readChildDocsNumberProp(node, "startChildLevel") ?? 1,
1348 endChildLevel: readChildDocsNumberProp(node, "endChildLevel") ?? -1,
1349 }
1350
1351 const baseItems =
1352 type === "item"
1353 ? findChildDocsActiveItem(sidebar.items, options?.activePath ?? "")
1354 ?.children || []
1355 : sidebar.items
1356
1357 const filterType =
1358 showItems !== undefined ? "show" : hideItems.length > 0 ? "hide" : "all"
1359
1360 const filterCondition = (item: Sidebar.SidebarItem): boolean => {
1361 if (item.type === "separator") {
1362 return false
1363 }
1364 switch (filterType) {
1365 case "hide":
1366 return (
1367 (!isChildDocsLink(item) || !hideItems.includes(item.path)) &&
1368 !hideItems.includes(item.title)
1369 )
1370 case "show":
1371 return (
1372 (isChildDocsLink(item) && showItems!.includes(item.path)) ||
1373 showItems!.includes(item.title)
1374 )
1375 default:
1376 return true
1377 }
1378 }
1379
1380 const filterItems = (
1381 items: Sidebar.SidebarItem[]
1382 ): Sidebar.InteractiveSidebarItem[] =>
1383 (items.filter(filterCondition) as Sidebar.InteractiveSidebarItem[])
1384 .map((item) => Object.assign({}, item))
1385 .map((item) => {
1386 if (item.children && filterType === "hide") {
1387 item.children = filterItems(item.children)
1388 }
1389 return item
1390 })
1391
1392 const filteredItems = filterNonInteractiveChildDocsItems(
1393 filterType !== "all" ? filterItems(baseItems) : baseItems
1394 )
1395
1396 const replacement: UnistNode[] = onlyTopLevel
1397 ? (() => {
1398 const list = buildChildDocsLinkList(filteredItems, ctx)
1399 return list ? [list] : []
1400 })()
1401 : buildChildDocsAllLevels(filteredItems, ctx.titleLevel, 1, ctx)
1402
1403 parent?.children.splice(index, 1, ...replacement)
1404 return [SKIP, index]
1405 }
1406
1407 /**
1408 * Helpers
1409 */
1410 const getTextNode = (node: UnistNode): UnistNode | undefined => {
1411 let textNode: UnistNode | undefined
1412 node.children?.some((child) => {
1413 if (textNode) {
1414 return true
1415 }
1416 if (child.type === "text") {
1417 textNode = child
1418 } else if (child.type === "paragraph") {
1419 textNode = getTextNode(child)
1420 } else if (child.type === "link") {
1421 textNode = getTextNode(child)
1422 } else if (child.value) {
1423 textNode = child
1424 }
1425
1426 return textNode !== undefined
1427 })
1428
1429 return textNode
1430 }
1431
1432 const formatNodeText = (node?: UnistNode): string => {
1433 if (!node) {
1434 return ""
1435 }
1436 if (node.type === "inlineCode") {
1437 return `\`${node.value}\``
1438 } else if (node.type === "code") {
1439 return `\`\`\`${"lang" in node ? node.lang : "ts"}\n${node.value}\n\`\`\``
1440 } else if (node.type === "link") {
1441 return `[${node.children?.[0].value}](${node.url})`
1442 }
1443
1444 return node.value || ""
1445 }
1446
1447 export type InjectedMarkdownParserOptions = {
1448 /**
1449 * The Markdown of the content that the component renders. The component
1450 * loads its content from outside the MDX file, such as generated files or a
1451 * CMS, so the content must be passed by the consuming project.
1452 */
1453 content?: string
1454 }
1455
1456 /**
1457 * Replaces a component, such as `<ChangelogList />`, with the Markdown of the
1458 * content it renders, so the Markdown version of a page holds the same content
1459 * as the page itself.
1460 */
1461 export const parseInjectedMarkdown: ComponentParser<
1462 InjectedMarkdownParserOptions
1463 > = async (
1464 node: UnistNodeWithData,
1465 index: number,
1466 parent: UnistTree,
1467 options
1468 ): Promise<VisitorResult> => {
1469 const content = options?.content?.trim()
1470
1471 if (!content) {
1472 // no content available: drop the component so no broken output remains
1473 parent?.children.splice(index, 1)
1474 return [SKIP, index]
1475 }
1476
1477 const { unified } = await import("unified")
1478 const { default: remarkParse } = await import("remark-parse")
1479 const tree = unified().use(remarkParse).parse(content) as unknown as UnistTree
1480
1481 parent?.children.splice(index, 1, ...tree.children)
1482
1483 // Skip past the inserted nodes, since they're plain Markdown and don't need
1484 // to be visited again.
1485 return [SKIP, index + tree.children.length]
1486 }