-
Notifications
You must be signed in to change notification settings - Fork 831
/
custom-props.ts
101 lines (95 loc) · 2.73 KB
/
custom-props.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
import * as t from '@babel/types';
import template from '@babel/template';
import generate from '@babel/generator';
import {formatCode, parse} from 'react-view';
export type TCustomPropFields = {
names: string[];
sharedProps: {[key: string]: string | {type: string; description: string}};
};
const parseOverridesInner = (overrides: any, acc: any) => {
overrides.forEach((override: any) => {
const overrideName = override.key.name;
const overrideProps = override.value.properties;
overrideProps.forEach((prop: any) => {
if (prop.key.name === 'style') {
acc[overrideName] = {
style: formatCode(generate(prop.value).code),
active: true,
};
}
// looking for 'props' key
if (prop.key.name === 'props') {
// looking for 'overrides' key
prop.value.properties.forEach((subprop: any) => {
if (subprop.key.name === 'overrides') {
acc[overrideName] = {
nestedValue: {},
active: true,
};
parseOverridesInner(
subprop.value.properties,
acc[overrideName].nestedValue,
);
}
});
}
});
});
};
export const parseOverrides = (code: string) => {
const ast: any = parse(`const foo = ${code};`);
const topOverrides = ast.program.body[0].declarations[0].init.properties;
const returnValue = {};
parseOverridesInner(topOverrides, returnValue);
return returnValue;
};
type TGenerateValue = {
[key: string]: {
active: boolean;
style?: string;
nestedValue?: TGenerateValue;
};
};
const generateOverrides = (value: TGenerateValue) => {
const activeValues = Object.entries(value).filter(
([, val]) => val.active && (val.style || val.nestedValue),
);
if (activeValues.length === 0) return null;
const keys: any = activeValues.map(([key, val]) => {
if (val.nestedValue) {
const nestedOverride = generateOverrides(val.nestedValue);
if (!nestedOverride) {
return null;
}
return t.objectProperty(
t.identifier(key),
t.objectExpression([
t.objectProperty(
t.identifier('props'),
t.objectExpression([
t.objectProperty(
t.identifier('overrides'),
nestedOverride as any,
),
]),
),
]),
);
}
return t.objectProperty(
t.identifier(key),
t.objectExpression([
t.objectProperty(t.identifier('style'), template.expression(
val.style as string,
)({}) as any),
]),
);
});
return t.objectExpression(keys);
};
export const customProps = {
overrides: {
generate: generateOverrides,
parse: parseOverrides,
},
};