-
Notifications
You must be signed in to change notification settings - Fork 1
/
sass.ts
76 lines (66 loc) · 2.37 KB
/
sass.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
/**
* Generate Sass from design tokens
*/
import fs from 'fs';
import path from 'path';
import prettier from 'prettier';
import { cssifyObject } from 'css-in-js-utils';
import { DesignTokens } from '../../types/design-tokens';
import { capitalize } from '../utils/string';
const GENERATED = path.resolve(__dirname, '..', '..', 'src', 'design-tokens');
const COLOR_FILE = path.resolve(GENERATED, '_color.scss');
const GRADIENT_FILE = path.resolve(GENERATED, '_gradient.scss');
const SHADOW_FILE = path.resolve(GENERATED, '_shadow.scss');
const TYPOGRAPHY_FILE = path.resolve(GENERATED, '_typography.scss');
function prefix(file: string): string {
return `// THIS FILE IS AUTO-GENERATED! DO NOT EDIT!
${file}`;
}
function buildColor(color: DesignTokens['color']): string {
return prefix(
Object.entries(color)
.map(([key, value]) => `$color-${key}: ${value};`)
.join('\n')
);
}
function buildGradient(gradient: DesignTokens['gradient']): string {
return prefix(
Object.entries(gradient)
.map(([key, value]) => `$gradient-${key}: ${value};`)
.join('\n')
);
}
function buildShadow(shadow: DesignTokens['shadow']): string {
return prefix(
Object.entries(shadow)
.map(([key, value]) => `$shadow-${key}: ${value};`)
.join('\n')
);
}
function buildTypography(typography: DesignTokens['typography']): string {
const variables = Object.entries(typography)
.map(([key, styles]) =>
Object.entries(styles)
.map(([property, value]) => `$typography-${key}-${property}: ${value};`)
.join('')
)
.join('');
const mixins = Object.entries(typography)
.map(
([key, styles]) =>
`
@mixin Typography--${capitalize(key)} {${cssifyObject(styles)}}`
)
.join('\n\n');
return prefix([variables, mixins].join('\n\n'));
}
// Run files through Prettier before saving (cuz we probably have whitespace errors above)
function prettify(file: string): string {
return prettier.format(file, { parser: 'scss', singleQuote: true });
}
export default function build(tokens: DesignTokens): void {
fs.writeFileSync(COLOR_FILE, prettify(buildColor(tokens.color)), 'utf8');
fs.writeFileSync(GRADIENT_FILE, prettify(buildGradient(tokens.gradient)), 'utf8');
fs.writeFileSync(SHADOW_FILE, prettify(buildShadow(tokens.shadow)), 'utf8');
fs.writeFileSync(TYPOGRAPHY_FILE, prettify(buildTypography(tokens.typography)), 'utf8');
}