-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.ts
170 lines (136 loc) · 4.87 KB
/
index.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
import { FileResponse, Color, Text, Node, Rectangle, Effect } from 'figma-js';
import namer from 'color-namer';
const uniq = <T>(list: T[]) => list.filter((x, i, a) => a.indexOf(x) === i);
const isSingleValue = (list: number[]) => uniq(list).length === 1;
const toPx = (val = 0) => (val !== 0 ? val + 'px' : '0');
const toEm = (letterSpacing: number) =>
letterSpacing === 0 ? 0 : (letterSpacing / 16).toFixed(2) + 'em';
export const normalizeRgba = (num: number) => Math.floor(num * 255);
export const toRgbaString = (node: Color) =>
`rgba(${normalizeRgba(node.r)},${normalizeRgba(node.g)},${normalizeRgba(
node.b,
)},${Number(node.a.toFixed(2))})`;
export const toBoxShadow = (effect: Effect) =>
effect.type === 'DROP_SHADOW'
? `${toPx(effect?.offset?.x)} ${toPx(effect?.offset?.y)} ${toPx(
effect.radius,
)} ${toColorString(effect?.color)}`
: `inset ${toPx(effect?.offset?.x)} ${toPx(effect?.offset?.y)} ${toPx(
effect.radius,
)} ${toColorString(effect?.color)}`;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const isColor = (node: any): node is Color =>
node.r && node.g && node.b && node.a;
export const isText = (node: Node): node is Text => node.type === 'TEXT';
export const isRectangle = (node: Node): node is Rectangle =>
node.type === 'RECTANGLE';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const hasEffects = (node: any) => node.effects && node.effects.length !== 0;
export const isShadow = (node: Effect) =>
(node.type === 'DROP_SHADOW' || node.type === 'INNER_SHADOW') &&
node.offset &&
node.color;
const toHex = (num: number) => normalizeRgba(num).toString(16);
export const toColorString = (node: Color = { r: 0, g: 0, b: 0, a: 0 }) =>
node.a === 1
? `#${toHex(node.r)}${toHex(node.g)}${toHex(node.b)}`
: toRgbaString(node);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isEmpty = (node: any) => !node || Object.keys(node).length === 0;
const capitalize = (str: string) => `${str[0].toUpperCase()}${str.substr(1)}`;
export const camelize = (str: string) =>
str
.replace(/[`'”“’‘,."]+/, '')
.replace(/_/, ' ')
.split(' ')
.map((word, i) => (i === 0 ? word.toLowerCase() : capitalize(word)))
.join('');
interface StyledSystemTheme {
colors?: { [index: string]: string };
lineHeights?: number[];
fontWeights?: number[];
fontSizes?: number[];
radii?: Array<number | string>;
letterSpacings?: Array<string | number>;
boxShadows?: string[];
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function walk(node: any, cb: (node: any) => any) {
if (isEmpty(node) || typeof node === 'string' || typeof node === 'number') {
return;
}
cb(node);
if (Array.isArray(node)) {
node.forEach((el) => walk(el, cb));
} else {
Object.values(node).forEach((v) => walk(v, cb));
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getColors(node: any): Record<string, string> {
const colors = new Set<string>();
walk(node, (n) => {
if (n.color && isColor(n.color)) {
colors.add(toColorString(n.color));
}
});
return [...colors].reduce(
(acc: Record<string, string>, color: string) => ({
...acc,
[camelize(namer(color).ntc[0].name)]: color,
}),
{},
);
}
function getTypography(node: Node[]): Partial<StyledSystemTheme> {
const lineHeights = new Set<number>();
const fontWeights = new Set<number>();
const fontSizes = new Set<number>();
const letterSpacings = new Set<string | number>();
walk(node, (n) => {
if (!isText(n)) return;
lineHeights.add(n.style.lineHeightPercent / 100);
fontWeights.add(n.style.fontWeight);
fontSizes.add(n.style.fontSize);
letterSpacings.add(toEm(n.style.letterSpacing));
});
return {
lineHeights: [...lineHeights].sort(),
fontWeights: [...fontWeights].sort(),
fontSizes: [...fontSizes].sort(),
letterSpacings: [...letterSpacings].sort(),
};
}
function getRadii(node: Node[]) {
const radii = new Set<number | string>();
walk(node, (n) => {
if (isRectangle(n) && !!n.rectangleCornerRadii) {
const corners = [...n.rectangleCornerRadii];
if (isSingleValue(corners)) {
radii.add(uniq(corners)[0]);
} else {
radii.add(corners.map(toPx).join(' '));
}
}
});
return [...radii].sort();
}
function getBoxShadows(node: Node[]) {
const boxShadows = new Set<string>();
walk(node, (n) => {
if (!hasEffects(n)) return;
n.effects.filter(isShadow).forEach((shadow: Effect) => {
boxShadows.add(toBoxShadow(shadow));
});
});
return [...boxShadows];
}
export default function generateTheme(file: FileResponse): StyledSystemTheme {
const canvases = [...file.document.children];
return {
colors: getColors(canvases),
...getTypography(canvases),
radii: getRadii(canvases),
boxShadows: getBoxShadows(canvases),
};
}