diff options
Diffstat (limited to 'subprojects/docs/src/plugins/remarkPluginUtils.ts')
-rw-r--r-- | subprojects/docs/src/plugins/remarkPluginUtils.ts | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/subprojects/docs/src/plugins/remarkPluginUtils.ts b/subprojects/docs/src/plugins/remarkPluginUtils.ts new file mode 100644 index 00000000..1dabcd11 --- /dev/null +++ b/subprojects/docs/src/plugins/remarkPluginUtils.ts | |||
@@ -0,0 +1,58 @@ | |||
1 | /* | ||
2 | * Copyright (c) Facebook, Inc. and its affiliates. | ||
3 | * Copyright (c) 2024 The Refinery Authors | ||
4 | * | ||
5 | * SPDX-License-Identifier: MIT AND EPL-2.0 | ||
6 | * | ||
7 | * This file is based on | ||
8 | * https://github.com/facebook/docusaurus/blob/e4ecffe41878728acff55a8370bd7440706c02f7/packages/docusaurus-remark-plugin-npm2yarn/src/index.ts | ||
9 | */ | ||
10 | |||
11 | import type { Code, Literal } from 'mdast'; | ||
12 | import type { Node, Parent } from 'unist'; | ||
13 | |||
14 | export function isParent(node: Node): node is Parent { | ||
15 | return 'children' in node && Array.isArray(node.children); | ||
16 | } | ||
17 | |||
18 | export function replaceChildrenRecursively<T extends Node>( | ||
19 | node: Node, | ||
20 | shoulReplace: (node: Node) => node is T, | ||
21 | replacement: (node: T) => Node[], | ||
22 | ): boolean { | ||
23 | if (!isParent(node)) { | ||
24 | return false; | ||
25 | } | ||
26 | let didReplace = false; | ||
27 | let index = 0; | ||
28 | while (index < node.children.length) { | ||
29 | const child = node.children[index]; | ||
30 | if (child !== undefined && shoulReplace(child)) { | ||
31 | const result = replacement(child); | ||
32 | node.children.splice(index, 1, ...result); | ||
33 | index += result.length; | ||
34 | didReplace = true; | ||
35 | } else { | ||
36 | if ( | ||
37 | child !== undefined && | ||
38 | replaceChildrenRecursively(child, shoulReplace, replacement) | ||
39 | ) { | ||
40 | didReplace = true; | ||
41 | } | ||
42 | index += 1; | ||
43 | } | ||
44 | } | ||
45 | return didReplace; | ||
46 | } | ||
47 | |||
48 | export function isCode(node: Node): node is Code { | ||
49 | return node.type === 'code'; | ||
50 | } | ||
51 | |||
52 | export function isLiteral(node: Node): node is Literal { | ||
53 | return node.type === 'mdxjsEsm'; | ||
54 | } | ||
55 | |||
56 | export function isImport(node: Node, importedPath: string): boolean { | ||
57 | return isLiteral(node) && node.value.includes(importedPath); | ||
58 | } | ||