@knapsack/renderer-react 4.90.0--canary.6591.86eb714.0 → 4.90.0--canary.7255.526ffd7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/dist/analyze/infer-spec.d.mts.map +1 -1
- package/dist/analyze/infer-spec.mjs.map +1 -1
- package/dist/analyze/utils/react-component-analyzer.mjs +7 -11
- package/dist/analyze/utils/react-component-analyzer.mjs.map +1 -1
- package/dist/react-creators.js +3 -3
- package/dist/react-creators.js.map +1 -1
- package/dist/renderer-react.js +463 -474
- package/dist/renderer-react.js.map +1 -1
- package/dist/utils.js +25 -24
- package/dist/utils.js.map +1 -1
- package/package.json +19 -19
- package/vitest.config.mts +1 -0
package/dist/renderer-react.js
CHANGED
|
@@ -1,16 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
-
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
-
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
-
};
|
|
8
|
-
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
-
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
-
};
|
|
13
|
-
var _KnapsackReactRenderer_demoWrapperPath, _KnapsackReactRenderer_disableReactStrictMode;
|
|
14
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
3
|
exports.KnapsackReactRenderer = void 0;
|
|
16
4
|
const renderer_webpack_base_1 = require("@knapsack/renderer-webpack-base");
|
|
@@ -50,6 +38,13 @@ See https://reactjs.org/docs/strict-mode.html for more info
|
|
|
50
38
|
codeSrcs: zod_1.z.array(types_1.CodeSrcUserConfigSchema).optional(),
|
|
51
39
|
});
|
|
52
40
|
class KnapsackReactRenderer extends renderer_webpack_base_1.RendererWebpackBase {
|
|
41
|
+
/**
|
|
42
|
+
* `react.js` & `react-dom.js` root relative paths
|
|
43
|
+
*/
|
|
44
|
+
assets;
|
|
45
|
+
babelConfig;
|
|
46
|
+
#demoWrapperPath;
|
|
47
|
+
#disableReactStrictMode;
|
|
53
48
|
constructor(options = {}) {
|
|
54
49
|
const { error } = OptionsSchema.safeParse(options);
|
|
55
50
|
const { webpackConfig, demoWrapperPath, disableReactStrictMode, codeSrcs } = options;
|
|
@@ -63,463 +58,6 @@ class KnapsackReactRenderer extends renderer_webpack_base_1.RendererWebpackBase
|
|
|
63
58
|
(0, path_1.join)(__dirname, '../dist/client/init.mjs'),
|
|
64
59
|
],
|
|
65
60
|
});
|
|
66
|
-
_KnapsackReactRenderer_demoWrapperPath.set(this, void 0);
|
|
67
|
-
_KnapsackReactRenderer_disableReactStrictMode.set(this, void 0);
|
|
68
|
-
this.setConfig = (opt) => {
|
|
69
|
-
super.setConfig(opt);
|
|
70
|
-
const { absolutePath, exists: demoWrapperPathExists, type, } = this.resolvePathSync({
|
|
71
|
-
path: __classPrivateFieldGet(this, _KnapsackReactRenderer_demoWrapperPath, "f"),
|
|
72
|
-
resolveFromDir: this.userConfigDir,
|
|
73
|
-
});
|
|
74
|
-
if (!demoWrapperPathExists) {
|
|
75
|
-
throw new Error(`Could not find demo wrapper at: "${__classPrivateFieldGet(this, _KnapsackReactRenderer_demoWrapperPath, "f")}"\nPlease adjust setting in "knapsack.config.js" or pass a different path when creating the React Renderer.`);
|
|
76
|
-
}
|
|
77
|
-
this.registerExtraJsImports({
|
|
78
|
-
DemoWrapper: {
|
|
79
|
-
exportName: 'DemoWrapper',
|
|
80
|
-
isDefaultExport: true,
|
|
81
|
-
path: type === 'package' ? __classPrivateFieldGet(this, _KnapsackReactRenderer_demoWrapperPath, "f") : absolutePath,
|
|
82
|
-
},
|
|
83
|
-
});
|
|
84
|
-
};
|
|
85
|
-
this.init = async (opt) => {
|
|
86
|
-
await super.init(opt);
|
|
87
|
-
};
|
|
88
|
-
this.hydrate = async (opt) => {
|
|
89
|
-
await super.hydrate(opt);
|
|
90
|
-
await this.init({ missingFileVerbosity: 'silent' });
|
|
91
|
-
};
|
|
92
|
-
this.getMeta = () => ({
|
|
93
|
-
id: this.id,
|
|
94
|
-
title: 'React',
|
|
95
|
-
aliasUse: 'optional',
|
|
96
|
-
aliasTitle: 'Named Export',
|
|
97
|
-
aliasIsJsNamedExport: true,
|
|
98
|
-
aliasDescription: 'If `export X` was used instead of `export default`, then provide X.',
|
|
99
|
-
enableDataDemos: true,
|
|
100
|
-
enableTemplateDemos: true,
|
|
101
|
-
hasSlotsSupport: true,
|
|
102
|
-
hasSlotOptionsSupport: true,
|
|
103
|
-
version: pkg.version,
|
|
104
|
-
hasInferSpecSupport: true,
|
|
105
|
-
syntaxHighlightingLanguage: 'jsx',
|
|
106
|
-
hasTemplateSuggestionsSupport: true,
|
|
107
|
-
prototypingTemplate: {
|
|
108
|
-
path: '@knapsack/renderer-react/prototype-template',
|
|
109
|
-
spec: {
|
|
110
|
-
isInferred: false,
|
|
111
|
-
props: {
|
|
112
|
-
type: 'object',
|
|
113
|
-
properties: {},
|
|
114
|
-
},
|
|
115
|
-
slots: {
|
|
116
|
-
children: { title: 'Children' },
|
|
117
|
-
},
|
|
118
|
-
},
|
|
119
|
-
},
|
|
120
|
-
});
|
|
121
|
-
this.changeCase = (str) => (0, utils_1.pascalCase)(str);
|
|
122
|
-
this.render = async (opt) => {
|
|
123
|
-
var _a;
|
|
124
|
-
if (((_a = opt.demo) === null || _a === void 0 ? void 0 : _a.type) === 'template') {
|
|
125
|
-
const { absolutePath: templateDemoPath, exists } = await this.resolvePath(opt.demo.templateInfo.path);
|
|
126
|
-
if (!exists) {
|
|
127
|
-
throw new Error(`Template demo file does not exist: "${opt.demo.templateInfo.path}"`);
|
|
128
|
-
}
|
|
129
|
-
const [templateFileContents, { usage, importMap }] = await Promise.all([
|
|
130
|
-
(0, file_utils_1.readFile)(templateDemoPath),
|
|
131
|
-
this.getUsageAndImports({
|
|
132
|
-
...opt,
|
|
133
|
-
importMap: new Map(),
|
|
134
|
-
}),
|
|
135
|
-
]);
|
|
136
|
-
const demoApp = await (0, utils_2.getDemoAppUsage)({
|
|
137
|
-
children: usage,
|
|
138
|
-
});
|
|
139
|
-
const results = await this.prepClientRenderResults({
|
|
140
|
-
usage: templateFileContents,
|
|
141
|
-
demoApp,
|
|
142
|
-
renderOptions: opt,
|
|
143
|
-
importMap,
|
|
144
|
-
});
|
|
145
|
-
return results;
|
|
146
|
-
}
|
|
147
|
-
if ((0, types_1.isDemoWithData)(opt.demo)) {
|
|
148
|
-
const { usage, importMap } = await this.getUsageAndImports({
|
|
149
|
-
...opt,
|
|
150
|
-
importMap: new Map(),
|
|
151
|
-
});
|
|
152
|
-
const importCode = renderer_webpack_base_1.RendererWebpackBase.createJsImportCodeBlock({
|
|
153
|
-
importMap,
|
|
154
|
-
});
|
|
155
|
-
const [demoAppUsage, demoApp] = await Promise.all([
|
|
156
|
-
(0, utils_2.getDemoAppUsage)({
|
|
157
|
-
children: usage,
|
|
158
|
-
imports: importCode,
|
|
159
|
-
format: true,
|
|
160
|
-
}),
|
|
161
|
-
(0, utils_2.getDemoAppUsage)({
|
|
162
|
-
children: usage,
|
|
163
|
-
}),
|
|
164
|
-
]);
|
|
165
|
-
return this.prepClientRenderResults({
|
|
166
|
-
demoApp,
|
|
167
|
-
usage: demoAppUsage,
|
|
168
|
-
renderOptions: opt,
|
|
169
|
-
importMap,
|
|
170
|
-
});
|
|
171
|
-
}
|
|
172
|
-
const _exhaustiveCheck = opt.demo;
|
|
173
|
-
throw new Error(`Unhandled demo type at reactRenderer.render`);
|
|
174
|
-
};
|
|
175
|
-
this.getUsageAndImports = async ({ demo, state, importMap, }) => {
|
|
176
|
-
if (!demo) {
|
|
177
|
-
throw new Error(`No demo provided while rendering `);
|
|
178
|
-
}
|
|
179
|
-
if ((0, types_1.isDemoWithData)(demo)) {
|
|
180
|
-
const { data: { props, slots, slotsOptionsComputed }, } = demo;
|
|
181
|
-
const { codeSrcPath, exportName } = this.normalizeDemo({
|
|
182
|
-
demo,
|
|
183
|
-
state,
|
|
184
|
-
});
|
|
185
|
-
if (!codeSrcPath) {
|
|
186
|
-
throw new Error(`Could not determine code source path for demo: ${JSON.stringify(demo)}`);
|
|
187
|
-
}
|
|
188
|
-
const { name: templateName } = await this.addUniqueValueToImportMap({
|
|
189
|
-
importMap,
|
|
190
|
-
path: codeSrcPath,
|
|
191
|
-
alias: exportName,
|
|
192
|
-
});
|
|
193
|
-
const children = [];
|
|
194
|
-
const extraProps = [];
|
|
195
|
-
if (slots) {
|
|
196
|
-
const slotNames = Object.keys(slots);
|
|
197
|
-
const slotUsages = await Promise.all(slotNames.map(async (slotName) => {
|
|
198
|
-
const slotItems = slots[slotName];
|
|
199
|
-
const slotItemsUsages = await Promise.all(slotItems
|
|
200
|
-
// remove any incomplete item - happens when users are filling out form
|
|
201
|
-
.filter((slotItem) => {
|
|
202
|
-
if (!slotItem)
|
|
203
|
-
return false;
|
|
204
|
-
if (slotItem.type !== 'text') {
|
|
205
|
-
if (slotItem.type === 'template-demo' && !slotItem.demoId) {
|
|
206
|
-
return false;
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
return true;
|
|
210
|
-
})
|
|
211
|
-
.map(async (slotItem) => {
|
|
212
|
-
var _a;
|
|
213
|
-
if (slotItem.type === 'text') {
|
|
214
|
-
if (slotItems.length === 1 && slotName !== 'children') {
|
|
215
|
-
// The ` prevents multi-line strings from causing error (even though they don't show a line break)
|
|
216
|
-
return `\`${slotItem.text}\``;
|
|
217
|
-
}
|
|
218
|
-
return slotItem.text;
|
|
219
|
-
}
|
|
220
|
-
if (slotItem.type === 'template-reference') {
|
|
221
|
-
const slottedTemplate = (_a = state.patterns[slotItem.patternId]) === null || _a === void 0 ? void 0 : _a.templates.find((t) => t.id === slotItem.templateId);
|
|
222
|
-
if (!slottedTemplate) {
|
|
223
|
-
throw new Error(`Could not find slotted template: ${slotItem.patternId} ${slotItem.templateId}`);
|
|
224
|
-
}
|
|
225
|
-
const pathInfo = (0, file_utils_1.getPathType)(slottedTemplate.path);
|
|
226
|
-
if (pathInfo.type === 'absolute') {
|
|
227
|
-
throw new Error(`Absolute paths are not supported for slotted templates: ${slottedTemplate.path}`);
|
|
228
|
-
}
|
|
229
|
-
const templateRefImport = await this.addUniqueValueToImportMap({
|
|
230
|
-
importMap,
|
|
231
|
-
path: pathInfo.path,
|
|
232
|
-
alias: slottedTemplate.alias || 'default',
|
|
233
|
-
});
|
|
234
|
-
/**
|
|
235
|
-
* i.e. Given a React Component, `Button`, normally this would be `<Button>` with a demo, but since there is none this will just be a reference to it: `Button`
|
|
236
|
-
* @see {KsSlotInfo['isTemplateReference']}
|
|
237
|
-
* @see {SlottedTemplate}
|
|
238
|
-
*/
|
|
239
|
-
return templateRefImport.name;
|
|
240
|
-
}
|
|
241
|
-
if (slotItem.type === 'template-demo') {
|
|
242
|
-
const thisDemo = slotItem.demo;
|
|
243
|
-
if (!thisDemo) {
|
|
244
|
-
throw new Error(`Could not find slotted template demo ${JSON.stringify(slotItem)}`);
|
|
245
|
-
}
|
|
246
|
-
const { usage } = await this.getUsageAndImports({
|
|
247
|
-
demo: thisDemo,
|
|
248
|
-
state,
|
|
249
|
-
importMap,
|
|
250
|
-
});
|
|
251
|
-
return usage;
|
|
252
|
-
}
|
|
253
|
-
const _exhaustiveCheck = slotItem;
|
|
254
|
-
throw new Error(`Unknown slot item: ${JSON.stringify(slotItem)}`);
|
|
255
|
-
}));
|
|
256
|
-
return {
|
|
257
|
-
slotName,
|
|
258
|
-
slotItemsUsages,
|
|
259
|
-
};
|
|
260
|
-
}));
|
|
261
|
-
slotUsages.forEach(({ slotName, slotItemsUsages }) => {
|
|
262
|
-
const slotOptionsComputed = slotsOptionsComputed === null || slotsOptionsComputed === void 0 ? void 0 : slotsOptionsComputed[slotName];
|
|
263
|
-
const { openTag, closeTag } = (0, renderers_1.createSlotOptionsHtmlTags)({
|
|
264
|
-
slotOptionsComputed,
|
|
265
|
-
classAttributeName: 'className',
|
|
266
|
-
stylesValueType: 'object',
|
|
267
|
-
});
|
|
268
|
-
if (openTag) {
|
|
269
|
-
if (slotName === 'children') {
|
|
270
|
-
children.push(openTag);
|
|
271
|
-
}
|
|
272
|
-
else {
|
|
273
|
-
extraProps.push({
|
|
274
|
-
key: slotName,
|
|
275
|
-
value: openTag,
|
|
276
|
-
});
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
slotItemsUsages.forEach((usage) => {
|
|
280
|
-
if (slotName === 'children') {
|
|
281
|
-
children.push(usage);
|
|
282
|
-
}
|
|
283
|
-
else {
|
|
284
|
-
extraProps.push({
|
|
285
|
-
key: slotName,
|
|
286
|
-
value: usage,
|
|
287
|
-
});
|
|
288
|
-
}
|
|
289
|
-
});
|
|
290
|
-
if (closeTag) {
|
|
291
|
-
if (slotName === 'children') {
|
|
292
|
-
children.push(closeTag);
|
|
293
|
-
}
|
|
294
|
-
else {
|
|
295
|
-
extraProps.push({
|
|
296
|
-
key: slotName,
|
|
297
|
-
value: closeTag,
|
|
298
|
-
});
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
});
|
|
302
|
-
}
|
|
303
|
-
const usage = await (0, utils_2.getUsage)({
|
|
304
|
-
templateName,
|
|
305
|
-
props,
|
|
306
|
-
children: children.join('\n'),
|
|
307
|
-
extraProps,
|
|
308
|
-
});
|
|
309
|
-
return {
|
|
310
|
-
usage,
|
|
311
|
-
importMap,
|
|
312
|
-
};
|
|
313
|
-
}
|
|
314
|
-
if (demo.type === 'template') {
|
|
315
|
-
const { templateInfo } = demo;
|
|
316
|
-
const pathInfo = (0, file_utils_1.getPathType)(templateInfo.path);
|
|
317
|
-
if (pathInfo.type === 'absolute') {
|
|
318
|
-
throw new Error(`Absolute paths are not supported for templates: ${templateInfo.path}`);
|
|
319
|
-
}
|
|
320
|
-
const { name: templateName } = await this.addUniqueValueToImportMap({
|
|
321
|
-
importMap,
|
|
322
|
-
path: pathInfo.path,
|
|
323
|
-
alias: templateInfo.alias || 'default',
|
|
324
|
-
});
|
|
325
|
-
const usage = await (0, utils_2.getUsage)({ templateName });
|
|
326
|
-
return {
|
|
327
|
-
usage,
|
|
328
|
-
importMap,
|
|
329
|
-
};
|
|
330
|
-
}
|
|
331
|
-
const _exhaustiveCheck = demo;
|
|
332
|
-
throw new Error(`Unhandled demo type at reactRenderer.getUsageAndImports`);
|
|
333
|
-
};
|
|
334
|
-
this.getDiscovery = async () => {
|
|
335
|
-
const codeSrcPaths = this.getCodeSrcs().map(({ path }) => path);
|
|
336
|
-
const results = await Promise.all(codeSrcPaths.map(async (path) => {
|
|
337
|
-
try {
|
|
338
|
-
const { exports, errorMsg } = await (0, file_utils_1.getJsExportNames)({
|
|
339
|
-
path,
|
|
340
|
-
resolveFromDir: this.dataDir,
|
|
341
|
-
pkgPathAliases: this.pkgPathAliases,
|
|
342
|
-
});
|
|
343
|
-
if (errorMsg) {
|
|
344
|
-
throw new Error(errorMsg);
|
|
345
|
-
}
|
|
346
|
-
return {
|
|
347
|
-
path,
|
|
348
|
-
exportNames: exports
|
|
349
|
-
// only allow names that start with a capital letter (i.e. React Component names)
|
|
350
|
-
// will exclude helper functions and custom hooks
|
|
351
|
-
.filter((e) => e === 'default' || (0, utils_1.isFirstLetterCapital)(e)),
|
|
352
|
-
};
|
|
353
|
-
}
|
|
354
|
-
catch (e) {
|
|
355
|
-
this.log.warn(`Could not get import names for "${path}": ${e.message}`, null, this.logPrefix);
|
|
356
|
-
return { path, exportNames: [] };
|
|
357
|
-
}
|
|
358
|
-
}));
|
|
359
|
-
return {
|
|
360
|
-
rendererId: this.id,
|
|
361
|
-
meta: this.getMeta(),
|
|
362
|
-
codeSrcsByPath: Object.fromEntries(this.codeSrcs.entries()),
|
|
363
|
-
templates: results.flatMap(({ path, exportNames }) => exportNames.map((exportName) => (0, types_1.addIdToTemplateInfo)({
|
|
364
|
-
rendererId: this.id,
|
|
365
|
-
codeSrcPath: path,
|
|
366
|
-
exportName,
|
|
367
|
-
}))),
|
|
368
|
-
};
|
|
369
|
-
};
|
|
370
|
-
this.inspect = async (templateInfo) => {
|
|
371
|
-
const { codeSrcPath, exportName } = templateInfo;
|
|
372
|
-
const { inferSpec } = await import('./analyze/index.mjs');
|
|
373
|
-
const { ksTemplateSpec: spec } = await inferSpec({
|
|
374
|
-
path: codeSrcPath,
|
|
375
|
-
namedExport: exportName,
|
|
376
|
-
resolveFrom: this.dataDir,
|
|
377
|
-
pkgPathAliases: this.pkgPathAliases,
|
|
378
|
-
});
|
|
379
|
-
return {
|
|
380
|
-
type: 'success',
|
|
381
|
-
spec,
|
|
382
|
-
};
|
|
383
|
-
};
|
|
384
|
-
this.watch = async () => {
|
|
385
|
-
super.watch();
|
|
386
|
-
app_1.knapsackEvents.onPatternTemplateChanged(() => {
|
|
387
|
-
(0, utils_2.clearInferSpecCache)();
|
|
388
|
-
});
|
|
389
|
-
};
|
|
390
|
-
this.getTemplateMeta = async ({ pattern, template, }) => {
|
|
391
|
-
const files = [];
|
|
392
|
-
if ((0, types_1.isSpecNotInferred)(template.spec)) {
|
|
393
|
-
const schema = JSON.parse(JSON.stringify(template.spec.props || {}));
|
|
394
|
-
if (template.spec.slots) {
|
|
395
|
-
Object.entries(template.spec.slots).forEach(([id, info]) => {
|
|
396
|
-
var _a;
|
|
397
|
-
schema.properties[id] = {
|
|
398
|
-
typeof: 'function',
|
|
399
|
-
tsType: 'React.ReactNode',
|
|
400
|
-
description: info.allowedPatternIds
|
|
401
|
-
? `${info.description}. Only use: ${info.allowedPatternIds.join(', ')}`
|
|
402
|
-
: info.description,
|
|
403
|
-
};
|
|
404
|
-
schema.required = (_a = schema.required) !== null && _a !== void 0 ? _a : [];
|
|
405
|
-
if (info.isRequired)
|
|
406
|
-
schema.required.push(id);
|
|
407
|
-
});
|
|
408
|
-
}
|
|
409
|
-
const typeDefs = await KnapsackReactRenderer.convertSchemaToTypeScriptDefs({
|
|
410
|
-
schema,
|
|
411
|
-
title: `${this.changeCase(pattern.id)}Props`,
|
|
412
|
-
// @todo pull in base url
|
|
413
|
-
description: `[Knapsack Docs](http://localhost:3999/pattern/${pattern.id}/${template.id})`,
|
|
414
|
-
patternId: pattern.id,
|
|
415
|
-
templateId: template.id,
|
|
416
|
-
postBanner: `import * as React from 'react';`,
|
|
417
|
-
});
|
|
418
|
-
files.push({
|
|
419
|
-
contents: typeDefs,
|
|
420
|
-
encoding: 'utf8',
|
|
421
|
-
path: `${pattern.id}.${template.id}.spec.d.ts`,
|
|
422
|
-
});
|
|
423
|
-
files.push({
|
|
424
|
-
contents: JSON.stringify(schema, null, ' '),
|
|
425
|
-
encoding: 'utf8',
|
|
426
|
-
path: `${pattern.id}.${template.id}.spec.json`,
|
|
427
|
-
});
|
|
428
|
-
}
|
|
429
|
-
return files;
|
|
430
|
-
};
|
|
431
|
-
this.alterTemplateMetaFiles = async ({ files, metaDir, }) => {
|
|
432
|
-
const imports = [];
|
|
433
|
-
const ext = '.spec.d.ts';
|
|
434
|
-
files.forEach((file) => {
|
|
435
|
-
if (file.path.endsWith(ext)) {
|
|
436
|
-
const { base } = (0, path_1.parse)(file.path);
|
|
437
|
-
const [patternId, templateId] = base.split('.');
|
|
438
|
-
const isFirst = templateId === this.id;
|
|
439
|
-
const exportName = this.changeCase(`${patternId}Props`);
|
|
440
|
-
const exportNameWithTemplateId = this.changeCase(`${patternId}-${templateId}Props`);
|
|
441
|
-
imports.push(`export { ${isFirst
|
|
442
|
-
? exportName
|
|
443
|
-
: `${exportName} as ${exportNameWithTemplateId}`} } from './${(0, path_1.relative)(metaDir, file.path).replace('.d.ts', '')}';`);
|
|
444
|
-
}
|
|
445
|
-
});
|
|
446
|
-
// extra line at end of file
|
|
447
|
-
imports.push('');
|
|
448
|
-
return [
|
|
449
|
-
...files,
|
|
450
|
-
{
|
|
451
|
-
contents: imports.join('\n'),
|
|
452
|
-
encoding: 'utf8',
|
|
453
|
-
path: (0, path_1.join)(metaDir, 'react.d.ts'),
|
|
454
|
-
},
|
|
455
|
-
];
|
|
456
|
-
};
|
|
457
|
-
this.getTemplateSuggestions = async ({ newPath, state, }) => {
|
|
458
|
-
// Deduplicate suggestions using Map with stringified path/alias as keys.
|
|
459
|
-
// Map values are suggestion objects, Array.from(map.values()) returns deduplicated array.
|
|
460
|
-
const usedSuggestions = Array.from(new Map(Object.values(state.patterns).reduce((acc, { templateDemos, templates }) => {
|
|
461
|
-
templates.forEach(({ path, alias, templateLanguageId }) => {
|
|
462
|
-
if (templateLanguageId !== this.id)
|
|
463
|
-
return;
|
|
464
|
-
acc.push([JSON.stringify({ path, alias }), { path, alias }]);
|
|
465
|
-
});
|
|
466
|
-
templateDemos.forEach(({ templateInfo: { path, alias }, templateLanguageId }) => {
|
|
467
|
-
if (templateLanguageId !== this.id)
|
|
468
|
-
return;
|
|
469
|
-
acc.push([JSON.stringify({ path, alias }), { path, alias }]);
|
|
470
|
-
});
|
|
471
|
-
return acc;
|
|
472
|
-
}, [])).values());
|
|
473
|
-
const codeSrcs = new Set(this.getCodeSrcs().map(({ path }) => path));
|
|
474
|
-
const allPaths = [
|
|
475
|
-
...new Set([
|
|
476
|
-
newPath,
|
|
477
|
-
...Object.keys(this.pkgPathAliases || {}),
|
|
478
|
-
...codeSrcs,
|
|
479
|
-
]),
|
|
480
|
-
];
|
|
481
|
-
// @todo use getDiscovery
|
|
482
|
-
const allSuggestions = await Promise.all(allPaths.map(async (path) => {
|
|
483
|
-
if (!path)
|
|
484
|
-
return [];
|
|
485
|
-
try {
|
|
486
|
-
const { exports, errorMsg } = await (0, file_utils_1.getJsExportNames)({
|
|
487
|
-
path,
|
|
488
|
-
resolveFromDir: this.dataDir,
|
|
489
|
-
pkgPathAliases: this.pkgPathAliases,
|
|
490
|
-
});
|
|
491
|
-
if (errorMsg) {
|
|
492
|
-
throw new Error(errorMsg);
|
|
493
|
-
}
|
|
494
|
-
return (exports
|
|
495
|
-
// only allow names that start with a capital letter (i.e. React Component names)
|
|
496
|
-
// will exclude helper functions and custom hooks
|
|
497
|
-
.filter((e) => e === 'default' || (0, utils_1.isFirstLetterCapital)(e))
|
|
498
|
-
.map((name) => ({
|
|
499
|
-
alias: name,
|
|
500
|
-
path,
|
|
501
|
-
})));
|
|
502
|
-
}
|
|
503
|
-
catch (e) {
|
|
504
|
-
// only want this showing with verbose since template suggestions are not critical
|
|
505
|
-
this.log.verbose(`Error getting import names for ${path}: ${e.message}`, null, this.logPrefix);
|
|
506
|
-
return [];
|
|
507
|
-
}
|
|
508
|
-
})).then((results) => {
|
|
509
|
-
// sadly `Promise.all` & `.flatMap` just don't work, so this:
|
|
510
|
-
return results.flat();
|
|
511
|
-
});
|
|
512
|
-
const suggestions = allSuggestions.filter((s) => {
|
|
513
|
-
return !usedSuggestions.find((us) => us.alias === s.alias && us.path === s.path);
|
|
514
|
-
});
|
|
515
|
-
const connectedSuggestions = usedSuggestions.map((s) => ({
|
|
516
|
-
...s,
|
|
517
|
-
connected: true,
|
|
518
|
-
}));
|
|
519
|
-
return {
|
|
520
|
-
suggestions: [...suggestions, ...connectedSuggestions],
|
|
521
|
-
};
|
|
522
|
-
};
|
|
523
61
|
if (error) {
|
|
524
62
|
this.log.error(`"KnapsackReactRenderer" constructor has invalid options, please fix in "knapsack.config.cjs":`, zod_1.z.prettifyError(error));
|
|
525
63
|
process.exit(1);
|
|
@@ -527,10 +65,10 @@ class KnapsackReactRenderer extends renderer_webpack_base_1.RendererWebpackBase
|
|
|
527
65
|
}
|
|
528
66
|
this.language = 'jsx';
|
|
529
67
|
this.assets = [];
|
|
530
|
-
|
|
68
|
+
this.#disableReactStrictMode = disableReactStrictMode;
|
|
531
69
|
this.creators = [react_creators_1.createReactPattern];
|
|
532
70
|
if (demoWrapperPath) {
|
|
533
|
-
|
|
71
|
+
this.#demoWrapperPath = demoWrapperPath;
|
|
534
72
|
}
|
|
535
73
|
else {
|
|
536
74
|
const defaultDemoWrapperPath = '@knapsack/renderer-react-components/demo-wrapper';
|
|
@@ -543,13 +81,67 @@ class KnapsackReactRenderer extends renderer_webpack_base_1.RendererWebpackBase
|
|
|
543
81
|
if (!exists) {
|
|
544
82
|
throw new Error(`Could not locate the default Demo Wrapper component at "${defaultDemoWrapperPath}". This is an internal error and may be caused by a NPM install issue.`);
|
|
545
83
|
}
|
|
546
|
-
|
|
84
|
+
this.#demoWrapperPath = absolutePath;
|
|
547
85
|
}
|
|
548
86
|
}
|
|
87
|
+
setConfig = (opt) => {
|
|
88
|
+
super.setConfig(opt);
|
|
89
|
+
const { absolutePath, exists: demoWrapperPathExists, type, } = this.resolvePathSync({
|
|
90
|
+
path: this.#demoWrapperPath,
|
|
91
|
+
resolveFromDir: this.userConfigDir,
|
|
92
|
+
});
|
|
93
|
+
if (!demoWrapperPathExists) {
|
|
94
|
+
throw new Error(`Could not find demo wrapper at: "${this.#demoWrapperPath}"\nPlease adjust setting in "knapsack.config.js" or pass a different path when creating the React Renderer.`);
|
|
95
|
+
}
|
|
96
|
+
this.registerExtraJsImports({
|
|
97
|
+
DemoWrapper: {
|
|
98
|
+
exportName: 'DemoWrapper',
|
|
99
|
+
isDefaultExport: true,
|
|
100
|
+
path: type === 'package' ? this.#demoWrapperPath : absolutePath,
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
};
|
|
104
|
+
init = async (opt) => {
|
|
105
|
+
await super.init(opt);
|
|
106
|
+
};
|
|
107
|
+
hydrate = async (opt) => {
|
|
108
|
+
await super.hydrate(opt);
|
|
109
|
+
await this.init({ missingFileVerbosity: 'silent' });
|
|
110
|
+
};
|
|
111
|
+
getMeta = () => ({
|
|
112
|
+
id: this.id,
|
|
113
|
+
title: 'React',
|
|
114
|
+
aliasUse: 'optional',
|
|
115
|
+
aliasTitle: 'Named Export',
|
|
116
|
+
aliasIsJsNamedExport: true,
|
|
117
|
+
aliasDescription: 'If `export X` was used instead of `export default`, then provide X.',
|
|
118
|
+
enableDataDemos: true,
|
|
119
|
+
enableTemplateDemos: true,
|
|
120
|
+
hasSlotsSupport: true,
|
|
121
|
+
hasSlotOptionsSupport: true,
|
|
122
|
+
version: pkg.version,
|
|
123
|
+
hasInferSpecSupport: true,
|
|
124
|
+
syntaxHighlightingLanguage: 'jsx',
|
|
125
|
+
hasTemplateSuggestionsSupport: true,
|
|
126
|
+
prototypingTemplate: {
|
|
127
|
+
path: '@knapsack/renderer-react/prototype-template',
|
|
128
|
+
spec: {
|
|
129
|
+
isInferred: false,
|
|
130
|
+
props: {
|
|
131
|
+
type: 'object',
|
|
132
|
+
properties: {},
|
|
133
|
+
},
|
|
134
|
+
slots: {
|
|
135
|
+
children: { title: 'Children' },
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
},
|
|
139
|
+
});
|
|
140
|
+
changeCase = (str) => (0, utils_1.pascalCase)(str);
|
|
549
141
|
async prepClientRenderResults({ usage, demoApp, importMap, renderOptions: { demo }, }) {
|
|
550
142
|
const meta = {
|
|
551
143
|
demo,
|
|
552
|
-
disableReactStrictMode:
|
|
144
|
+
disableReactStrictMode: this.#disableReactStrictMode,
|
|
553
145
|
neededImportsByCodeSrcId: (0, renderer_webpack_base_1.convertImportMapToNeededImportsByCodeSrcId)(importMap),
|
|
554
146
|
demoWrapperProps: {
|
|
555
147
|
demo,
|
|
@@ -593,7 +185,404 @@ class KnapsackReactRenderer extends renderer_webpack_base_1.RendererWebpackBase
|
|
|
593
185
|
templateLanguage: this.language,
|
|
594
186
|
};
|
|
595
187
|
}
|
|
188
|
+
render = async (opt) => {
|
|
189
|
+
if (opt.demo?.type === 'template') {
|
|
190
|
+
const { absolutePath: templateDemoPath, exists } = await this.resolvePath(opt.demo.templateInfo.path);
|
|
191
|
+
if (!exists) {
|
|
192
|
+
throw new Error(`Template demo file does not exist: "${opt.demo.templateInfo.path}"`);
|
|
193
|
+
}
|
|
194
|
+
const [templateFileContents, { usage, importMap }] = await Promise.all([
|
|
195
|
+
(0, file_utils_1.readFile)(templateDemoPath),
|
|
196
|
+
this.getUsageAndImports({
|
|
197
|
+
...opt,
|
|
198
|
+
importMap: new Map(),
|
|
199
|
+
}),
|
|
200
|
+
]);
|
|
201
|
+
const demoApp = await (0, utils_2.getDemoAppUsage)({
|
|
202
|
+
children: usage,
|
|
203
|
+
});
|
|
204
|
+
const results = await this.prepClientRenderResults({
|
|
205
|
+
usage: templateFileContents,
|
|
206
|
+
demoApp,
|
|
207
|
+
renderOptions: opt,
|
|
208
|
+
importMap,
|
|
209
|
+
});
|
|
210
|
+
return results;
|
|
211
|
+
}
|
|
212
|
+
if ((0, types_1.isDemoWithData)(opt.demo)) {
|
|
213
|
+
const { usage, importMap } = await this.getUsageAndImports({
|
|
214
|
+
...opt,
|
|
215
|
+
importMap: new Map(),
|
|
216
|
+
});
|
|
217
|
+
const importCode = renderer_webpack_base_1.RendererWebpackBase.createJsImportCodeBlock({
|
|
218
|
+
importMap,
|
|
219
|
+
});
|
|
220
|
+
const [demoAppUsage, demoApp] = await Promise.all([
|
|
221
|
+
(0, utils_2.getDemoAppUsage)({
|
|
222
|
+
children: usage,
|
|
223
|
+
imports: importCode,
|
|
224
|
+
format: true,
|
|
225
|
+
}),
|
|
226
|
+
(0, utils_2.getDemoAppUsage)({
|
|
227
|
+
children: usage,
|
|
228
|
+
}),
|
|
229
|
+
]);
|
|
230
|
+
return this.prepClientRenderResults({
|
|
231
|
+
demoApp,
|
|
232
|
+
usage: demoAppUsage,
|
|
233
|
+
renderOptions: opt,
|
|
234
|
+
importMap,
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
const _exhaustiveCheck = opt.demo;
|
|
238
|
+
throw new Error(`Unhandled demo type at reactRenderer.render`);
|
|
239
|
+
};
|
|
240
|
+
getUsageAndImports = async ({ demo, state, importMap, }) => {
|
|
241
|
+
if (!demo) {
|
|
242
|
+
throw new Error(`No demo provided while rendering `);
|
|
243
|
+
}
|
|
244
|
+
if ((0, types_1.isDemoWithData)(demo)) {
|
|
245
|
+
const { data: { props, slots, slotsOptionsComputed }, } = demo;
|
|
246
|
+
const { codeSrcPath, exportName } = this.normalizeDemo({
|
|
247
|
+
demo,
|
|
248
|
+
state,
|
|
249
|
+
});
|
|
250
|
+
if (!codeSrcPath) {
|
|
251
|
+
throw new Error(`Could not determine code source path for demo: ${JSON.stringify(demo)}`);
|
|
252
|
+
}
|
|
253
|
+
const { name: templateName } = await this.addUniqueValueToImportMap({
|
|
254
|
+
importMap,
|
|
255
|
+
path: codeSrcPath,
|
|
256
|
+
alias: exportName,
|
|
257
|
+
});
|
|
258
|
+
const children = [];
|
|
259
|
+
const extraProps = [];
|
|
260
|
+
if (slots) {
|
|
261
|
+
const slotNames = Object.keys(slots);
|
|
262
|
+
const slotUsages = await Promise.all(slotNames.map(async (slotName) => {
|
|
263
|
+
const slotItems = slots[slotName];
|
|
264
|
+
const slotItemsUsages = await Promise.all(slotItems
|
|
265
|
+
// remove any incomplete item - happens when users are filling out form
|
|
266
|
+
.filter((slotItem) => {
|
|
267
|
+
if (!slotItem)
|
|
268
|
+
return false;
|
|
269
|
+
if (slotItem.type !== 'text') {
|
|
270
|
+
if (slotItem.type === 'template-demo' && !slotItem.demoId) {
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return true;
|
|
275
|
+
})
|
|
276
|
+
.map(async (slotItem) => {
|
|
277
|
+
if (slotItem.type === 'text') {
|
|
278
|
+
if (slotItems.length === 1 && slotName !== 'children') {
|
|
279
|
+
// The ` prevents multi-line strings from causing error (even though they don't show a line break)
|
|
280
|
+
return `\`${slotItem.text}\``;
|
|
281
|
+
}
|
|
282
|
+
return slotItem.text;
|
|
283
|
+
}
|
|
284
|
+
if (slotItem.type === 'template-reference') {
|
|
285
|
+
const slottedTemplate = state.patterns[slotItem.patternId]?.templates.find((t) => t.id === slotItem.templateId);
|
|
286
|
+
if (!slottedTemplate) {
|
|
287
|
+
throw new Error(`Could not find slotted template: ${slotItem.patternId} ${slotItem.templateId}`);
|
|
288
|
+
}
|
|
289
|
+
const pathInfo = (0, file_utils_1.getPathType)(slottedTemplate.path);
|
|
290
|
+
if (pathInfo.type === 'absolute') {
|
|
291
|
+
throw new Error(`Absolute paths are not supported for slotted templates: ${slottedTemplate.path}`);
|
|
292
|
+
}
|
|
293
|
+
const templateRefImport = await this.addUniqueValueToImportMap({
|
|
294
|
+
importMap,
|
|
295
|
+
path: pathInfo.path,
|
|
296
|
+
alias: slottedTemplate.alias || 'default',
|
|
297
|
+
});
|
|
298
|
+
/**
|
|
299
|
+
* i.e. Given a React Component, `Button`, normally this would be `<Button>` with a demo, but since there is none this will just be a reference to it: `Button`
|
|
300
|
+
* @see {KsSlotInfo['isTemplateReference']}
|
|
301
|
+
* @see {SlottedTemplate}
|
|
302
|
+
*/
|
|
303
|
+
return templateRefImport.name;
|
|
304
|
+
}
|
|
305
|
+
if (slotItem.type === 'template-demo') {
|
|
306
|
+
const thisDemo = slotItem.demo;
|
|
307
|
+
if (!thisDemo) {
|
|
308
|
+
throw new Error(`Could not find slotted template demo ${JSON.stringify(slotItem)}`);
|
|
309
|
+
}
|
|
310
|
+
const { usage } = await this.getUsageAndImports({
|
|
311
|
+
demo: thisDemo,
|
|
312
|
+
state,
|
|
313
|
+
importMap,
|
|
314
|
+
});
|
|
315
|
+
return usage;
|
|
316
|
+
}
|
|
317
|
+
const _exhaustiveCheck = slotItem;
|
|
318
|
+
throw new Error(`Unknown slot item: ${JSON.stringify(slotItem)}`);
|
|
319
|
+
}));
|
|
320
|
+
return {
|
|
321
|
+
slotName,
|
|
322
|
+
slotItemsUsages,
|
|
323
|
+
};
|
|
324
|
+
}));
|
|
325
|
+
slotUsages.forEach(({ slotName, slotItemsUsages }) => {
|
|
326
|
+
const slotOptionsComputed = slotsOptionsComputed?.[slotName];
|
|
327
|
+
const { openTag, closeTag } = (0, renderers_1.createSlotOptionsHtmlTags)({
|
|
328
|
+
slotOptionsComputed,
|
|
329
|
+
classAttributeName: 'className',
|
|
330
|
+
stylesValueType: 'object',
|
|
331
|
+
});
|
|
332
|
+
if (openTag) {
|
|
333
|
+
if (slotName === 'children') {
|
|
334
|
+
children.push(openTag);
|
|
335
|
+
}
|
|
336
|
+
else {
|
|
337
|
+
extraProps.push({
|
|
338
|
+
key: slotName,
|
|
339
|
+
value: openTag,
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
slotItemsUsages.forEach((usage) => {
|
|
344
|
+
if (slotName === 'children') {
|
|
345
|
+
children.push(usage);
|
|
346
|
+
}
|
|
347
|
+
else {
|
|
348
|
+
extraProps.push({
|
|
349
|
+
key: slotName,
|
|
350
|
+
value: usage,
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
if (closeTag) {
|
|
355
|
+
if (slotName === 'children') {
|
|
356
|
+
children.push(closeTag);
|
|
357
|
+
}
|
|
358
|
+
else {
|
|
359
|
+
extraProps.push({
|
|
360
|
+
key: slotName,
|
|
361
|
+
value: closeTag,
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
const usage = await (0, utils_2.getUsage)({
|
|
368
|
+
templateName,
|
|
369
|
+
props,
|
|
370
|
+
children: children.join('\n'),
|
|
371
|
+
extraProps,
|
|
372
|
+
});
|
|
373
|
+
return {
|
|
374
|
+
usage,
|
|
375
|
+
importMap,
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
if (demo.type === 'template') {
|
|
379
|
+
const { templateInfo } = demo;
|
|
380
|
+
const pathInfo = (0, file_utils_1.getPathType)(templateInfo.path);
|
|
381
|
+
if (pathInfo.type === 'absolute') {
|
|
382
|
+
throw new Error(`Absolute paths are not supported for templates: ${templateInfo.path}`);
|
|
383
|
+
}
|
|
384
|
+
const { name: templateName } = await this.addUniqueValueToImportMap({
|
|
385
|
+
importMap,
|
|
386
|
+
path: pathInfo.path,
|
|
387
|
+
alias: templateInfo.alias || 'default',
|
|
388
|
+
});
|
|
389
|
+
const usage = await (0, utils_2.getUsage)({ templateName });
|
|
390
|
+
return {
|
|
391
|
+
usage,
|
|
392
|
+
importMap,
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
const _exhaustiveCheck = demo;
|
|
396
|
+
throw new Error(`Unhandled demo type at reactRenderer.getUsageAndImports`);
|
|
397
|
+
};
|
|
398
|
+
getDiscovery = async () => {
|
|
399
|
+
const codeSrcPaths = this.getCodeSrcs().map(({ path }) => path);
|
|
400
|
+
const results = await Promise.all(codeSrcPaths.map(async (path) => {
|
|
401
|
+
try {
|
|
402
|
+
const { exports, errorMsg } = await (0, file_utils_1.getJsExportNames)({
|
|
403
|
+
path,
|
|
404
|
+
resolveFromDir: this.dataDir,
|
|
405
|
+
pkgPathAliases: this.pkgPathAliases,
|
|
406
|
+
});
|
|
407
|
+
if (errorMsg) {
|
|
408
|
+
throw new Error(errorMsg);
|
|
409
|
+
}
|
|
410
|
+
return {
|
|
411
|
+
path,
|
|
412
|
+
exportNames: exports
|
|
413
|
+
// only allow names that start with a capital letter (i.e. React Component names)
|
|
414
|
+
// will exclude helper functions and custom hooks
|
|
415
|
+
.filter((e) => e === 'default' || (0, utils_1.isFirstLetterCapital)(e)),
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
catch (e) {
|
|
419
|
+
this.log.warn(`Could not get import names for "${path}": ${e.message}`, null, this.logPrefix);
|
|
420
|
+
return { path, exportNames: [] };
|
|
421
|
+
}
|
|
422
|
+
}));
|
|
423
|
+
return {
|
|
424
|
+
rendererId: this.id,
|
|
425
|
+
meta: this.getMeta(),
|
|
426
|
+
codeSrcsByPath: Object.fromEntries(this.codeSrcs.entries()),
|
|
427
|
+
templates: results.flatMap(({ path, exportNames }) => exportNames.map((exportName) => (0, types_1.addIdToTemplateInfo)({
|
|
428
|
+
rendererId: this.id,
|
|
429
|
+
codeSrcPath: path,
|
|
430
|
+
exportName,
|
|
431
|
+
}))),
|
|
432
|
+
};
|
|
433
|
+
};
|
|
434
|
+
inspect = async (templateInfo) => {
|
|
435
|
+
const { codeSrcPath, exportName } = templateInfo;
|
|
436
|
+
const { inferSpec } = await import('./analyze/index.mjs');
|
|
437
|
+
const { ksTemplateSpec: spec } = await inferSpec({
|
|
438
|
+
path: codeSrcPath,
|
|
439
|
+
namedExport: exportName,
|
|
440
|
+
resolveFrom: this.dataDir,
|
|
441
|
+
pkgPathAliases: this.pkgPathAliases,
|
|
442
|
+
});
|
|
443
|
+
return {
|
|
444
|
+
type: 'success',
|
|
445
|
+
spec,
|
|
446
|
+
};
|
|
447
|
+
};
|
|
448
|
+
watch = async () => {
|
|
449
|
+
super.watch();
|
|
450
|
+
app_1.knapsackEvents.onPatternTemplateChanged(() => {
|
|
451
|
+
(0, utils_2.clearInferSpecCache)();
|
|
452
|
+
});
|
|
453
|
+
};
|
|
454
|
+
getTemplateMeta = async ({ pattern, template, }) => {
|
|
455
|
+
const files = [];
|
|
456
|
+
if ((0, types_1.isSpecNotInferred)(template.spec)) {
|
|
457
|
+
const schema = JSON.parse(JSON.stringify(template.spec.props || {}));
|
|
458
|
+
if (template.spec.slots) {
|
|
459
|
+
Object.entries(template.spec.slots).forEach(([id, info]) => {
|
|
460
|
+
schema.properties[id] = {
|
|
461
|
+
typeof: 'function',
|
|
462
|
+
tsType: 'React.ReactNode',
|
|
463
|
+
description: info.allowedPatternIds
|
|
464
|
+
? `${info.description}. Only use: ${info.allowedPatternIds.join(', ')}`
|
|
465
|
+
: info.description,
|
|
466
|
+
};
|
|
467
|
+
schema.required = schema.required ?? [];
|
|
468
|
+
if (info.isRequired)
|
|
469
|
+
schema.required.push(id);
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
const typeDefs = await KnapsackReactRenderer.convertSchemaToTypeScriptDefs({
|
|
473
|
+
schema,
|
|
474
|
+
title: `${this.changeCase(pattern.id)}Props`,
|
|
475
|
+
// @todo pull in base url
|
|
476
|
+
description: `[Knapsack Docs](http://localhost:3999/pattern/${pattern.id}/${template.id})`,
|
|
477
|
+
patternId: pattern.id,
|
|
478
|
+
templateId: template.id,
|
|
479
|
+
postBanner: `import * as React from 'react';`,
|
|
480
|
+
});
|
|
481
|
+
files.push({
|
|
482
|
+
contents: typeDefs,
|
|
483
|
+
encoding: 'utf8',
|
|
484
|
+
path: `${pattern.id}.${template.id}.spec.d.ts`,
|
|
485
|
+
});
|
|
486
|
+
files.push({
|
|
487
|
+
contents: JSON.stringify(schema, null, ' '),
|
|
488
|
+
encoding: 'utf8',
|
|
489
|
+
path: `${pattern.id}.${template.id}.spec.json`,
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
return files;
|
|
493
|
+
};
|
|
494
|
+
alterTemplateMetaFiles = async ({ files, metaDir, }) => {
|
|
495
|
+
const imports = [];
|
|
496
|
+
const ext = '.spec.d.ts';
|
|
497
|
+
files.forEach((file) => {
|
|
498
|
+
if (file.path.endsWith(ext)) {
|
|
499
|
+
const { base } = (0, path_1.parse)(file.path);
|
|
500
|
+
const [patternId, templateId] = base.split('.');
|
|
501
|
+
const isFirst = templateId === this.id;
|
|
502
|
+
const exportName = this.changeCase(`${patternId}Props`);
|
|
503
|
+
const exportNameWithTemplateId = this.changeCase(`${patternId}-${templateId}Props`);
|
|
504
|
+
imports.push(`export { ${isFirst
|
|
505
|
+
? exportName
|
|
506
|
+
: `${exportName} as ${exportNameWithTemplateId}`} } from './${(0, path_1.relative)(metaDir, file.path).replace('.d.ts', '')}';`);
|
|
507
|
+
}
|
|
508
|
+
});
|
|
509
|
+
// extra line at end of file
|
|
510
|
+
imports.push('');
|
|
511
|
+
return [
|
|
512
|
+
...files,
|
|
513
|
+
{
|
|
514
|
+
contents: imports.join('\n'),
|
|
515
|
+
encoding: 'utf8',
|
|
516
|
+
path: (0, path_1.join)(metaDir, 'react.d.ts'),
|
|
517
|
+
},
|
|
518
|
+
];
|
|
519
|
+
};
|
|
520
|
+
getTemplateSuggestions = async ({ newPath, state, }) => {
|
|
521
|
+
// Deduplicate suggestions using Map with stringified path/alias as keys.
|
|
522
|
+
// Map values are suggestion objects, Array.from(map.values()) returns deduplicated array.
|
|
523
|
+
const usedSuggestions = Array.from(new Map(Object.values(state.patterns).reduce((acc, { templateDemos, templates }) => {
|
|
524
|
+
templates.forEach(({ path, alias, templateLanguageId }) => {
|
|
525
|
+
if (templateLanguageId !== this.id)
|
|
526
|
+
return;
|
|
527
|
+
acc.push([JSON.stringify({ path, alias }), { path, alias }]);
|
|
528
|
+
});
|
|
529
|
+
templateDemos.forEach(({ templateInfo: { path, alias }, templateLanguageId }) => {
|
|
530
|
+
if (templateLanguageId !== this.id)
|
|
531
|
+
return;
|
|
532
|
+
acc.push([JSON.stringify({ path, alias }), { path, alias }]);
|
|
533
|
+
});
|
|
534
|
+
return acc;
|
|
535
|
+
}, [])).values());
|
|
536
|
+
const codeSrcs = new Set(this.getCodeSrcs().map(({ path }) => path));
|
|
537
|
+
const allPaths = [
|
|
538
|
+
...new Set([
|
|
539
|
+
newPath,
|
|
540
|
+
...Object.keys(this.pkgPathAliases || {}),
|
|
541
|
+
...codeSrcs,
|
|
542
|
+
]),
|
|
543
|
+
];
|
|
544
|
+
// @todo use getDiscovery
|
|
545
|
+
const allSuggestions = await Promise.all(allPaths.map(async (path) => {
|
|
546
|
+
if (!path)
|
|
547
|
+
return [];
|
|
548
|
+
try {
|
|
549
|
+
const { exports, errorMsg } = await (0, file_utils_1.getJsExportNames)({
|
|
550
|
+
path,
|
|
551
|
+
resolveFromDir: this.dataDir,
|
|
552
|
+
pkgPathAliases: this.pkgPathAliases,
|
|
553
|
+
});
|
|
554
|
+
if (errorMsg) {
|
|
555
|
+
throw new Error(errorMsg);
|
|
556
|
+
}
|
|
557
|
+
return (exports
|
|
558
|
+
// only allow names that start with a capital letter (i.e. React Component names)
|
|
559
|
+
// will exclude helper functions and custom hooks
|
|
560
|
+
.filter((e) => e === 'default' || (0, utils_1.isFirstLetterCapital)(e))
|
|
561
|
+
.map((name) => ({
|
|
562
|
+
alias: name,
|
|
563
|
+
path,
|
|
564
|
+
})));
|
|
565
|
+
}
|
|
566
|
+
catch (e) {
|
|
567
|
+
// only want this showing with verbose since template suggestions are not critical
|
|
568
|
+
this.log.verbose(`Error getting import names for ${path}: ${e.message}`, null, this.logPrefix);
|
|
569
|
+
return [];
|
|
570
|
+
}
|
|
571
|
+
})).then((results) => {
|
|
572
|
+
// sadly `Promise.all` & `.flatMap` just don't work, so this:
|
|
573
|
+
return results.flat();
|
|
574
|
+
});
|
|
575
|
+
const suggestions = allSuggestions.filter((s) => {
|
|
576
|
+
return !usedSuggestions.find((us) => us.alias === s.alias && us.path === s.path);
|
|
577
|
+
});
|
|
578
|
+
const connectedSuggestions = usedSuggestions.map((s) => ({
|
|
579
|
+
...s,
|
|
580
|
+
connected: true,
|
|
581
|
+
}));
|
|
582
|
+
return {
|
|
583
|
+
suggestions: [...suggestions, ...connectedSuggestions],
|
|
584
|
+
};
|
|
585
|
+
};
|
|
596
586
|
}
|
|
597
587
|
exports.KnapsackReactRenderer = KnapsackReactRenderer;
|
|
598
|
-
_KnapsackReactRenderer_demoWrapperPath = new WeakMap(), _KnapsackReactRenderer_disableReactStrictMode = new WeakMap();
|
|
599
588
|
//# sourceMappingURL=renderer-react.js.map
|