Fix textShadow parsing

This commit is contained in:
Niklas von Hertzen 2017-08-11 20:40:49 +08:00
parent ad487f4585
commit 18761b7352

View File

@ -10,33 +10,85 @@ export type TextShadow = {
blur: number blur: number
}; };
const TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){3})/g; const NUMBER = /^([+-]|\d|\.)$/i;
const TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
export const parseTextShadow = (textShadow: ?string): Array<TextShadow> | null => { export const parseTextShadow = (textShadow: ?string): Array<TextShadow> | null => {
if (textShadow === 'none' || typeof textShadow !== 'string') { if (textShadow === 'none' || typeof textShadow !== 'string') {
return null; return null;
} }
const shadows = textShadow.match(TEXT_SHADOW_PROPERTY); let currentValue = '';
let isLength = false;
const values = [];
const shadows = [];
let numParens = 0;
let color = null;
if (!shadows) { const appendValue = () => {
return null; if (currentValue.length) {
} if (isLength) {
values.push(parseFloat(currentValue));
} else {
color = new Color(currentValue);
}
}
isLength = false;
currentValue = '';
};
const shadowList = []; const appendShadow = () => {
if (values.length && color !== null) {
for (let i = 0; i < shadows.length; i++) { shadows.push({
const shadow = shadows[i].match(TEXT_SHADOW_VALUES); color,
if (shadow) { offsetX: values[0] || 0,
shadowList.push({ offsetY: values[1] || 0,
color: new Color(shadow[0]), blur: values[2] || 0
offsetX: shadow[1] ? parseFloat(shadow[1].replace('px', '')) : 0,
offsetY: shadow[2] ? parseFloat(shadow[2].replace('px', '')) : 0,
blur: shadow[3] ? parseFloat(shadow[3].replace('px', '')) : 0
}); });
} }
values.splice(0, values.length);
color = null;
};
for (let i = 0; i < textShadow.length; i++) {
const c = textShadow[i];
switch (c) {
case '(':
currentValue += c;
numParens++;
break;
case ')':
currentValue += c;
numParens--;
break;
case ',':
if (numParens === 0) {
appendValue();
appendShadow();
} else {
currentValue += c;
}
break;
case ' ':
if (numParens === 0) {
appendValue();
} else {
currentValue += c;
}
break;
default:
if (currentValue.length === 0 && NUMBER.test(c)) {
isLength = true;
}
currentValue += c;
}
} }
return shadowList; appendValue();
appendShadow();
if (shadows.length === 0) {
return null;
}
return shadows;
}; };