-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocs-wrapper-plugin.ts
More file actions
347 lines (311 loc) · 11.9 KB
/
docs-wrapper-plugin.ts
File metadata and controls
347 lines (311 loc) · 11.9 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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
import { transformSync } from "@babel/core";
import type { PluginItem } from "@babel/core";
import * as t from "@babel/types";
import kebabCase from "lodash.kebabcase";
import path from "path";
import type { Plugin } from "vite";
interface ImportInfo {
source: string;
importedName: string;
}
interface NodeToWrap {
path: any; // Babel path object - complex type, using any for simplicity
componentName: string;
componentPath: string;
}
// Mapping from source path patterns to documentation paths
const COMPONENT_DOC_MAPPING: Record<string, string | Record<string, string>> = {
// Media components
"media/components": "product-media-gallery",
// Store components
"store/components": {
Product: "product",
ProductModifiers: "product-modifiers",
ProductVariantSelector: "product-variant-selector",
SelectedVariant: "selected-variant",
Collection: "collection",
},
// Ecom components
"ecom/components": {
CurrentCart: "current-cart",
},
// Member components
"members/components": {
CurrentMemberProfile: "current-member-profile",
ProfileUpdate: "profile-update",
PhotoUpload: "photo-upload",
},
// Booking components
"bookings/components": {
BookingServices: "bookings-services",
BookingAvailability: "booking-availability",
BookingSelection: "booking-selection",
},
// SEO components
"seo/components": {
SEO: "seo-tags",
},
};
function getDocumentationPath(
sourcePath: string,
componentName: string
): string {
const normalizedPath = sourcePath.replace(/\\/g, "/").replace(/\.\.\//g, "");
// Check each mapping pattern
for (const [pattern, mapping] of Object.entries(COMPONENT_DOC_MAPPING)) {
if (normalizedPath.includes(pattern)) {
if (typeof mapping === "string") {
// Direct mapping for single component files
return `/docs/components/${mapping}`;
} else if (typeof mapping === "object") {
// Component-specific mapping
const baseComponentName = componentName.split(".")[0];
const docPath = mapping[baseComponentName];
if (docPath) {
return `/docs/components/${docPath}`;
}
}
}
}
// Fallback to original logic
const fileNameWithExt = path.basename(sourcePath);
const fileName = path.parse(fileNameWithExt).name;
return `/docs/components/${kebabCase(fileName)}`;
}
export function headlessDocsWrapper(): Plugin {
return {
name: "headless-docs-wrapper",
enforce: "pre",
transform(code: string, id: string) {
if (
!id.endsWith(".tsx") ||
id.includes("node_modules") ||
id.includes("src/headless/")
) {
return null;
}
const headlessImports = new Map<string, ImportInfo>();
// First pass to find headless imports to avoid running babel if not needed
const headlessPath = path.resolve(process.cwd(), "src/headless");
const usedJSXComponents = new Set<string>();
transformSync(code, {
ast: true,
code: false,
filename: id,
plugins: [
["@babel/plugin-syntax-typescript", { isTSX: true }] as PluginItem,
function precheckPlugin() {
return {
visitor: {
ImportDeclaration(p: any) {
const source = p.node.source.value;
let isHeadlessImport = false;
if (source.startsWith(".")) {
const resolvedPath = path.resolve(path.dirname(id), source);
if (resolvedPath.startsWith(headlessPath)) {
isHeadlessImport = true;
}
}
if (isHeadlessImport) {
p.node.specifiers.forEach((spec: any) => {
if (spec.type === "ImportSpecifier") {
headlessImports.set(spec.local.name, {
source,
importedName: spec.imported.name,
});
}
});
}
},
JSXElement(p: any) {
const openingElement = p.node.openingElement;
if (openingElement.name.type === "JSXIdentifier") {
usedJSXComponents.add(openingElement.name.name);
} else if (
openingElement.name.type === "JSXMemberExpression"
) {
if (openingElement.name.object.type === "JSXIdentifier") {
usedJSXComponents.add(openingElement.name.object.name);
}
}
},
},
};
},
],
});
// Filter headless imports to only those actually used as JSX components
const filteredHeadlessImports = new Map<string, ImportInfo>();
for (const [localName, importInfo] of headlessImports) {
if (usedJSXComponents.has(localName)) {
filteredHeadlessImports.set(localName, importInfo);
}
}
headlessImports.clear();
for (const [key, value] of filteredHeadlessImports) {
headlessImports.set(key, value);
}
if (headlessImports.size === 0) {
return null;
}
const result = transformSync(code, {
filename: id,
sourceMaps: true,
plugins: [
["@babel/plugin-syntax-typescript", { isTSX: true }] as PluginItem,
["@babel/plugin-syntax-jsx"] as PluginItem,
function autoDocsWrapperPlugin({ types }: { types: typeof t }) {
const nodesToWrap: NodeToWrap[] = [];
return {
visitor: {
JSXElement(p: any) {
const openingElement = p.node.openingElement;
let componentId = "";
let importInfo: ImportInfo | null = null;
let isHeadlessComponent = false;
if (types.isJSXIdentifier(openingElement.name)) {
// Direct usage: <ComponentName>
componentId = openingElement.name.name;
if (headlessImports.has(componentId)) {
importInfo = headlessImports.get(componentId)!;
isHeadlessComponent = true;
}
} else if (types.isJSXMemberExpression(openingElement.name)) {
// Namespaced usage: <Namespace.ComponentName>
const { object, property } = openingElement.name;
if (
types.isJSXIdentifier(object) &&
types.isJSXIdentifier(property)
) {
const namespaceName = object.name;
componentId = `${namespaceName}.${property.name}`;
if (headlessImports.has(namespaceName)) {
importInfo = headlessImports.get(namespaceName)!;
isHeadlessComponent = true;
}
}
}
// Only process headless components
if (!isHeadlessComponent || !importInfo) {
return;
}
// Filter out whitespace-only text nodes
const meaningfulChildren = p.node.children.filter(
(child: any) => {
if (types.isJSXText(child)) {
return child.value.trim() !== "";
}
return true;
}
);
if (meaningfulChildren.length !== 1) {
return;
}
const child = meaningfulChildren[0];
if (
!types.isJSXExpressionContainer(child) ||
!types.isArrowFunctionExpression(child.expression)
) {
return;
}
const componentProperty = componentId.split(".")[1] || "";
const componentName = componentId;
const componentPath =
getDocumentationPath(importInfo.source, componentName) +
(componentProperty
? `#${componentProperty.toLowerCase()}`
: "");
// Find the index of the meaningful child in the original children array
const childIndex = p.node.children.indexOf(child);
nodesToWrap.push({
path: p.get(`children.${childIndex}.expression`),
componentName,
componentPath,
});
},
Program: {
exit(programPath: any) {
if (nodesToWrap.length === 0) {
return;
}
// Add import if needed
let alreadyHasWrapperImport = false;
programPath.traverse({
ImportDeclaration(p: any) {
const source = p.node.source.value;
const from = path.dirname(id);
const docsModePath = path.resolve(
process.cwd(),
"src/components/DocsMode.tsx"
);
const resolvedSource = path.resolve(from, source);
if (
resolvedSource.startsWith(
docsModePath.replace(".tsx", "")
)
) {
p.node.specifiers.forEach((spec: any) => {
if (
types.isImportSpecifier(spec) &&
types.isIdentifier(spec.imported, {
name: "withDocsWrapper",
})
) {
alreadyHasWrapperImport = true;
}
});
}
},
});
if (!alreadyHasWrapperImport) {
const from = path.dirname(id);
const to = path.resolve(
process.cwd(),
"src/components/DocsMode"
);
let relativePath = path.relative(from, to);
if (!relativePath.startsWith(".")) {
relativePath = "./" + relativePath;
}
const importDecl = types.importDeclaration(
[
types.importSpecifier(
types.identifier("withDocsWrapper"),
types.identifier("withDocsWrapper")
),
],
types.stringLiteral(relativePath)
);
programPath.node.body.unshift(importDecl);
}
// Apply transformations
nodesToWrap.forEach((nodeInfo) => {
const { path, componentName, componentPath } = nodeInfo;
const renderPropFn = path.node;
const wrapperCall = types.callExpression(
types.identifier("withDocsWrapper"),
[
renderPropFn,
types.stringLiteral(componentName),
types.stringLiteral(componentPath),
]
);
path.replaceWith(wrapperCall);
});
},
},
},
};
},
],
});
if (result && result.code) {
return {
code: result.code,
map: result.map,
};
}
return null;
},
};
}