forked from stenciljs/output-targets
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-stencil-react-components.ts
More file actions
247 lines (224 loc) · 8.79 KB
/
create-stencil-react-components.ts
File metadata and controls
247 lines (224 loc) · 8.79 KB
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
import type { ComponentCompilerMeta } from '@stencil/core/internal';
import { Project, VariableDeclarationKind } from 'ts-morph';
import { eventListenerName, kebabToPascalCase, normalizeTypeString } from './utils/string-utils.js';
import type { RenderToStringOptions } from './runtime/ssr.js';
interface ReactEvent {
originalName: string;
name: string;
type: string;
}
export const createStencilReactComponents = ({
components,
stencilPackageName,
customElementsDir,
hydrateModule,
clientModule,
serializeShadowRoot,
transformTag,
}: {
components: ComponentCompilerMeta[];
stencilPackageName: string;
customElementsDir: string;
hydrateModule?: string;
clientModule?: string;
serializeShadowRoot?: RenderToStringOptions['serializeShadowRoot'];
transformTag?: boolean;
}) => {
const project = new Project({ useInMemoryFileSystem: true });
/**
* automatically attach the `use client` directive if we are not generating
* server side rendering components.
*/
const useClientDirective = `'use client';\n\n`;
const autogeneratedComment = `/**
* This file was automatically generated by the Stencil React Output Target.
* Changes to this file may cause incorrect behavior and will be lost if the code is regenerated.
*/\n\n`;
const disableEslint = `/* eslint-disable */\n`;
const getTagTransformerImport = transformTag ? `import { getTagTransformer } from './tag-transformer.js';\n` : '';
const createComponentImport = hydrateModule
? [
getTagTransformerImport,
`import { createComponent, type SerializeShadowRootOptions, type HydrateModule, type ReactWebComponent } from '@stencil/react-output-target/ssr';`,
]
.filter(Boolean)
.join('\n')
: `import { createComponent } from '@stencil/react-output-target/runtime';`;
// transformTag should be imported from tag-transformer for both client and server
const transformTagImport = transformTag ? `import { transformTag } from './tag-transformer.js';\n` : '';
const sourceFile = project.createSourceFile(
'component.ts',
`${useClientDirective}${autogeneratedComment}${disableEslint}
import React from 'react';
${createComponentImport}
import type { EventName, StencilReactComponent } from '@stencil/react-output-target/runtime';
${transformTagImport}
import type { Components } from "${stencilPackageName}/${customElementsDir}";
`
);
/**
* Add the `clientComponents` import if hydrateModule is provided.
* This import needs a @ts-ignore comment, which will be added after organizeImports().
*/
if (hydrateModule && clientModule) {
sourceFile.addImportDeclaration({
moduleSpecifier: clientModule,
namespaceImport: 'clientComponents',
});
}
/**
* Add the `serializeShadowRoot` variable to the file if the hydrateModule is provided.
*/
if (hydrateModule) {
sourceFile.addVariableStatement({
isExported: true,
declarationKind: VariableDeclarationKind.Const,
declarations: [
{
name: 'serializeShadowRoot',
type: 'SerializeShadowRootOptions',
initializer: serializeShadowRoot
? JSON.stringify(serializeShadowRoot)
: '{ default: "declarative-shadow-dom" }',
},
],
});
}
for (const component of components) {
const tagName = component.tagName;
const reactTagName = kebabToPascalCase(tagName);
const componentElement = `${reactTagName}Element`;
const componentCustomEvent = `${reactTagName}CustomEvent`;
sourceFile.addImportDeclaration({
moduleSpecifier: `${stencilPackageName}/${customElementsDir}/${tagName}.js`,
namedImports: [
{
name: reactTagName,
alias: componentElement,
},
{
name: 'defineCustomElement',
alias: `define${reactTagName}`,
},
],
});
const publicEvents = (component.events || []).filter((e) => e.internal === false);
const events: ReactEvent[] = [];
const importedEventDetailTypes = new Set<string>();
let importedComponentCustomEvent = false;
for (const event of publicEvents) {
/**
* Import the referenced types from the component library.
* Stencil will automatically re-export type definitions from the components,
* if they are used in the component's property or event types.
*/
if (Object.keys(event.complexType.references).length > 0) {
for (const referenceKey of Object.keys(event.complexType.references)) {
const reference = event.complexType.references[referenceKey];
const isGlobalType = reference.location === 'global';
/**
* Global type references should not have an explicit import.
* The type should be available globally.
*/
if (!isGlobalType && !importedEventDetailTypes.has(referenceKey)) {
importedEventDetailTypes.add(referenceKey);
sourceFile.addImportDeclaration({
moduleSpecifier: stencilPackageName,
namedImports: [
{
name: referenceKey,
isTypeOnly: true,
},
],
});
}
}
}
/**
* Import the CustomEvent type for the web component from the Stencil package.
*
* For example:
* ```
* import type { ComponentCustomEvent } from 'my-component-library';
* ```
*/
if (!importedComponentCustomEvent) {
importedComponentCustomEvent = true;
sourceFile.addImportDeclaration({
moduleSpecifier: stencilPackageName,
namedImports: [
{
name: componentCustomEvent,
isTypeOnly: true,
},
],
});
}
// Always type events using the Stencil per-component CustomEvent type.
events.push({
originalName: event.name,
name: eventListenerName(event.name),
type: `EventName<${componentCustomEvent}<${normalizeTypeString(event.complexType.original)}>>`,
});
}
const componentEventNamesType = `${reactTagName}Events`;
sourceFile.addTypeAlias({
isExported: true,
name: componentEventNamesType,
type: events.length > 0 ? `{ ${events.map((e) => `${e.name}: ${e.type}`).join(',\n')} }` : 'NonNullable<unknown>',
});
const transformTagParam = transformTag ? ',\n transformTag' : '';
const clientComponentCall = `/*@__PURE__*/ createComponent<${componentElement}, ${componentEventNamesType}, Components.${reactTagName}>({
tagName: '${tagName}',
elementClass: ${componentElement},
// @ts-ignore - ignore potential React type mismatches between the Stencil Output Target and your project.
react: React,
events: {${events.map((e) => `${e.name}: '${e.originalName}'`).join(',\n')}} as ${componentEventNamesType},
defineCustomElement: define${reactTagName}${transformTagParam}
})`;
const getTagTransformerParam = transformTag ? ',\n getTagTransformer' : '';
const serverComponentCall = `/*@__PURE__*/ createComponent<${componentElement}, ${componentEventNamesType}, Components.${reactTagName}>({
tagName: '${tagName}',
properties: {${component.properties
/**
* Filter out properties that don't have an attribute.
* These are properties with complex types and can't be serialized.
*/
.filter((prop) => Boolean(prop.attribute))
.map((e) => `${e.name}: '${e.attribute}'`)
.join(',\n')}},
hydrateModule: typeof window === 'undefined' ? (import('${hydrateModule}') as Promise<HydrateModule>) : undefined,
clientModule: clientComponents.${reactTagName} as StencilReactComponent<${componentElement}, ${componentEventNamesType}, Components.${reactTagName}>,
serializeShadowRoot${getTagTransformerParam}
})`;
sourceFile.addVariableStatement({
isExported: true,
declarationKind: VariableDeclarationKind.Const,
declarations: [
{
name: reactTagName,
type: `StencilReactComponent<${componentElement}, ${componentEventNamesType}, Components.${reactTagName}>`,
initializer: hydrateModule ? serverComponentCall : clientComponentCall,
},
],
});
}
sourceFile.organizeImports();
/**
* Add the @ts-ignore comment to the clientComponents import after organizeImports()
* to ensure the comment stays attached to the correct import.
*/
if (hydrateModule && clientModule) {
const clientComponentsImport = sourceFile
.getImportDeclarations()
.find((imp) => imp.getNamespaceImport()?.getText() === 'clientComponents');
if (clientComponentsImport) {
sourceFile.insertText(
clientComponentsImport.getStart(),
'// @ts-ignore - ignore potential type issues as the project is importing itself\n'
);
}
}
sourceFile.formatText();
return sourceFile.getFullText();
};