UNPKG

1.31 kBJavaScriptView Raw
1// tooling
2import { list } from 'postcss';
3
4// return sass-like arrays as literal arrays ('(hello), (goodbye)' to [[hello], [goodbye]])
5export default function getValueAsObject(value) {
6 const hasWrappingParens = matchWrappingParens.test(value);
7 const unwrappedValue = String(hasWrappingParens ? value.replace(matchWrappingParens, '$1') : value).replace(matchTrailingComma, '');
8 const separatedValue = list.comma(unwrappedValue);
9 const firstValue = separatedValue[0];
10
11 if (firstValue === value) {
12 return value;
13 } else {
14 const objectValue = {};
15 const arrayValue = [];
16
17 separatedValue.forEach(
18 (subvalue, index) => {
19 const [ match, key, keyvalue ] = subvalue.match(matchDeclaration) || [];
20
21 if (match) {
22 objectValue[key] = getValueAsObject(keyvalue);
23 } else {
24 arrayValue[index] = getValueAsObject(subvalue);
25 }
26 }
27 );
28
29 const transformedValue = Object.keys(objectValue).length > 0
30 ? Object.assign(objectValue, arrayValue)
31 : arrayValue;
32
33 return transformedValue;
34 }
35}
36
37// match wrapping parentheses ((), (anything), (anything (anything)))
38const matchWrappingParens = /^\(([\W\w]*)\)$/g;
39
40// match a property name (any-possible_name)
41const matchDeclaration = /^([\w-]+)\s*:\s*([\W\w]+)\s*$/;
42
43// match a trailing comma
44const matchTrailingComma = /\s*,\s*$/;