-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathhelpers.ts
More file actions
309 lines (294 loc) · 9.01 KB
/
helpers.ts
File metadata and controls
309 lines (294 loc) · 9.01 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
import { all as KnownCssProperties } from 'known-css-properties';
import { MdxJsxAttribute } from 'mdast-util-mdx';
import type { ArrayExpression, Directive, MemberExpression, ObjectExpression } from 'estree-jsx';
// matches options in strings: "--width=200px --height=20%" -> {width: '20px', height='20%'}
const OPTION_REGEX = /(^|\s+)--(?<key>[a-zA-Z\-]+)\s*=\s*(?<value>[\d\S-]+)/;
const BOOLEAN_REGEX = /(^|\s+)--(?<key>[a-zA-Z\-]+)\s*/;
// ?: makes an uncaptured group
const EXTRACT_OPTINS_REGEX = /(^|\s+)--((?:[a-zA-Z\-]+)\s*=\s*(?:[\d\S-]+)|(?:[a-zA-Z\-]+)\s*)/g;
const ALIASES = {
width: 'minWidth',
min: 'minWidth',
align: 'alignItems',
grow: 'flexGrow',
cols: 'columns',
basis: 'flexBasis',
justify: 'justifyContent',
class: 'className',
classes: 'className'
};
export const captialize = (s: string) => {
if (!s) {
return s;
}
return s.charAt(0).toUpperCase() + s.slice(1);
};
type ExpressionType =
| { type: string; value: any; raw: string }
| { type: 'Identifier'; name: string }
| Directive['expression']
| MemberExpression
| ObjectExpression
| ArrayExpression;
export const toMdxJsxExpressionAttribute = (
key: string,
value: number | boolean | string | Object,
expression: ExpressionType
): MdxJsxAttribute => {
return {
type: 'mdxJsxAttribute',
name: key,
value: {
type: 'mdxJsxAttributeValueExpression',
value: typeof value === 'object' ? JSON.stringify(value) : `${value}`,
data: {
estree: {
type: 'Program',
body: [
{
type: 'ExpressionStatement',
expression: expression as unknown as any
}
],
sourceType: 'module',
comments: []
}
}
}
};
};
export const toJsxAttribute = (key: string, value: string | number | boolean | Object): MdxJsxAttribute => {
if (Number.isFinite(value)) {
return toMdxJsxExpressionAttribute(key, `${value}`, {
type: 'Literal',
value: value,
raw: `${value}`
});
}
if (typeof value === 'boolean') {
if (value) {
return {
type: 'mdxJsxAttribute',
name: key,
value: null
};
}
return toMdxJsxExpressionAttribute(key, `${value}`, {
type: 'Literal',
value: value,
raw: `${value}`
});
}
if (typeof value === 'object') {
if (Array.isArray(value)) {
const arrExpr = {
type: 'ArrayExpression',
elements: Object.entries(value).map(
([k, v]) => (toJsxAttribute('val', v) as any).value!.data.estree.body[0].expression
)
} as ArrayExpression;
return toMdxJsxExpressionAttribute(key, value, arrExpr);
}
const expression = {
type: 'ObjectExpression',
properties: Object.entries(value).map(([k, v]) => ({
type: 'Property',
method: false,
shorthand: false,
computed: false,
key: {
type: 'Identifier',
name: k
},
value: {
type: 'Literal',
value: v,
raw: JSON.stringify(v)
},
kind: 'init'
}))
} as ObjectExpression;
return toMdxJsxExpressionAttribute(key, value, expression);
}
return {
type: 'mdxJsxAttribute',
name: key,
value: value === '' ? null : `${value}`
};
};
/**
*
* @param dashed dashed string, e.g. hello-bello
* @returns camelCased string, e.g. helloBello
*/
export const camelCased = (dashed: string): string => {
return dashed.replace(/-([a-zA-Z])/g, (g) => g[1].toUpperCase()).replace(/-/g, '');
};
/**
* @param camelCased dashed string, e.g. hellBello
* @returns dashed string, e.g. hello-bello
*/
export const dashedString = (camelCased: string): string => {
const match = camelCased.match(/[A-Z]/g);
if (!match) {
return camelCased;
}
return match.reduce((acc, c) => {
return acc.replace(c, `-${c.toLowerCase()}`);
}, camelCased);
};
/**
* style, className and jsxAttributes have distinct keys
* attributes contains everything.
*/
export interface Options {
style: { [key: string]: string | boolean };
className: string;
jsxAttributes: { [key: string]: string | number | boolean };
attributes: { [key: string]: string | number | boolean };
}
/**
*
* @param attributes
* @param keyAliases
*/
export const transformAttributes = (
attributes: { [key: string]: string | undefined | null } | undefined | null,
keyAliases: { [key: string]: string } = ALIASES
) => {
const options: Options = {
style: {},
className: '',
attributes: {},
jsxAttributes: {}
};
if (!attributes) {
return options;
}
for (const [key, value] of Object.entries(attributes)) {
const k = keyAliases[key] ?? key;
const val =
value === 'true'
? true
: value === 'false'
? false
: value === ''
? true
: value === null || value === undefined
? ''
: !Number.isNaN(Number(value))
? Number(value)
: value;
if (KnownCssProperties.includes(dashedString(k))) {
options.style[camelCased(k)] = typeof val === 'number' ? `${val}` : val;
} else if (k === 'className' && value) {
options.className = value;
} else {
options.jsxAttributes[k] = val;
}
options.attributes[k] = val;
}
return options;
};
/**
* transforms 'path/to/file' to `require('path/to/file').defaut` to mdast
* @param src path to require
*/
export const requireDefaultMdastNode = (key: string, src: string) => {
return toMdxJsxExpressionAttribute(key, `require('${src}').default`, {
type: 'MemberExpression',
object: {
type: 'CallExpression',
callee: {
type: 'Identifier',
name: 'require'
},
arguments: [
{
type: 'Literal',
value: src,
raw: `'${src}'`
}
],
optional: false
},
property: {
type: 'Identifier',
name: 'default'
},
computed: false,
optional: false
});
};
export const cleanedText = (rawText: string, trim: boolean = true) => {
const cleaned = rawText
.replace(new RegExp(OPTION_REGEX, 'g'), '')
.replace(new RegExp(BOOLEAN_REGEX, 'g'), '');
return trim ? cleaned.trim() : cleaned;
};
/**
* returns only the options from a string
* @example
* cleanedOptions('Hello --width=200px --height=20% Options --inline') -> '--width=200px --height=20% --inline'
*/
export const extractOptions = (rawText: string) => {
return Array.from(rawText.matchAll(EXTRACT_OPTINS_REGEX), (m) => m[0].trim()).join(' ');
};
export interface ParsedOptions {
className?: string;
[key: string]: string | boolean | number | undefined;
}
export const parseOptions = (
rawText: string,
transform2CamelCase = false,
keyAliases: { [key: string]: string } = {}
) => {
const options: ParsedOptions = {};
let raw = rawText;
const optKey = (key: string) => {
let k = key;
if (k in keyAliases) {
k = keyAliases[k];
}
if (transform2CamelCase) {
k = camelCased(k);
}
return k;
};
while (OPTION_REGEX.test(raw)) {
const match = raw.match(OPTION_REGEX);
raw = raw.replace(OPTION_REGEX, '');
const { key, value } = match?.groups || {};
if (key) {
(options as any)[optKey(key)] = value;
}
}
while (BOOLEAN_REGEX.test(raw)) {
const match = raw.match(BOOLEAN_REGEX);
raw = raw.replace(BOOLEAN_REGEX, '');
const { key } = match?.groups || {};
if (key) {
(options as any)[optKey(key)] = true;
}
}
return options;
};
export const serializeOptions = (options: ParsedOptions) => {
const opts: string[] = [];
Object.entries(options).forEach(([key, value]) => {
if (typeof value === 'boolean') {
if (value) {
opts.push(`--${key}`);
}
} else if (value === 'true' || value === 'false') {
if (value === 'true') {
opts.push(`--${key}`);
}
} else {
if (value !== undefined) {
opts.push(`--${key}=${value}`);
}
}
});
return opts.join(' ');
};