-
-
Notifications
You must be signed in to change notification settings - Fork 184
/
getConfigValue.js
84 lines (67 loc) · 2.07 KB
/
getConfigValue.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
import { isEmpty, throwIf, stripNegative } from './misc'
import { logGeneralError } from './../logging'
const normalizeValue = value => {
if (['string', 'function'].includes(typeof value) || Array.isArray(value)) {
return value
}
if (typeof value === 'number') {
return String(value)
}
logGeneralError(
`The config value "${Object.stringify(
value
)}" is unsupported - try a string, function, array, or number`
)
}
const matchChildKey = (from, matcher) => {
if (!matcher) return
for (const entry of Object.entries(from)) {
const [key, value] = entry
if (typeof value !== 'object') continue
// Fixes https://github.com/ben-rogerson/twin.macro/issues/104
if (!matcher.startsWith(key)) continue
const splitMatcher = matcher.split(key)
if (isEmpty(splitMatcher[1])) continue
const match = stripNegative(splitMatcher[1])
const objectMatch = value[match]
if (isEmpty(objectMatch)) continue
const isValueReturnable =
typeof objectMatch === 'string' ||
typeof objectMatch === 'number' ||
Array.isArray(objectMatch)
throwIf(!isValueReturnable, () =>
logGeneralError(
`The tailwind config is nested too deep\nReplace this with a string, number or array:\n${JSON.stringify(
objectMatch
)}`
)
)
return String(objectMatch)
}
}
/**
* Searches the tailwindConfig
* Maximum of two levels deep
*/
const getConfigValue = (from, matcher) => {
if (!from) return
// Match default value from current object
if (isEmpty(matcher) && !isEmpty(from.DEFAULT)) {
return normalizeValue(from.DEFAULT)
}
const match = from[matcher]
if (
['string', 'number', 'function'].includes(typeof match) ||
Array.isArray(match)
) {
return normalizeValue(match)
}
// Match default value from child object
const defaultMatch = typeof match === 'object' && match.DEFAULT
if (defaultMatch) {
return normalizeValue(defaultMatch)
}
const firstChildKey = matchChildKey(from, matcher)
if (firstChildKey) return firstChildKey
}
export default getConfigValue