-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathrecma-provide-components.ts
103 lines (100 loc) · 3.15 KB
/
recma-provide-components.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
/* eslint-disable @typescript-eslint/no-explicit-any */
import type {
Node,
FunctionDeclaration,
VariableDeclarator,
VariableDeclaration,
CallExpression,
Literal,
} from 'estree-jsx';
function isNamedFunction(node: FunctionDeclaration, name: string) {
return Boolean(node.id?.name === name);
}
export const recmaProvideComponents = () => {
let id = 0;
return (tree: { body: any[] }) => {
const replacement = [];
for (const _node of tree.body) {
const node = _node as Node;
if (node.type === 'FunctionDeclaration' && node.id) {
if (
isNamedFunction(node, 'MDXContent') ||
isNamedFunction(node, '_createMdxContent')
) {
/**
* Transforms function MDXContent (props = {}) {...}
* to const MDXContent = _componentQrl(_inlinedQrl(function (props = {}) {...}, 'symbolName', []))
* allows using Qwik hooks inside
* */
const symbolName = `${node.id?.name || 'mdx'}_${id++}`;
const declarations: VariableDeclarator[] = [
{
id: node.id,
type: 'VariableDeclarator',
init: {
type: 'CallExpression',
callee: {
type: 'Identifier',
name: '_componentQrl',
},
arguments: [
{
type: 'CallExpression',
callee: {
type: 'Identifier',
name: '_inlinedQrl',
},
arguments: [
{
type: 'ArrowFunctionExpression',
id: null,
params: node.params,
body: node.body,
async: node.async,
generator: node.generator,
},
{
type: 'Literal',
value: symbolName,
raw: String.raw`"${symbolName}"`,
} as Literal,
{
type: 'ArrayExpression',
elements: [],
},
],
} as CallExpression,
],
} as CallExpression,
},
];
const newNode: VariableDeclaration = {
type: 'VariableDeclaration',
kind: 'const',
declarations,
};
replacement.push(newNode);
continue;
}
}
replacement.push(_node);
}
tree.body = replacement;
tree.body.unshift({
type: 'ImportDeclaration',
specifiers: [
{
type: 'ImportSpecifier',
imported: { type: 'Identifier', name: 'componentQrl' },
local: { type: 'Identifier', name: '_componentQrl' },
},
{
type: 'ImportSpecifier',
imported: { type: 'Identifier', name: 'inlinedQrl' },
local: { type: 'Identifier', name: '_inlinedQrl' },
},
],
source: { type: 'Literal', value: '@qwik.dev/core' },
});
};
};