-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
FileContentGenerator.ts
295 lines (265 loc) · 8.82 KB
/
FileContentGenerator.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
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
import _ from 'lodash';
import {TAllClassnames} from '../types/classes';
import {TailwindConfigParser} from './TailwindConfigParser';
export class FileContentGenerator {
private _configParser: TailwindConfigParser;
private readonly _generatedClassNames: TAllClassnames;
/**
* Initializes a new instance of the `FileContentGenerator` class.
* @param generatedClassnames The generated classnames to put in the template.
*/
constructor(generatedClassnames: TAllClassnames, configParser: TailwindConfigParser) {
this._configParser = configParser;
this._generatedClassNames = generatedClassnames;
}
public generateFileContent = (): string => {
return (
this.fileHeaderTemplate() +
'\n\n' +
this.importStatementsTemplate() +
'\n\n' +
this.regularClassnamesTypesTemplate() +
'\n\n' +
this.variantsTypeTemplate() +
'\n\n' +
this.utilityFunctionsTemplate() +
'\n\n' +
this.mainExportStatementsTemplate()
);
};
private fileHeaderTemplate = (): string => {
return (
'/* eslint-disable */\n' +
'/* tslint:disable */\n' +
'\n' +
'//////////////////////////////////////////////////////////////////////////////\n' +
'/// Autogenerated by tailwindcss-classnames CLI. https://git.io/JtsPU\n' +
'/// DO NOT EDIT THIS FILE DIRECTLY!\n' +
'//////////////////////////////////////////////////////////////////////////////\n'
);
};
private importStatementsTemplate = (): string => {
return "import classnamesLib from 'clsx';" + '\n' + `T_CUSTOM_CLASSES_IMPORT_STATEMENT`;
};
private variantsTypeTemplate = (): string => {
const variants = this._configParser.getVariants();
return this.generateTypesTemplate(
'PseudoClassVariants',
variants.map(variant => variant + this._configParser.getSeparator()), // 'hover:', 'focus:'
undefined,
true,
);
};
private regularClassnamesTypesTemplate = (): string => {
return Object.keys(this._generatedClassNames)
.map(classGroupKey => {
return this.generateTypesGroupTemplate(
this._generatedClassNames[classGroupKey as keyof TAllClassnames] as TAllClassnames,
classGroupKey,
);
})
.join('\n');
};
private utilityFunctionsTemplate = (): string => {
let template =
'//////////// Utility Function generic type\n\n' +
'type TUtilityFunction<T extends string> = (\n' +
' ...args: Array<\n' +
' | T\n' +
' | `!${T}`\n' +
' | `${TPseudoClassVariants}${T}`\n' +
' | `${TPseudoClassVariants}!${T}`\n' +
' | null\n' +
' | undefined\n' +
' | {[key in T | `${TPseudoClassVariants}${T}` | `!${T}` | `${TPseudoClassVariants}!${T}` | TTailwindString]?: boolean}\n' +
' | TTailwindString\n' +
' >\n' +
') => TTailwindString;';
/**
* Specific subcategory utility functions
*/
for (const [categoryKey, value] of Object.entries(this._generatedClassNames)) {
const subCategoriesTemplate = Object.keys(value) // sub-ctegories keys
.map(SubCategory => {
const fnName = _.camelCase(SubCategory);
const fnType = `TUtilityFunction<T${_.upperFirst(SubCategory)}>`;
return `export const ${fnName}: ${fnType} = classnamesLib as any`;
})
.join('\n');
template =
template +
'\n' +
`\n//////////// ${categoryKey} Utility functions\n` +
'\n' +
subCategoriesTemplate;
}
/**
* general category utility functions
*/
const generalCategoriesTemplate = Object.keys(this._generatedClassNames)
.map(categorykey => {
const comment = '\n' + `\n//////////// ${categorykey} Utility functions\n` + '\n';
const fnName = _.camelCase(categorykey);
const fnType = `TUtilityFunction<T${_.upperFirst(categorykey)}>`;
return comment + `export const ${fnName}: ${fnType} = classnamesLib as any`;
})
.join('\n');
template = template + generalCategoriesTemplate;
return template;
};
private mainExportStatementsTemplate = (): string => {
const specificUtilityFunctionsObjectTemplate = Object.keys(this._generatedClassNames)
.map(cn => {
const subCategoryObj = this._generatedClassNames[cn as keyof TAllClassnames];
if (subCategoryObj !== undefined) {
return Object.keys(subCategoryObj)
.map(sc => ' ' + sc)
.join(',\n');
}
})
.join(',\n');
const generalUtilityFunctionsObjectTemplate = Object.keys(this._generatedClassNames)
.map(cn => ' ' + _.camelCase(cn))
.join(',\n');
return (
`export const TW = {\n${specificUtilityFunctionsObjectTemplate}\n}\n` +
'\n' +
`export const CN = {\n${generalUtilityFunctionsObjectTemplate}\n}\n` +
'\n' +
'export const mainCategoriesUtilityFunctions = CN;\n' +
'\n' +
'export const subCategoriesUtilityFunctions = TW;\n' +
'\n' +
'export type TTailwindString = "TAILWIND_STRING"\n' +
'\n' +
'export type TArg =\n' +
'| null\n' +
'| undefined\n' +
this.getDarkModeClassnameType() +
'| TTailwindString\nIMPORTED_T_CUSTOM_CLASSES_ARG' +
'\n' +
'export type TTailwind = (...args: TArg[]) => TTailwindString\n' +
'\n' +
'export const classnames: TTailwind = classnamesLib as any\n' +
'\n' +
'export default classnames'
);
};
/**
* Get the dark mode config custom classname type
* @returns the name of the classname for dark mode
*/
private getDarkModeClassnameType = (): string => {
const darkModeConfig = this._configParser.getDarkMode();
if (_.isArray(darkModeConfig) && darkModeConfig[0] === 'class') {
return `| '${darkModeConfig[1]}'\n`;
} else if (_.isString(darkModeConfig) && darkModeConfig === 'class') {
return `| 'dark'\n`;
} else {
return '';
}
};
/**
* Generates types group template for a utility classes group object.
*
*
* ### example:
*
* A utility group object as:
*
* ```js
* const FlexBox = {
* alignSelf: ['self-auto', 'self-start', 'self-center'],
* flexWrap: ['flex-nowrap', 'flex-wrap'],
* }
*```
*
* will produce a template which looks like this:
*
* ```ts
* export type TFlexWrap =
* | 'flex-nowrap'
* | 'flex-wrap';
*
* export type TAlignSelf =
* | 'self-auto'
* | 'self-start'
* | 'self-center';
*
* export type TFlexBox = TFlexWrap | TAlignSelf;
* ```
*/
private generateTypesGroupTemplate = (group: TAllClassnames, groupName: string): string => {
const members = Object.keys(group);
const generateMembersStatements = (): string[] => {
return members.map(member => {
return this.generateTypesTemplate(
member,
group[member as keyof TAllClassnames] as string[],
this._configParser.getPrefix(),
);
});
};
const generateGroupStatement = (): string => {
const getMembersStatementsReferences = (): string =>
members.map(member => 'T' + _.upperFirst(member)).join('\n | ');
return (
`export type T${_.upperFirst(groupName)} =` +
'\n | ' +
getMembersStatementsReferences() +
'\n'
);
};
return generateMembersStatements().join('\n\n') + '\n\n' + generateGroupStatement();
};
/**
* Generates TS types template from a list of strings.
*
* #### Example:
*
* Given typeName: 'baz' and items:
* ```js
* ['foo', 'bar']
* ```
*
* generates:
*
* ```
* export type TBaz
* | foo
* | bar;
* ```
* or with quoutes:
* ```
* export type TBaz
* | 'foo'
* | 'bar';
* ```
* @param typeName The name of the type (without T prefix).
* @param items The list of the strings of items to add to the type name.
* @param prefix The prefix to add to the beginning of each item of the string array.
* @param surroundWithQuotes Whether to quote the types or not (make it a string or an actual type)
*/
private generateTypesTemplate = (
typeName: string,
items: string[],
prefix?: string,
surroundWithQuotes: boolean = true,
): string => {
return (
`export type T${_.upperFirst(typeName)} =` +
'\n | ' +
items
.flatMap(item => {
const classnamesThatShouldKeepTheDefaultSuffix = ['cursor'];
return classnamesThatShouldKeepTheDefaultSuffix.map(x => {
const shouldKeepDefaultSuffix: boolean = item.includes(x);
const name = shouldKeepDefaultSuffix ? item : item.replace('-DEFAULT', '');
const nameWithOrWithoutPrefix = `${prefix ? prefix : ''}${name}`;
return surroundWithQuotes ? `'${nameWithOrWithoutPrefix}'` : nameWithOrWithoutPrefix;
});
})
.join('\n | ')
);
};
}