UNPKG

1.54 kBJavaScriptView Raw
1
2import { re } from './style-re';
3
4const prefixColor = (color) => {
5 const regex = new RegExp(`^${re.colorhex}$`);
6 return (regex.test(color) ? '#' : '') + color;
7}
8
9const definedProps = obj => Object.fromEntries(
10 Object.entries(obj).filter(([k, v]) => v !== undefined)
11);
12
13/**
14 * Function to parse style string to object
15 * @function style.parse
16 * @param {string} styleString - a style string
17 * @returns {StyleObject} elements of style string
18 * @example
19 * style.parse('-CP10G_blue_D_red,Cyan_')
20 *
21 * return {
22 * 'colorize': true,
23 * 'padding': 10,
24 * 'background': 'blue',
25 * 'detail': ['red', 'Cyan']
26 * }
27 */
28const parse = (styleString) => {
29 const regex = `^${re.full}`;
30 const m = ((typeof styleString === 'string') ? styleString.match(new RegExp(regex)) : []) || [];
31
32 return definedProps({
33 'colorize': !m[1] ? undefined : !!m[1],
34 'padding': !m[2] ? undefined : parseInt(m[2].slice(1)),
35 'background': !m[3] ? undefined : prefixColor(m[3].slice(2, -1)),
36 'detail': !m[4] ? undefined : m[4].slice(2, -1).split(',').map(prefixColor),
37 'zoom': !m[5] ? undefined : (m[5] === 'Zx' ? 'x' : parseFloat(m[5].slice(1))),
38 'detailsym': !m[6] ? undefined : m[6].match(new RegExp(re.detailsym, 'g')).map((val) => {
39 const parts = val.split('_');
40 const detail = parts[1].split(',').map(prefixColor);
41 return {
42 'index': parseInt(parts[0].slice(1)),
43 'detail': detail
44 }
45 }),
46 'classes': !m[7] ? undefined : m[7],
47 'id': !m[8] ? undefined : m[8]
48 })
49}
50
51export { parse }