-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
93 lines (79 loc) · 2.18 KB
/
index.js
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
/**
* @typedef {import('./types').IncrementConfig} IncrementConfig
* @typedef {import('./types').ScaleConfig} ScaleConfig
*/
/**
* Generates a scale based on the given configuration.
*
* @param {ScaleConfig} config - The configuration for generating the scale.
* @returns {Object<string, string>} The generated scale.
*/
const generateScale = (config) => {
// Merge config with defaults
const {
classPrefix,
classSuffix,
unit,
scale,
from,
to,
increment
} = getConfig(config);
// Precompute increment keys and convert them to numbers
const belowKeys = Object.keys(increment.below || {}).map(Number);
const aboveKeys = Object.keys(increment.above || {}).map(Number);
// generate scale
const spacing = {};
let size = from;
while (size <= to) {
const className = `${classPrefix}${size}${classSuffix}`;
const value = `${size / scale}${unit}`;
spacing[className] = value;
size = getNextSize(size, increment, belowKeys, aboveKeys);
}
return spacing;
};
const getConfig = (config) => {
/** @type {ScaleConfig} */
const defaultConfig = {
classPrefix: "",
classSuffix: "",
unit: "rem",
scale: 4,
from: 0,
to: 256,
increment: {
default: 1,
below: {
5: 0.5,
},
above: {
100: 2,
200: 4,
}
}
};
// Merge config with defaults
return { ...defaultConfig, ...config };
}
const getNextSize = (currentSize, increment, belowKeys, aboveKeys) => {
let nextSize = currentSize + (increment.default || 1);
for (const key of belowKeys) {
if (currentSize < key) {
nextSize = currentSize + (increment.below[key] || increment.default || 1);
return nextSize;
}
}
for (const key of aboveKeys) {
if (currentSize >= key) {
nextSize = currentSize + (increment.above[key] || increment.default || 1);
return nextSize;
}
}
return nextSize;
};
module.exports = {
generateScale,
getConfig,
getNextSize,
};;