@recursica/mantine-adapter 0.9.2 → 0.9.3

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.
@@ -0,0 +1,787 @@
1
+ /**
2
+ * Type guard function to check if a token is a FontFamilyToken
3
+ *
4
+ * @param token - The token to check
5
+ * @returns True if the token has fontFamily and variableName properties, indicating it's a FontFamilyToken
6
+ */
7
+ function isFontFamilyToken(token) {
8
+ return "fontFamily" in token && "variableName" in token;
9
+ }
10
+ /**
11
+ * Type guard function to check if a token is an EffectToken
12
+ *
13
+ * @param token - The token to check
14
+ * @returns True if the token has effects and variableName properties, indicating it's an EffectToken
15
+ */
16
+ function isEffectToken(token) {
17
+ return "effects" in token && "variableName" in token;
18
+ }
19
+ /**
20
+ * Type guard function to check if a token is a basic Token (color or float)
21
+ *
22
+ * @param token - The token to check
23
+ * @returns True if the token has mode, type, name, and value properties, indicating it's a basic Token
24
+ */
25
+ function isColorOrFloatToken(token) {
26
+ return ("mode" in token && "type" in token && "name" in token && "value" in token);
27
+ }
28
+
29
+ function autoGeneratedFile() {
30
+ return `/* prettier-ignore */
31
+ /* eslint-disable */
32
+ /* tslint:disable */
33
+ /*
34
+ Auto-generated by Recursica.
35
+ Do NOT edit these files directly\n
36
+ For more information about Recursica, go to https://recursica.com
37
+ */
38
+ `;
39
+ }
40
+
41
+ function capitalize(str) {
42
+ return str.replace(/-/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
43
+ }
44
+
45
+ class ProcessTokens {
46
+ constructor(overrides) {
47
+ this.tokens = {};
48
+ this.themes = {};
49
+ this.breakpoints = {};
50
+ this.colors = [];
51
+ this.spacers = [];
52
+ this.borderRadius = [];
53
+ this.uiKit = {};
54
+ this.processValue = (target, token) => {
55
+ if (typeof token.value === "string") {
56
+ target[token.name] = token.value;
57
+ return true;
58
+ }
59
+ if (typeof token.value === "number") {
60
+ target[token.name] = `${token.value}px`;
61
+ return true;
62
+ }
63
+ if (typeof token.value === "object") {
64
+ target[token.name] = token.value;
65
+ return true;
66
+ }
67
+ return false;
68
+ };
69
+ this.overrides = overrides;
70
+ }
71
+ processTokenValue(token, modeName, jsonThemeName) {
72
+ if (token.collection === "Breakpoints") {
73
+ this.processValue(this.breakpoints, token);
74
+ // Add breakpoints to uiKit with 'breakpoints/' prefix
75
+ const uiKitTarget = {};
76
+ this.processValue(uiKitTarget, token);
77
+ Object.entries(uiKitTarget).forEach(([key, value]) => {
78
+ // Ensure we only store string values
79
+ if (typeof value === "string") {
80
+ this.uiKit[`breakpoint/${key}`] = value;
81
+ }
82
+ else if (typeof value === "number") {
83
+ this.uiKit[`breakpoint/${key}`] = `${value.toString()}px`;
84
+ }
85
+ });
86
+ }
87
+ else if (token.collection === "UI Kit") {
88
+ this.processValue(this.uiKit, token);
89
+ }
90
+ else if (token.collection === "Tokens") {
91
+ this.processValue(this.tokens, token);
92
+ }
93
+ else {
94
+ if (!jsonThemeName)
95
+ return;
96
+ if (!this.themes[jsonThemeName])
97
+ this.themes[jsonThemeName] = {};
98
+ if (!this.themes[jsonThemeName][modeName])
99
+ this.themes[jsonThemeName][modeName] = {};
100
+ this.processValue(this.themes[jsonThemeName][modeName], token);
101
+ }
102
+ }
103
+ processTokens(variables, jsonThemeName) {
104
+ // Process tokens collection
105
+ for (const token of Object.values(variables)) {
106
+ if (isFontFamilyToken(token)) {
107
+ if (!jsonThemeName)
108
+ continue;
109
+ if (!this.tokens[jsonThemeName])
110
+ this.tokens[jsonThemeName] = {};
111
+ if (typeof this.tokens[jsonThemeName] !== "object")
112
+ this.tokens[jsonThemeName] = {};
113
+ this.tokens[jsonThemeName][`typography/${token.variableName}`] =
114
+ this.overrides?.fontFamily?.[token.fontFamily] ?? token.fontFamily;
115
+ this.tokens[jsonThemeName][`typography/${token.variableName}-size`] =
116
+ `${token.fontSize.toString()}px`;
117
+ // check if overrides.fontWeight is defined
118
+ if (this.overrides?.fontWeight) {
119
+ const weight = this.overrides.fontWeight.find((weight) => weight.alias === token.fontWeight.alias &&
120
+ weight.fontFamily === token.fontFamily);
121
+ // check if there's a weight that matches the alias and fontFamily
122
+ // if there is, use the value from the overrides
123
+ // if there isn't, use the value from the token
124
+ if (weight) {
125
+ this.tokens[jsonThemeName][`typography/${token.variableName}-weight`] = weight.value.toString();
126
+ }
127
+ else {
128
+ this.tokens[jsonThemeName][`typography/${token.variableName}-weight`] = token.fontWeight.value.toString();
129
+ }
130
+ }
131
+ else {
132
+ this.tokens[jsonThemeName][`typography/${token.variableName}-weight`] = token.fontWeight.value.toString();
133
+ }
134
+ if (token.lineHeight.unit === "PERCENT") {
135
+ this.tokens[jsonThemeName][`typography/${token.variableName}-line-height`] = `${token.lineHeight.value.toString()}%`;
136
+ }
137
+ else {
138
+ this.tokens[jsonThemeName][`typography/${token.variableName}-line-height`] = "1.2";
139
+ }
140
+ this.tokens[jsonThemeName][`typography/${token.variableName}-letter-spacing`] =
141
+ token.letterSpacing.unit === "PIXELS"
142
+ ? `${token.letterSpacing.value.toString()}px`
143
+ : `${token.letterSpacing.value.toString()}%`;
144
+ this.tokens[jsonThemeName][`typography/${token.variableName}-text-case`] = token.textCase;
145
+ this.tokens[jsonThemeName][`typography/${token.variableName}-text-decoration`] = token.textDecoration;
146
+ continue;
147
+ }
148
+ if (isEffectToken(token)) {
149
+ const effectValue = [];
150
+ token.effects.forEach((effect) => {
151
+ const { color: { r, g, b, a }, offset: { x, y }, radius, spread, } = effect;
152
+ effectValue.push(`${x.toString()}px ${y.toString()}px ${radius.toString()}px ${spread.toString()}px rgba(${r.toString()}, ${g.toString()}, ${b.toString()}, ${a.toString()})`);
153
+ });
154
+ this.tokens[`effect/${token.variableName}`] = effectValue.join(", ");
155
+ continue;
156
+ }
157
+ if (isColorOrFloatToken(token)) {
158
+ const modeName = capitalize(token.mode)
159
+ .replace(/[()/]/g, "-")
160
+ .replace(/\s/g, "")
161
+ .replace(/-$/, "");
162
+ if (modeName !== "mode1")
163
+ this.themes[modeName] = {};
164
+ if (token.type === "color" && !this.colors.includes(token.name)) {
165
+ this.colors.push(token.name);
166
+ }
167
+ if (token.name.startsWith("size/spacer/") &&
168
+ !this.spacers.includes(token.name)) {
169
+ this.spacers.push(token.name);
170
+ }
171
+ if (token.name.startsWith("size/border-radius/") &&
172
+ !this.borderRadius.includes(token.name)) {
173
+ this.borderRadius.push(token.name);
174
+ }
175
+ this.processTokenValue(token, modeName, jsonThemeName);
176
+ }
177
+ else {
178
+ console.warn(`${JSON.stringify(token, null, 2)} could not be processed`);
179
+ }
180
+ }
181
+ }
182
+ }
183
+
184
+ function parseValue(value, recursicaTokens) {
185
+ if (typeof value === "object") {
186
+ if (value.collection === "Tokens") {
187
+ return `${recursicaTokens}["${value.name}"]`;
188
+ }
189
+ if (value.collection === "Themes") {
190
+ return `themeVars["${value.name}"]`;
191
+ }
192
+ }
193
+ else if (!isNaN(Number(value))) {
194
+ return `"${value}"`;
195
+ }
196
+ return `"${value.toString()}"`;
197
+ }
198
+ function generateTypeDefinitions(themeDef) {
199
+ // Extract all unique theme modes from themeDef
200
+ const allThemeModes = new Set();
201
+ Object.values(themeDef).forEach((themeVariants) => {
202
+ Object.keys(themeVariants).forEach((mode) => {
203
+ allThemeModes.add(mode);
204
+ });
205
+ });
206
+ // Generate the ThemeVariant interface dynamically
207
+ const themeVariantProperties = Array.from(allThemeModes)
208
+ .sort() // Sort for consistent output
209
+ .map((mode) => ` ${mode}: string;`)
210
+ .join("\n");
211
+ return `${autoGeneratedFile()}
212
+ import { THEMES } from "./RecursicaThemes";
213
+
214
+ export interface ThemeVariant {
215
+ ${themeVariantProperties}
216
+ }
217
+
218
+ // TypeScript will automatically infer this as a union of literal types
219
+ export type ThemeType = typeof THEMES[keyof typeof THEMES];
220
+
221
+ export type ThemeDictionary = Record<ThemeType, ThemeVariant>;
222
+ `;
223
+ }
224
+ function generateVanillaExtractThemes(tokens, themes, recursicaTokensFilename, { outputPath, project }) {
225
+ const themesContent = [];
226
+ // Contract tokens
227
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
228
+ const themeContractFilename = `Recursica${projectName}ContractTheme.css`;
229
+ const contractThemeOutputPath = outputPath + "/" + `${themeContractFilename}.ts`;
230
+ const contractTokens = {};
231
+ const themeDef = {};
232
+ for (const [rawThemeName, currentTheme] of Object.entries(themes)) {
233
+ for (const [key, theme] of Object.entries(currentTheme)) {
234
+ const currentThemeName = capitalize(rawThemeName);
235
+ const recursicaTokens = `Recursica${projectName}Tokens`;
236
+ const themeKey = key.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
237
+ const themeName = `${currentThemeName}${themeKey}Theme`;
238
+ if (!themeDef[currentThemeName]) {
239
+ themeDef[currentThemeName] = {};
240
+ }
241
+ themeDef[currentThemeName][themeKey] = themeName;
242
+ const generatedThemeContent = `${autoGeneratedFile()}
243
+ import { createTheme } from '@vanilla-extract/css';
244
+
245
+ import { themeVars } from './${themeContractFilename.replace(".ts", "")}'
246
+ import { ${recursicaTokens} } from './${recursicaTokensFilename.replace(".ts", "")}'
247
+
248
+ export const ${themeName} = createTheme(themeVars,{
249
+ ${Object.entries(theme)
250
+ .map(([key, value]) => {
251
+ contractTokens[key] = null;
252
+ return `'${key}': ${parseValue(value, recursicaTokens)}`;
253
+ })
254
+ .join(",\n\t")},
255
+ ${Object.entries(tokens?.[rawThemeName] ?? {})
256
+ .map(([key, value]) => {
257
+ contractTokens[key] = null;
258
+ return `'${key}': ${parseValue(value, recursicaTokens)}`;
259
+ })
260
+ .join(",\n\t")}
261
+ })`;
262
+ themesContent.push({
263
+ name: themeName,
264
+ content: generatedThemeContent,
265
+ });
266
+ }
267
+ }
268
+ let themesFileContent = autoGeneratedFile();
269
+ const vanillaExtractThemes = [];
270
+ for (const theme of themesContent) {
271
+ const themeName = `Recursica${projectName}${theme.name}`;
272
+ const autoGeneratedThemeFilename = `${themeName}.css.ts`;
273
+ const themeFilePath = outputPath + "/" + autoGeneratedThemeFilename;
274
+ vanillaExtractThemes.push({
275
+ content: theme.content,
276
+ path: themeFilePath,
277
+ filename: autoGeneratedThemeFilename,
278
+ });
279
+ // generate a theme.css.ts where we import all the themes using just 1 variables (1 export)
280
+ themesFileContent += `export { ${theme.name} } from './${autoGeneratedThemeFilename.replace(".ts", "")}';\n`;
281
+ themesFileContent += `import { ${theme.name} } from './${autoGeneratedThemeFilename.replace(".ts", "")}';\n`;
282
+ }
283
+ themesFileContent += `\nexport const Themes = {
284
+ ${Object.entries(themeDef)
285
+ .map(([key, value]) => `'${key}': {
286
+ ${Object.entries(value)
287
+ .map(([key, value]) => `'${key}': ${value}`)
288
+ .join(",\n\t\t")}`)
289
+ .join("\n\t},\n\t")}
290
+ }
291
+ }`;
292
+ // create the themes.ts file
293
+ const availableThemesContent = `${autoGeneratedFile()}
294
+ export const AvailableThemes = [${themesContent.map((theme) => `"${theme.name}"`).join(", ")}] as const;
295
+ export type AvailableThemesType = (typeof AvailableThemes)[number];
296
+ `;
297
+ const availableThemesPath = outputPath + "/types.ts";
298
+ const themeContractContent = `${autoGeneratedFile()}
299
+ import { createThemeContract } from '@vanilla-extract/css';
300
+
301
+ export const themeVars = createThemeContract(${JSON.stringify(contractTokens, null, 2)});
302
+ `;
303
+ const themesFilename = `Recursica${projectName}Themes.css.ts`;
304
+ const themesFilePath = outputPath + "/" + themesFilename;
305
+ // Generate type definitions in types.d.ts
306
+ const typeDefinitionsContent = generateTypeDefinitions(themeDef);
307
+ const typesPath = outputPath + "/types.d.ts";
308
+ return {
309
+ typeDefinitions: {
310
+ content: typeDefinitionsContent,
311
+ path: typesPath,
312
+ filename: "types.d.ts",
313
+ },
314
+ themesFileContent: {
315
+ content: themesFileContent,
316
+ path: themesFilePath,
317
+ filename: themesFilename,
318
+ },
319
+ availableThemes: {
320
+ content: availableThemesContent,
321
+ path: availableThemesPath,
322
+ filename: "types.ts",
323
+ },
324
+ vanillaExtractThemes,
325
+ themeContract: {
326
+ content: themeContractContent,
327
+ path: contractThemeOutputPath,
328
+ filename: themeContractFilename,
329
+ },
330
+ contractTokens,
331
+ };
332
+ }
333
+
334
+ function generateRecursicaTokens(baseTokens, { outputPath, project }) {
335
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
336
+ const recursicaTokensFilename = `Recursica${projectName}Tokens.ts`;
337
+ const recursicaTokensPath = outputPath + "/" + recursicaTokensFilename;
338
+ const recursicaTokensContent = `${autoGeneratedFile()}
339
+ export const Recursica${projectName}Tokens = {
340
+ ${Object.entries(baseTokens)
341
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
342
+ .filter(([_, value]) => typeof value === "string")
343
+ .map(([key, value]) => `"${key}": "${value}"`)
344
+ .join(",\n ")}
345
+ };
346
+ `;
347
+ return {
348
+ content: recursicaTokensContent,
349
+ path: recursicaTokensPath,
350
+ filename: recursicaTokensFilename,
351
+ };
352
+ }
353
+
354
+ function generateUiKit(uiKit, { recursicaTokensFilename, themeContractFilename }, { outputPath, project }) {
355
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
356
+ const uiKitFilename = `Recursica${projectName}UiKit.ts`;
357
+ const uiKitPath = outputPath + "/" + uiKitFilename;
358
+ const recursicaTokens = `Recursica${projectName}Tokens`;
359
+ const uiKitContent = `${autoGeneratedFile()}
360
+ import { themeVars } from './${themeContractFilename.replace(".ts", "")}'
361
+ import { ${recursicaTokens} } from './${recursicaTokensFilename.replace(".ts", "")}'
362
+
363
+ export const uiKit = {
364
+ ${Object.entries(uiKit)
365
+ .map(([key, value]) => `'${key}': ${parseValue(value, recursicaTokens)}`)
366
+ .join(",\n\t")}\n\t}`;
367
+ return {
368
+ content: uiKitContent,
369
+ path: uiKitPath,
370
+ filename: uiKitFilename,
371
+ };
372
+ }
373
+
374
+ function parseKey(key) {
375
+ return key.replaceAll("/", "-");
376
+ }
377
+ function generateMantineTheme({ mantineThemeOverride, tokens, breakpoints, contractTokens: { tokens: contractTokens, filename: contractFilename }, exportingProps: { outputPath, project, rootPath }, }) {
378
+ const themeTokens = {
379
+ colors: {},
380
+ radius: {},
381
+ fontSizes: {},
382
+ primaryColor: mantineThemeOverride?.["1-scale"],
383
+ white: mantineThemeOverride?.background,
384
+ };
385
+ for (const [key, value] of Object.entries(tokens)) {
386
+ if (typeof value === "object")
387
+ continue;
388
+ if (key.includes("border-radius")) {
389
+ themeTokens.radius[parseKey(key)] = value;
390
+ }
391
+ if (key.includes("font/size")) {
392
+ themeTokens.fontSizes[parseKey(key)] = `"${value}"`;
393
+ }
394
+ }
395
+ for (const [key] of Object.entries(contractTokens)) {
396
+ if (key.includes("color/") || key.includes("color-on/")) {
397
+ themeTokens.colors[parseKey(key)] = `themeVars['${key}']`;
398
+ }
399
+ if (/font\/(\w+)\/size/.test(key)) {
400
+ themeTokens.fontSizes[parseKey(key)] = `themeVars['${key}']`;
401
+ }
402
+ }
403
+ const postCssFilename = "postcss.config.cjs";
404
+ let postCssContent = `${autoGeneratedFile()}\n`;
405
+ postCssContent += `module.exports = {
406
+ plugins: {
407
+ 'postcss-preset-mantine': {},
408
+ 'postcss-simple-vars': {
409
+ variables: {`;
410
+ for (const [key, value] of Object.entries(breakpoints)) {
411
+ postCssContent += `\n\t\t\t\t'mantine-breakpoint-${key}': '${value}',`;
412
+ }
413
+ postCssContent += `
414
+ }
415
+ }
416
+ }
417
+ }`;
418
+ const postCssFileContent = {
419
+ content: postCssContent,
420
+ path: rootPath ? rootPath + "/" + postCssFilename : postCssFilename,
421
+ filename: postCssFilename,
422
+ };
423
+ const fileContent = `${autoGeneratedFile()}
424
+ import { colorsTuple, createTheme } from '@mantine/core'
425
+ import { themeVars } from './${contractFilename.replace(".ts", "")}'
426
+
427
+ export const mantineTheme = createTheme({
428
+ ${themeTokens.primaryColor ? `primaryColor: ${themeTokens.primaryColor},` : ""}
429
+ ${themeTokens.white ? `white: ${themeTokens.white},` : ""}
430
+ breakpoints: {
431
+ ${Object.entries(breakpoints)
432
+ .map(([key, value]) => `'${key}': '${value}'`)
433
+ .join(",\n\t\t")}
434
+ },
435
+ colors: {
436
+ ${Object.entries(themeTokens.colors)
437
+ .map(([key, value]) => `"${key}": colorsTuple(${value})`)
438
+ .join(",\n\t\t")}
439
+ },
440
+ radius: {
441
+ ${Object.entries(themeTokens.radius)
442
+ .map(([key, value]) => `"${key}": "${value}"`)
443
+ .join(",\n\t\t")}
444
+ },
445
+ fontSizes: {
446
+ ${Object.entries(themeTokens.fontSizes)
447
+ .map(([key, value]) => `"${key}": ${value}`)
448
+ .join(",\n\t\t")}
449
+ }
450
+ })`;
451
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
452
+ const filename = `Recursica${projectName}MantineTheme.ts`;
453
+ const mantineThemeFileContent = {
454
+ content: fileContent,
455
+ path: outputPath + "/" + filename,
456
+ filename,
457
+ };
458
+ return { mantineTheme: mantineThemeFileContent, postCss: postCssFileContent };
459
+ }
460
+
461
+ function createRecursicaObject(project, outputPath) {
462
+ const projectName = typeof project === "string" ? project : (project.name ?? "Recursica");
463
+ const tokens = `Recursica${projectName}Tokens`;
464
+ const contract = `Recursica${projectName}ContractTheme`;
465
+ const uiKit = `Recursica${projectName}UiKit`;
466
+ const recursicaObjectContent = `${autoGeneratedFile()}
467
+ import { ${tokens} } from './${tokens}';
468
+ import { themeVars } from './${contract}.css';
469
+ import { uiKit } from './${uiKit}';
470
+
471
+ export const recursica = {
472
+ ...uiKit,
473
+ ...themeVars,
474
+ ...${tokens},
475
+ }
476
+ `;
477
+ return {
478
+ content: recursicaObjectContent,
479
+ path: outputPath + "/Recursica.ts",
480
+ filename: "Recursica.ts",
481
+ };
482
+ }
483
+
484
+ function generateColorsType(colorTokens, outputPath) {
485
+ const colorsType = `${autoGeneratedFile()}
486
+ export type RecursicaColors = \n\t"${colorTokens.join('" |\n\t"')}";\n`;
487
+ return {
488
+ content: colorsType,
489
+ path: `${outputPath}/RecursicaColorsType.ts`,
490
+ filename: "RecursicaColorsType.ts",
491
+ };
492
+ }
493
+
494
+ function generateIcons(icons, srcPath, config) {
495
+ let iconsPath;
496
+ if (!config?.output) {
497
+ iconsPath = srcPath + "/components" + "/Icons";
498
+ }
499
+ else {
500
+ iconsPath = srcPath + "/" + config.output;
501
+ }
502
+ const svgPath = iconsPath + "/Svg";
503
+ const exportedIcons = [];
504
+ // Generate svg files
505
+ for (const [rawIconName, iconPath] of Object.entries(icons)) {
506
+ const [iconName, variant] = rawIconName.split("[");
507
+ let cleanIconName = iconName.replaceAll("-", "_");
508
+ // check if the iconName is in the names array, if not, skip
509
+ if (!config?.include?.names?.includes(cleanIconName)) {
510
+ continue;
511
+ }
512
+ // detect if the iconName starts with a number, if so, add an underscore to the beginning
513
+ if (cleanIconName.match(/^\d/)) {
514
+ cleanIconName = `_${cleanIconName}`;
515
+ }
516
+ const cleanVariant = variant.replace("]", "").replace("Style=", "");
517
+ const codedVariant = cleanVariant.replaceAll(" ", "_");
518
+ // check if the codedVariant is in the variants array, if not, skip
519
+ if (!config?.include?.variants?.includes(codedVariant)) {
520
+ continue;
521
+ }
522
+ const finalIconName = `${cleanIconName}_${codedVariant}`;
523
+ exportedIcons.push({
524
+ content: iconPath
525
+ .replaceAll('fill="black"', "")
526
+ .replaceAll('fill="none"', ""),
527
+ path: `${svgPath}/${finalIconName}.svg`,
528
+ filename: `${finalIconName}`,
529
+ });
530
+ }
531
+ // Generate icon exports file
532
+ const exportsPath = iconsPath + "/icon_exports.ts";
533
+ let exportsContent = `${autoGeneratedFile()}
534
+ /// <reference types="vite-plugin-svgr/client" />\n`;
535
+ for (const icon of exportedIcons) {
536
+ exportsContent += `import ${icon.filename} from './Svg/${icon.filename}.svg?react';\n`;
537
+ exportsContent += `export { ${icon.filename} };\n`;
538
+ }
539
+ // Generate icon map file
540
+ const mapPath = iconsPath + "/icon_resource_map.ts";
541
+ let mapContent = `${autoGeneratedFile()}\nimport * as IconExports from './icon_exports';\n\n`;
542
+ mapContent += "export const IconResourceMap = {";
543
+ mapContent += exportedIcons
544
+ .map((icon) => `\n\t'${icon.filename}': IconExports.${icon.filename},`)
545
+ .join("");
546
+ mapContent += "\n};\n";
547
+ return {
548
+ exportedIcons,
549
+ iconExports: {
550
+ content: exportsContent,
551
+ path: exportsPath,
552
+ filename: "icon_exports.ts",
553
+ },
554
+ iconResourceMap: {
555
+ content: mapContent,
556
+ path: mapPath,
557
+ filename: "icon_resource_map.ts",
558
+ },
559
+ };
560
+ }
561
+
562
+ function generateSpacersType(spacerTokens, outputPath) {
563
+ const spacersType = `${autoGeneratedFile()}
564
+ export type RecursicaSpacersType = \n\t"${spacerTokens.join('" |\n\t"')}";\n`;
565
+ return {
566
+ content: spacersType,
567
+ path: `${outputPath}/RecursicaSpacersType.ts`,
568
+ filename: "RecursicaSpacersType.ts",
569
+ };
570
+ }
571
+
572
+ function generateBorderRadiusType(borderRadius, outputPath) {
573
+ const borderRadiusTypeContent = `${autoGeneratedFile()}
574
+ export type RecursicaBorderRadiusType = ${borderRadius
575
+ .map((key) => `'${key}'`)
576
+ .join(" | ")};
577
+ `;
578
+ return {
579
+ content: borderRadiusTypeContent,
580
+ path: `${outputPath}/RecursicaBorderRadiusType.ts`,
581
+ filename: "RecursicaBorderRadiusType.ts",
582
+ };
583
+ }
584
+
585
+ /**
586
+ * Generates the RecursicaThemes.ts file that contains the THEMES constant
587
+ * based on the theme dictionary
588
+ */
589
+ function generateRecursicaThemes({ outputPath, themes, }) {
590
+ const themeDef = {};
591
+ // Build themeDef object similar to generateVanillaExtractThemes
592
+ for (const [rawThemeName, currentTheme] of Object.entries(themes)) {
593
+ for (const [key] of Object.entries(currentTheme)) {
594
+ const currentThemeName = capitalize(rawThemeName);
595
+ const themeKey = key.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
596
+ themeDef[currentThemeName] ?? (themeDef[currentThemeName] = {});
597
+ themeDef[currentThemeName][themeKey] = currentThemeName;
598
+ }
599
+ }
600
+ const content = `/* prettier-ignore */
601
+ /* eslint-disable */
602
+ /* tslint:disable */
603
+ /*
604
+ Auto-generated by Recursica.
605
+ Do NOT edit these files directly
606
+
607
+ For more information about Recursica, go to https://recursica.com
608
+ */
609
+
610
+ // Auto-generated THEMES constant from ThemeType
611
+ export const THEMES = {
612
+ ${Object.entries(themeDef)
613
+ .map(([key]) => ` ${key}: '${key}'`)
614
+ .join(",\n")}
615
+ } as const;
616
+ `;
617
+ return {
618
+ content,
619
+ path: outputPath + "/RecursicaThemes.ts",
620
+ filename: "RecursicaThemes.ts",
621
+ };
622
+ }
623
+
624
+ function generatePrettierignore() {
625
+ return {
626
+ filename: ".prettierignore",
627
+ path: ".prettierignore",
628
+ content: `recursica/
629
+ recursica.json
630
+ recursica-bundle.json
631
+ recursica-icons.json
632
+ icon_exports.ts
633
+ icon_resource_map.ts`,
634
+ };
635
+ }
636
+
637
+ function runAdapter({ rootPath, overrides, srcPath, project, icons, iconsConfig, processTokens, }) {
638
+ const outputPath = srcPath + "/recursica";
639
+ const recursicaTokens = generateRecursicaTokens(processTokens.tokens, {
640
+ outputPath,
641
+ project,
642
+ });
643
+ const vanillaExtractThemes = generateVanillaExtractThemes(processTokens.tokens, processTokens.themes, recursicaTokens.filename, {
644
+ outputPath,
645
+ project,
646
+ });
647
+ const mantineTheme = generateMantineTheme({
648
+ mantineThemeOverride: overrides?.mantineTheme,
649
+ tokens: processTokens.tokens,
650
+ breakpoints: processTokens.breakpoints,
651
+ contractTokens: {
652
+ tokens: vanillaExtractThemes.contractTokens,
653
+ filename: vanillaExtractThemes.themeContract.filename,
654
+ },
655
+ exportingProps: {
656
+ outputPath,
657
+ project,
658
+ rootPath,
659
+ },
660
+ });
661
+ const uiKitObject = generateUiKit(processTokens.uiKit, {
662
+ recursicaTokensFilename: recursicaTokens.filename,
663
+ themeContractFilename: vanillaExtractThemes.themeContract.filename,
664
+ }, { outputPath, project });
665
+ const recursicaObject = createRecursicaObject(project, outputPath);
666
+ const colorsType = generateColorsType(processTokens.colors, outputPath);
667
+ const spacersType = generateSpacersType(processTokens.spacers, outputPath);
668
+ const borderRadiusType = generateBorderRadiusType(processTokens.borderRadius, outputPath);
669
+ let iconsObject;
670
+ if (icons) {
671
+ iconsObject = generateIcons(icons, srcPath, iconsConfig);
672
+ }
673
+ const recursicaThemes = generateRecursicaThemes({
674
+ outputPath,
675
+ themes: processTokens.themes,
676
+ });
677
+ const prettierignore = generatePrettierignore();
678
+ const fileContents = {
679
+ recursicaTokens,
680
+ vanillaExtractThemes,
681
+ mantineTheme,
682
+ uiKitObject,
683
+ recursicaObject,
684
+ colorsType,
685
+ spacersType,
686
+ borderRadiusType,
687
+ iconsObject,
688
+ recursicaThemes,
689
+ prettierignore,
690
+ };
691
+ return fileContents;
692
+ }
693
+
694
+ /**
695
+ * Processes JSON content and creates ProcessTokens instance
696
+ * This is shared logic between CLI and WebWorker
697
+ */
698
+ function processJsonContent(jsonFileContent, { project, overrides }) {
699
+ const jsonContent = JSON.parse(jsonFileContent);
700
+ const jsonProjectId = jsonContent.projectId;
701
+ if (!jsonProjectId) {
702
+ throw new Error("project-id is required in the json file");
703
+ }
704
+ if (jsonProjectId.toLowerCase() !==
705
+ (typeof project === "string"
706
+ ? project.toLowerCase()
707
+ : project.name?.toLowerCase())) {
708
+ throw new Error("project-id does not match the project in the config file");
709
+ }
710
+ const processTokens = new ProcessTokens(overrides);
711
+ processTokens.processTokens(jsonContent.tokens);
712
+ for (const theme of Object.keys(jsonContent.themes)) {
713
+ processTokens.processTokens(jsonContent.themes[theme], theme);
714
+ }
715
+ processTokens.processTokens(jsonContent.uiKit);
716
+ return processTokens;
717
+ }
718
+ /**
719
+ * Processes icons JSON content and returns icons object
720
+ * This is shared logic between CLI and WebWorker
721
+ */
722
+ function processIcons(iconsJsonContent) {
723
+ const icons = {};
724
+ const iconsJsonParsed = JSON.parse(iconsJsonContent);
725
+ for (const [iconName, iconPath] of Object.entries(iconsJsonParsed)) {
726
+ icons[iconName] = iconPath;
727
+ }
728
+ return icons;
729
+ }
730
+ /**
731
+ * Core adapter processing logic shared between CLI and WebWorker
732
+ * This function handles the main processing workflow
733
+ */
734
+ function processAdapter({ rootPath, bundledJsonContent, project, overrides, srcPath, iconsJsonContent, iconsConfig, }) {
735
+ let icons = {};
736
+ // Process icons if provided
737
+ if (iconsJsonContent) {
738
+ icons = processIcons(iconsJsonContent);
739
+ }
740
+ if (!bundledJsonContent) {
741
+ throw new Error("bundledJson content not found");
742
+ }
743
+ // Process the main JSON content
744
+ const processTokens = processJsonContent(bundledJsonContent, {
745
+ project,
746
+ overrides,
747
+ });
748
+ // Run the adapter
749
+ const files = runAdapter({
750
+ rootPath,
751
+ overrides,
752
+ srcPath,
753
+ icons,
754
+ processTokens,
755
+ project,
756
+ iconsConfig,
757
+ });
758
+ return files;
759
+ }
760
+
761
+ // 1. Listen for a message from the main application thread
762
+ // You can use self.addEventListener or the shorter self.onmessage
763
+ self.onmessage = (event) => {
764
+ // Run the script
765
+ const params = event.data;
766
+ try {
767
+ const { bundledJson, srcPath, project, overrides, iconsConfig, rootPath } = params;
768
+ if (!bundledJson)
769
+ throw new Error("bundledJson not found");
770
+ // Use shared processing logic
771
+ const files = processAdapter({
772
+ bundledJsonContent: params.bundledJson,
773
+ project,
774
+ overrides,
775
+ srcPath,
776
+ rootPath,
777
+ iconsJsonContent: params.iconsJson,
778
+ iconsConfig,
779
+ });
780
+ // 3. Send the response back to the main thread
781
+ console.log("...Worker sending response back:", files);
782
+ self.postMessage(files);
783
+ }
784
+ catch (error) {
785
+ console.error("Error generating theme:", error);
786
+ }
787
+ };