format: prettify entire project

This commit is contained in:
Rim
2025-04-02 06:50:39 -04:00
parent 86f0782a98
commit 7ccc0be712
1711 changed files with 755867 additions and 235931 deletions

View File

@ -2,7 +2,7 @@ var Hack = {
ASTERISK: 'asterisk',
BANG: 'bang',
BACKSLASH: 'backslash',
UNDERSCORE: 'underscore'
UNDERSCORE: 'underscore',
};
module.exports = Hack;

View File

@ -11,7 +11,8 @@ var removeUnused = require('../remove-unused');
var restoreFromOptimizing = require('../restore-from-optimizing');
var wrapForOptimizing = require('../wrap-for-optimizing').all;
var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel;
var OptimizationLevel =
require('../../options/optimization-level').OptimizationLevel;
var Token = require('../../tokenizer/token');
var Marker = require('../../tokenizer/marker');
@ -26,7 +27,8 @@ var IgnoreProperty = 'ignore-property';
var CHARSET_TOKEN = '@charset';
var CHARSET_REGEXP = new RegExp('^' + CHARSET_TOKEN, 'i');
var DEFAULT_ROUNDING_PRECISION = require('../../options/rounding-precision').DEFAULT;
var DEFAULT_ROUNDING_PRECISION =
require('../../options/rounding-precision').DEFAULT;
var WHOLE_PIXEL_VALUE = /(?:^|\s|\()(-?\d+)px/;
var TIME_VALUE = /^(\-?[\d\.]+)(m?s)$/;
@ -40,7 +42,7 @@ var URL_PREFIX_PATTERN = /^url\(/i;
var LOCAL_PREFIX_PATTERN = /^local\(/i;
var VARIABLE_NAME_PATTERN = /^--\S+$/;
function isLocal(value){
function isLocal(value) {
return LOCAL_PREFIX_PATTERN.test(value);
}
@ -78,13 +80,35 @@ function optimizeBorderRadius(property) {
var values = property.value;
var spliceAt;
if (values.length == 3 && values[1][1] == '/' && values[0][1] == values[2][1]) {
if (
values.length == 3 &&
values[1][1] == '/' &&
values[0][1] == values[2][1]
) {
spliceAt = 1;
} else if (values.length == 5 && values[2][1] == '/' && values[0][1] == values[3][1] && values[1][1] == values[4][1]) {
} else if (
values.length == 5 &&
values[2][1] == '/' &&
values[0][1] == values[3][1] &&
values[1][1] == values[4][1]
) {
spliceAt = 2;
} else if (values.length == 7 && values[3][1] == '/' && values[0][1] == values[4][1] && values[1][1] == values[5][1] && values[2][1] == values[6][1]) {
} else if (
values.length == 7 &&
values[3][1] == '/' &&
values[0][1] == values[4][1] &&
values[1][1] == values[5][1] &&
values[2][1] == values[6][1]
) {
spliceAt = 3;
} else if (values.length == 9 && values[4][1] == '/' && values[0][1] == values[5][1] && values[1][1] == values[6][1] && values[2][1] == values[7][1] && values[3][1] == values[8][1]) {
} else if (
values.length == 9 &&
values[4][1] == '/' &&
values[0][1] == values[5][1] &&
values[1][1] == values[6][1] &&
values[2][1] == values[7][1] &&
values[3][1] == values[8][1]
) {
spliceAt = 4;
}
@ -106,51 +130,77 @@ function optimizeColors(name, value, compatibility) {
}
value = value
.replace(/(rgb|hsl)a?\((\-?\d+),(\-?\d+\%?),(\-?\d+\%?),(0*[1-9]+[0-9]*(\.?\d*)?)\)/gi, function (match, colorFn, p1, p2, p3, alpha) {
return (parseInt(alpha, 10) >= 1 ? colorFn + '(' + [p1,p2,p3].join(',') + ')' : match);
})
.replace(/rgb\((\-?\d+),(\-?\d+),(\-?\d+)\)/gi, function (match, red, green, blue) {
return shortenRgb(red, green, blue);
})
.replace(/hsl\((-?\d+),(-?\d+)%?,(-?\d+)%?\)/gi, function (match, hue, saturation, lightness) {
return shortenHsl(hue, saturation, lightness);
})
.replace(/(^|[^='"])#([0-9a-f]{6})/gi, function (match, prefix, color, at, inputValue) {
var suffix = inputValue[at + match.length];
if (suffix && HEX_VALUE_PATTERN.test(suffix)) {
return match;
} else if (color[0] == color[1] && color[2] == color[3] && color[4] == color[5]) {
return (prefix + '#' + color[0] + color[2] + color[4]).toLowerCase();
} else {
return (prefix + '#' + color).toLowerCase();
.replace(
/(rgb|hsl)a?\((\-?\d+),(\-?\d+\%?),(\-?\d+\%?),(0*[1-9]+[0-9]*(\.?\d*)?)\)/gi,
function (match, colorFn, p1, p2, p3, alpha) {
return parseInt(alpha, 10) >= 1 ?
colorFn + '(' + [p1, p2, p3].join(',') + ')'
: match;
}
})
)
.replace(
/rgb\((\-?\d+),(\-?\d+),(\-?\d+)\)/gi,
function (match, red, green, blue) {
return shortenRgb(red, green, blue);
}
)
.replace(
/hsl\((-?\d+),(-?\d+)%?,(-?\d+)%?\)/gi,
function (match, hue, saturation, lightness) {
return shortenHsl(hue, saturation, lightness);
}
)
.replace(
/(^|[^='"])#([0-9a-f]{6})/gi,
function (match, prefix, color, at, inputValue) {
var suffix = inputValue[at + match.length];
if (suffix && HEX_VALUE_PATTERN.test(suffix)) {
return match;
} else if (
color[0] == color[1] &&
color[2] == color[3] &&
color[4] == color[5]
) {
return (prefix + '#' + color[0] + color[2] + color[4]).toLowerCase();
} else {
return (prefix + '#' + color).toLowerCase();
}
}
)
.replace(/(^|[^='"])#([0-9a-f]{3})/gi, function (match, prefix, color) {
return prefix + '#' + color.toLowerCase();
})
.replace(/(rgb|rgba|hsl|hsla)\(([^\)]+)\)/gi, function (match, colorFunction, colorDef) {
var tokens = colorDef.split(',');
var colorFnLowercase = colorFunction && colorFunction.toLowerCase();
var applies = (colorFnLowercase == 'hsl' && tokens.length == 3) ||
(colorFnLowercase == 'hsla' && tokens.length == 4) ||
(colorFnLowercase == 'rgb' && tokens.length === 3 && colorDef.indexOf('%') > 0) ||
(colorFnLowercase == 'rgba' && tokens.length == 4 && colorDef.indexOf('%') > 0);
.replace(
/(rgb|rgba|hsl|hsla)\(([^\)]+)\)/gi,
function (match, colorFunction, colorDef) {
var tokens = colorDef.split(',');
var colorFnLowercase = colorFunction && colorFunction.toLowerCase();
var applies =
(colorFnLowercase == 'hsl' && tokens.length == 3) ||
(colorFnLowercase == 'hsla' && tokens.length == 4) ||
(colorFnLowercase == 'rgb' &&
tokens.length === 3 &&
colorDef.indexOf('%') > 0) ||
(colorFnLowercase == 'rgba' &&
tokens.length == 4 &&
colorDef.indexOf('%') > 0);
if (!applies) {
return match;
if (!applies) {
return match;
}
if (tokens[1].indexOf('%') == -1) {
tokens[1] += '%';
}
if (tokens[2].indexOf('%') == -1) {
tokens[2] += '%';
}
return colorFunction + '(' + tokens.join(',') + ')';
}
if (tokens[1].indexOf('%') == -1) {
tokens[1] += '%';
}
if (tokens[2].indexOf('%') == -1) {
tokens[2] += '%';
}
return colorFunction + '(' + tokens.join(',') + ')';
});
);
if (compatibility.colors.opacity && name.indexOf('background') == -1) {
value = value.replace(/(?:rgba|hsla)\(0,0%?,0%?,0\)/g, function (match) {
@ -167,9 +217,12 @@ function optimizeColors(name, value, compatibility) {
function optimizeFilter(property) {
if (property.value.length == 1) {
property.value[0][1] = property.value[0][1].replace(/progid:DXImageTransform\.Microsoft\.(Alpha|Chroma)(\W)/, function (match, filter, suffix) {
return filter.toLowerCase() + suffix;
});
property.value[0][1] = property.value[0][1].replace(
/progid:DXImageTransform\.Microsoft\.(Alpha|Chroma)(\W)/,
function (match, filter, suffix) {
return filter.toLowerCase() + suffix;
}
);
}
property.value[0][1] = property.value[0][1]
@ -193,7 +246,13 @@ function optimizeMultipleZeros(property) {
var values = property.value;
var spliceAt;
if (values.length == 4 && values[0][1] === '0' && values[1][1] === '0' && values[2][1] === '0' && values[3][1] === '0') {
if (
values.length == 4 &&
values[0][1] === '0' &&
values[1][1] === '0' &&
values[2][1] === '0' &&
values[3][1] === '0'
) {
if (property.name.indexOf('box-shadow') > -1) {
spliceAt = 2;
} else {
@ -228,15 +287,27 @@ function optimizePixelLengths(_, value, compatibility) {
return match;
}
if (compatibility.properties.shorterLengthUnits && compatibility.units.pt && intVal * 3 % 4 === 0) {
newValue = intVal * 3 / 4 + 'pt';
if (
compatibility.properties.shorterLengthUnits &&
compatibility.units.pt &&
(intVal * 3) % 4 === 0
) {
newValue = (intVal * 3) / 4 + 'pt';
}
if (compatibility.properties.shorterLengthUnits && compatibility.units.pc && intVal % 16 === 0) {
if (
compatibility.properties.shorterLengthUnits &&
compatibility.units.pc &&
intVal % 16 === 0
) {
newValue = intVal / 16 + 'pc';
}
if (compatibility.properties.shorterLengthUnits && compatibility.units.in && intVal % 96 === 0) {
if (
compatibility.properties.shorterLengthUnits &&
compatibility.units.in &&
intVal % 96 === 0
) {
newValue = intVal / 96 + 'in';
}
@ -255,19 +326,23 @@ function optimizePrecision(_, value, precisionOptions) {
return value
.replace(precisionOptions.decimalPointMatcher, '$1$2$3')
.replace(precisionOptions.zeroMatcher, function (match, integerPart, fractionPart, unit) {
var multiplier = precisionOptions.units[unit].multiplier;
var parsedInteger = parseInt(integerPart);
var integer = isNaN(parsedInteger) ? 0 : parsedInteger;
var fraction = parseFloat(fractionPart);
.replace(
precisionOptions.zeroMatcher,
function (match, integerPart, fractionPart, unit) {
var multiplier = precisionOptions.units[unit].multiplier;
var parsedInteger = parseInt(integerPart);
var integer = isNaN(parsedInteger) ? 0 : parsedInteger;
var fraction = parseFloat(fractionPart);
return Math.round((integer + fraction) * multiplier) / multiplier + unit;
});
return (
Math.round((integer + fraction) * multiplier) / multiplier + unit
);
}
);
}
function optimizeTimeUnits(_, value) {
if (!TIME_VALUE.test(value))
return value;
if (!TIME_VALUE.test(value)) return value;
return value.replace(TIME_VALUE, function (match, val, unit) {
var newValue;
@ -287,11 +362,23 @@ function optimizeUnits(name, value, unitsRegexp) {
return value;
}
if (name == 'flex' || name == '-ms-flex' || name == '-webkit-flex' || name == 'flex-basis' || name == '-webkit-flex-basis') {
if (
name == 'flex' ||
name == '-ms-flex' ||
name == '-webkit-flex' ||
name == 'flex-basis' ||
name == '-webkit-flex-basis'
) {
return value;
}
if (value.indexOf('%') > 0 && (name == 'height' || name == 'max-height' || name == 'width' || name == 'max-width')) {
if (
value.indexOf('%') > 0 &&
(name == 'height' ||
name == 'max-height' ||
name == 'width' ||
name == 'max-width')
) {
return value;
}
@ -301,11 +388,18 @@ function optimizeUnits(name, value, unitsRegexp) {
}
function optimizeWhitespace(name, value) {
if (name.indexOf('filter') > -1 || value.indexOf(' ') == -1 || value.indexOf('expression') === 0) {
if (
name.indexOf('filter') > -1 ||
value.indexOf(' ') == -1 ||
value.indexOf('expression') === 0
) {
return value;
}
if (value.indexOf(Marker.SINGLE_QUOTE) > -1 || value.indexOf(Marker.DOUBLE_QUOTE) > -1) {
if (
value.indexOf(Marker.SINGLE_QUOTE) > -1 ||
value.indexOf(Marker.DOUBLE_QUOTE) > -1
) {
return value;
}
@ -351,24 +445,38 @@ function optimizeZeroUnits(name, value) {
}
function removeQuotes(name, value) {
if (name == 'content' || name.indexOf('font-variation-settings') > -1 || name.indexOf('font-feature-settings') > -1 || name == 'grid' || name.indexOf('grid-') > -1) {
if (
name == 'content' ||
name.indexOf('font-variation-settings') > -1 ||
name.indexOf('font-feature-settings') > -1 ||
name == 'grid' ||
name.indexOf('grid-') > -1
) {
return value;
}
return QUOTED_BUT_SAFE_PATTERN.test(value) ?
value.substring(1, value.length - 1) :
value;
value.substring(1, value.length - 1)
: value;
}
function removeUrlQuotes(value) {
return /^url\(['"].+['"]\)$/.test(value) && !/^url\(['"].*[\*\s\(\)'"].*['"]\)$/.test(value) && !/^url\(['"]data:[^;]+;charset/.test(value) ?
value.replace(/["']/g, '') :
value;
return (
/^url\(['"].+['"]\)$/.test(value) &&
!/^url\(['"].*[\*\s\(\)'"].*['"]\)$/.test(value) &&
!/^url\(['"]data:[^;]+;charset/.test(value)
) ?
value.replace(/["']/g, '')
: value;
}
function transformValue(propertyName, propertyValue, rule, transformCallback) {
var selector = serializeRules(rule);
var transformedValue = transformCallback(propertyName, propertyValue, selector);
var transformedValue = transformCallback(
propertyName,
propertyValue,
selector
);
if (transformedValue === undefined) {
return propertyValue;
@ -389,35 +497,62 @@ function optimizeBody(rule, properties, context) {
var propertyToken;
var _properties = wrapForOptimizing(properties, true);
propertyLoop:
for (var i = 0, l = _properties.length; i < l; i++) {
propertyLoop: for (var i = 0, l = _properties.length; i < l; i++) {
property = _properties[i];
name = property.name;
if (!PROPERTY_NAME_PATTERN.test(name)) {
propertyToken = property.all[property.position];
context.warnings.push('Invalid property name \'' + name + '\' at ' + formatPosition(propertyToken[1][2][0]) + '. Ignoring.');
context.warnings.push(
"Invalid property name '" +
name +
"' at " +
formatPosition(propertyToken[1][2][0]) +
'. Ignoring.'
);
property.unused = true;
}
if (property.value.length === 0) {
propertyToken = property.all[property.position];
context.warnings.push('Empty property \'' + name + '\' at ' + formatPosition(propertyToken[1][2][0]) + '. Ignoring.');
context.warnings.push(
"Empty property '" +
name +
"' at " +
formatPosition(propertyToken[1][2][0]) +
'. Ignoring.'
);
property.unused = true;
}
if (property.hack && (
(property.hack[0] == Hack.ASTERISK || property.hack[0] == Hack.UNDERSCORE) && !options.compatibility.properties.iePrefixHack ||
property.hack[0] == Hack.BACKSLASH && !options.compatibility.properties.ieSuffixHack ||
property.hack[0] == Hack.BANG && !options.compatibility.properties.ieBangHack)) {
if (
property.hack &&
(((property.hack[0] == Hack.ASTERISK ||
property.hack[0] == Hack.UNDERSCORE) &&
!options.compatibility.properties.iePrefixHack) ||
(property.hack[0] == Hack.BACKSLASH &&
!options.compatibility.properties.ieSuffixHack) ||
(property.hack[0] == Hack.BANG &&
!options.compatibility.properties.ieBangHack))
) {
property.unused = true;
}
if (levelOptions.removeNegativePaddings && name.indexOf('padding') === 0 && (isNegative(property.value[0]) || isNegative(property.value[1]) || isNegative(property.value[2]) || isNegative(property.value[3]))) {
if (
levelOptions.removeNegativePaddings &&
name.indexOf('padding') === 0 &&
(isNegative(property.value[0]) ||
isNegative(property.value[1]) ||
isNegative(property.value[2]) ||
isNegative(property.value[3]))
) {
property.unused = true;
}
if (!options.compatibility.properties.ieFilters && isLegacyFilter(property)) {
if (
!options.compatibility.properties.ieFilters &&
isLegacyFilter(property)
) {
property.unused = true;
}
@ -441,39 +576,49 @@ function optimizeBody(rule, properties, context) {
if (type == Token.PROPERTY_BLOCK) {
property.unused = true;
context.warnings.push('Invalid value token at ' + formatPosition(value[0][1][2][0]) + '. Ignoring.');
context.warnings.push(
'Invalid value token at ' +
formatPosition(value[0][1][2][0]) +
'. Ignoring.'
);
break;
}
if (valueIsUrl && !context.validator.isUrl(value)) {
property.unused = true;
context.warnings.push('Broken URL \'' + value + '\' at ' + formatPosition(property.value[j][2][0]) + '. Ignoring.');
context.warnings.push(
"Broken URL '" +
value +
"' at " +
formatPosition(property.value[j][2][0]) +
'. Ignoring.'
);
break;
}
if (valueIsUrl) {
value = levelOptions.normalizeUrls ?
normalizeUrl(value) :
value;
value = !options.compatibility.properties.urlQuotes ?
removeUrlQuotes(value) :
value;
value = levelOptions.normalizeUrls ? normalizeUrl(value) : value;
value =
!options.compatibility.properties.urlQuotes ?
removeUrlQuotes(value)
: value;
} else if (isQuoted(value) || isLocal(value)) {
value = levelOptions.removeQuotes ?
removeQuotes(name, value) :
value;
value = levelOptions.removeQuotes ? removeQuotes(name, value) : value;
} else {
value = levelOptions.removeWhitespace ?
optimizeWhitespace(name, value) :
value;
value =
levelOptions.removeWhitespace ?
optimizeWhitespace(name, value)
: value;
value = optimizePrecision(name, value, options.precision);
value = optimizePixelLengths(name, value, options.compatibility);
value = levelOptions.replaceTimeUnits ?
optimizeTimeUnits(name, value) :
value;
value = levelOptions.replaceZeroUnits ?
optimizeZeroUnits(name, value) :
value;
value =
levelOptions.replaceTimeUnits ?
optimizeTimeUnits(name, value)
: value;
value =
levelOptions.replaceZeroUnits ?
optimizeZeroUnits(name, value)
: value;
if (options.compatibility.properties.zeroUnits) {
value = optimizeZeroDegUnit(name, value);
@ -501,9 +646,17 @@ function optimizeBody(rule, properties, context) {
if (name == 'background' && levelOptions.optimizeBackground) {
optimizeBackground(property);
} else if (name.indexOf('border') === 0 && name.indexOf('radius') > 0 && levelOptions.optimizeBorderRadius) {
} else if (
name.indexOf('border') === 0 &&
name.indexOf('radius') > 0 &&
levelOptions.optimizeBorderRadius
) {
optimizeBorderRadius(property);
} else if (name == 'filter'&& levelOptions.optimizeFilter && options.compatibility.properties.ieFilters) {
} else if (
name == 'filter' &&
levelOptions.optimizeFilter &&
options.compatibility.properties.ieFilters
) {
optimizeFilter(property);
} else if (name == 'font-weight' && levelOptions.optimizeFontWeight) {
optimizeFontWeight(property, 0);
@ -538,7 +691,12 @@ function removeComments(tokens, options) {
}
function optimizeComment(token, options) {
if (token[1][2] == Marker.EXCLAMATION && (options.level[OptimizationLevel.One].specialComments == 'all' || options.commentsKept < options.level[OptimizationLevel.One].specialComments)) {
if (
token[1][2] == Marker.EXCLAMATION &&
(options.level[OptimizationLevel.One].specialComments == 'all' ||
options.commentsKept <
options.level[OptimizationLevel.One].specialComments)
) {
options.commentsKept++;
return;
}
@ -552,11 +710,9 @@ function cleanupCharsets(tokens) {
for (var i = 0, l = tokens.length; i < l; i++) {
var token = tokens[i];
if (token[0] != Token.AT_RULE)
continue;
if (token[0] != Token.AT_RULE) continue;
if (!CHARSET_REGEXP.test(token[1]))
continue;
if (!CHARSET_REGEXP.test(token[1])) continue;
if (hasCharset || token[1].indexOf(CHARSET_TOKEN) == -1) {
tokens.splice(i, 1);
@ -565,7 +721,10 @@ function cleanupCharsets(tokens) {
} else {
hasCharset = true;
tokens.splice(i, 1);
tokens.unshift([Token.AT_RULE, token[1].replace(CHARSET_REGEXP, CHARSET_TOKEN)]);
tokens.unshift([
Token.AT_RULE,
token[1].replace(CHARSET_REGEXP, CHARSET_TOKEN),
]);
}
}
}
@ -606,8 +765,14 @@ function buildPrecisionOptions(roundingPrecision) {
if (optimizable.length > 0) {
precisionOptions.enabled = true;
precisionOptions.decimalPointMatcher = new RegExp('(\\d)\\.($|' + optimizable.join('|') + ')($|\\W)', 'g');
precisionOptions.zeroMatcher = new RegExp('(\\d*)(\\.\\d+)(' + optimizable.join('|') + ')', 'g');
precisionOptions.decimalPointMatcher = new RegExp(
'(\\d)\\.($|' + optimizable.join('|') + ')($|\\W)',
'g'
);
precisionOptions.zeroMatcher = new RegExp(
'(\\d*)(\\.\\d+)(' + optimizable.join('|') + ')',
'g'
);
}
return precisionOptions;
@ -623,9 +788,11 @@ function isLegacyFilter(property) {
if (property.name == 'filter' || property.name == '-ms-filter') {
value = property.value[0][1];
return value.indexOf('progid') > -1 ||
return (
value.indexOf('progid') > -1 ||
value.indexOf('alpha') === 0 ||
value.indexOf('chroma') === 0;
value.indexOf('chroma') === 0
);
} else {
return false;
}
@ -636,13 +803,15 @@ function level1Optimize(tokens, context) {
var levelOptions = options.level[OptimizationLevel.One];
var ie7Hack = options.compatibility.selectors.ie7Hack;
var adjacentSpace = options.compatibility.selectors.adjacentSpace;
var spaceAfterClosingBrace = options.compatibility.properties.spaceAfterClosingBrace;
var spaceAfterClosingBrace =
options.compatibility.properties.spaceAfterClosingBrace;
var format = options.format;
var mayHaveCharset = false;
var afterRules = false;
options.unitsRegexp = options.unitsRegexp || buildUnitRegexp(options);
options.precision = options.precision || buildPrecisionOptions(levelOptions.roundingPrecision);
options.precision =
options.precision || buildPrecisionOptions(levelOptions.roundingPrecision);
options.commentsKept = options.commentsKept || 0;
for (var i = 0, l = tokens.length; i < l; i++) {
@ -659,7 +828,10 @@ function level1Optimize(tokens, context) {
afterRules = true;
break;
case Token.NESTED_BLOCK:
token[1] = levelOptions.tidyBlockScopes ? tidyBlock(token[1], spaceAfterClosingBrace) : token[1];
token[1] =
levelOptions.tidyBlockScopes ?
tidyBlock(token[1], spaceAfterClosingBrace)
: token[1];
level1Optimize(token[2], context);
afterRules = true;
break;
@ -667,14 +839,30 @@ function level1Optimize(tokens, context) {
optimizeComment(token, options);
break;
case Token.RULE:
token[1] = levelOptions.tidySelectors ? tidyRules(token[1], !ie7Hack, adjacentSpace, format, context.warnings) : token[1];
token[1] = token[1].length > 1 ? sortSelectors(token[1], levelOptions.selectorsSortingMethod) : token[1];
token[1] =
levelOptions.tidySelectors ?
tidyRules(
token[1],
!ie7Hack,
adjacentSpace,
format,
context.warnings
)
: token[1];
token[1] =
token[1].length > 1 ?
sortSelectors(token[1], levelOptions.selectorsSortingMethod)
: token[1];
optimizeBody(token[1], token[2], context);
afterRules = true;
break;
}
if (token[0] == Token.COMMENT && token[1].length === 0 || levelOptions.removeEmpty && (token[1].length === 0 || (token[2] && token[2].length === 0))) {
if (
(token[0] == Token.COMMENT && token[1].length === 0) ||
(levelOptions.removeEmpty &&
(token[1].length === 0 || (token[2] && token[2].length === 0)))
) {
tokens.splice(i, 1);
i--;
l--;

View File

@ -146,7 +146,7 @@ var COLORS = {
white: '#fff',
whitesmoke: '#f5f5f5',
yellow: '#ff0',
yellowgreen: '#9acd32'
yellowgreen: '#9acd32',
};
var toHex = {};
@ -162,8 +162,14 @@ for (var name in COLORS) {
}
}
var toHexPattern = new RegExp('(^| |,|\\))(' + Object.keys(toHex).join('|') + ')( |,|\\)|$)', 'ig');
var toNamePattern = new RegExp('(' + Object.keys(toName).join('|') + ')([^a-f0-9]|$)', 'ig');
var toHexPattern = new RegExp(
'(^| |,|\\))(' + Object.keys(toHex).join('|') + ')( |,|\\)|$)',
'ig'
);
var toNamePattern = new RegExp(
'(' + Object.keys(toName).join('|') + ')([^a-f0-9]|$)',
'ig'
);
function hexConverter(match, prefix, colorValue, suffix) {
return prefix + toHex[colorValue.toLowerCase()] + suffix;
@ -181,9 +187,7 @@ function shortenHex(value) {
shortened = shortened.replace(toHexPattern, hexConverter);
}
return hasHex ?
shortened.replace(toNamePattern, nameConverter) :
shortened;
return hasHex ? shortened.replace(toNamePattern, nameConverter) : shortened;
}
module.exports = shortenHex;

View File

@ -6,32 +6,25 @@ function hslToRgb(h, s, l) {
// normalize hue orientation b/w 0 and 360 degrees
h = h % 360;
if (h < 0)
h += 360;
if (h < 0) h += 360;
h = ~~h / 360;
if (s < 0)
s = 0;
else if (s > 100)
s = 100;
if (s < 0) s = 0;
else if (s > 100) s = 100;
s = ~~s / 100;
if (l < 0)
l = 0;
else if (l > 100)
l = 100;
if (l < 0) l = 0;
else if (l > 100) l = 100;
l = ~~l / 100;
if (s === 0) {
r = g = b = l; // achromatic
} else {
var q = l < 0.5 ?
l * (1 + s) :
l + s - l * s;
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hueToRgb(p, q, h + 1/3);
r = hueToRgb(p, q, h + 1 / 3);
g = hueToRgb(p, q, h);
b = hueToRgb(p, q, h - 1/3);
b = hueToRgb(p, q, h - 1 / 3);
}
return [~~(r * 255), ~~(g * 255), ~~(b * 255)];
@ -40,9 +33,9 @@ function hslToRgb(h, s, l) {
function hueToRgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
@ -52,10 +45,12 @@ function shortenHsl(hue, saturation, lightness) {
var greenAsHex = asRgb[1].toString(16);
var blueAsHex = asRgb[2].toString(16);
return '#' +
return (
'#' +
((redAsHex.length == 1 ? '0' : '') + redAsHex) +
((greenAsHex.length == 1 ? '0' : '') + greenAsHex) +
((blueAsHex.length == 1 ? '0' : '') + blueAsHex);
((blueAsHex.length == 1 ? '0' : '') + blueAsHex)
);
}
module.exports = shortenHsl;

View File

@ -4,7 +4,17 @@ function shortenRgb(red, green, blue) {
var normalizedBlue = Math.max(0, Math.min(parseInt(blue), 255));
// Credit: Asen http://jsbin.com/UPUmaGOc/2/edit?js,console
return '#' + ('00000' + (normalizedRed << 16 | normalizedGreen << 8 | normalizedBlue).toString(16)).slice(-6);
return (
'#' +
(
'00000' +
(
(normalizedRed << 16) |
(normalizedGreen << 8) |
normalizedBlue
).toString(16)
).slice(-6)
);
}
module.exports = shortenRgb;

View File

@ -5,7 +5,9 @@ function tidyBlock(values, spaceAfterClosingBrace) {
var i;
for (i = values.length - 1; i >= 0; i--) {
withoutSpaceAfterClosingBrace = !spaceAfterClosingBrace && SUPPORTED_COMPACT_BLOCK_MATCHER.test(values[i][1]);
withoutSpaceAfterClosingBrace =
!spaceAfterClosingBrace &&
SUPPORTED_COMPACT_BLOCK_MATCHER.test(values[i][1]);
values[i][1] = values[i][1]
.replace(/\n|\r\n/g, ' ')

View File

@ -28,9 +28,18 @@ function hasInvalidCharacters(value) {
if (isEscaped) {
// continue as always
} else if (character == Marker.SINGLE_QUOTE || character == Marker.DOUBLE_QUOTE) {
} else if (
character == Marker.SINGLE_QUOTE ||
character == Marker.DOUBLE_QUOTE
) {
isQuote = !isQuote;
} else if (!isQuote && (character == Marker.CLOSE_CURLY_BRACKET || character == Marker.EXCLAMATION || character == LESS_THAN || character == Marker.SEMICOLON)) {
} else if (
!isQuote &&
(character == Marker.CLOSE_CURLY_BRACKET ||
character == Marker.EXCLAMATION ||
character == LESS_THAN ||
character == Marker.SEMICOLON)
) {
isInvalid = true;
break;
} else if (!isQuote && i === 0 && RELATION_PATTERN.test(character)) {
@ -61,16 +70,23 @@ function removeWhitespace(value, format) {
var wasRelation = false;
var wasWhitespace = false;
var withCaseAttribute = CASE_ATTRIBUTE_PATTERN.test(value);
var spaceAroundRelation = format && format.spaces[Spaces.AroundSelectorRelation];
var spaceAroundRelation =
format && format.spaces[Spaces.AroundSelectorRelation];
var i, l;
for (i = 0, l = value.length; i < l; i++) {
character = value[i];
isNewLineNix = character == Marker.NEW_LINE_NIX;
isNewLineWin = character == Marker.NEW_LINE_NIX && value[i - 1] == Marker.CARRIAGE_RETURN;
isNewLineWin =
character == Marker.NEW_LINE_NIX &&
value[i - 1] == Marker.CARRIAGE_RETURN;
isQuoted = isSingleQuoted || isDoubleQuoted;
isRelation = !isAttribute && !isEscaped && roundBracketLevel === 0 && RELATION_PATTERN.test(character);
isRelation =
!isAttribute &&
!isEscaped &&
roundBracketLevel === 0 &&
RELATION_PATTERN.test(character);
isWhitespace = WHITESPACE_PATTERN.test(character);
if (wasEscaped && isQuoted && isNewLineWin) {
@ -111,11 +127,19 @@ function removeWhitespace(value, format) {
} else if (!isWhitespace && wasRelation && spaceAroundRelation) {
stripped.push(Marker.SPACE);
stripped.push(character);
} else if (isWhitespace && (isAttribute || roundBracketLevel > 0) && !isQuoted) {
} else if (
isWhitespace &&
(isAttribute || roundBracketLevel > 0) &&
!isQuoted
) {
// skip space
} else if (isWhitespace && wasWhitespace && !isQuoted) {
// skip extra space
} else if ((isNewLineWin || isNewLineNix) && (isAttribute || roundBracketLevel > 0) && isQuoted) {
} else if (
(isNewLineWin || isNewLineNix) &&
(isAttribute || roundBracketLevel > 0) &&
isQuoted
) {
// skip newline
} else if (isRelation && wasWhitespace && !spaceAroundRelation) {
stripped.pop();
@ -136,12 +160,12 @@ function removeWhitespace(value, format) {
}
return withCaseAttribute ?
stripped.join('').replace(CASE_RESTORE_PATTERN, '$1 $2]') :
stripped.join('');
stripped.join('').replace(CASE_RESTORE_PATTERN, '$1 $2]')
: stripped.join('');
}
function removeQuotes(value) {
if (value.indexOf('\'') == -1 && value.indexOf('"') == -1) {
if (value.indexOf("'") == -1 && value.indexOf('"') == -1) {
return value;
}
@ -157,7 +181,13 @@ function tidyRules(rules, removeUnsupported, adjacentSpace, format, warnings) {
var repeated = [];
function removeHTMLComment(rule, match) {
warnings.push('HTML comment \'' + match + '\' at ' + formatPosition(rule[2][0]) + '. Removing.');
warnings.push(
"HTML comment '" +
match +
"' at " +
formatPosition(rule[2][0]) +
'. Removing.'
);
return '';
}
@ -165,10 +195,19 @@ function tidyRules(rules, removeUnsupported, adjacentSpace, format, warnings) {
var rule = rules[i];
var reduced = rule[1];
reduced = reduced.replace(HTML_COMMENT_PATTERN, removeHTMLComment.bind(null, rule));
reduced = reduced.replace(
HTML_COMMENT_PATTERN,
removeHTMLComment.bind(null, rule)
);
if (hasInvalidCharacters(reduced)) {
warnings.push('Invalid selector \'' + rule[1] + '\' at ' + formatPosition(rule[2][0]) + '. Ignoring.');
warnings.push(
"Invalid selector '" +
rule[1] +
"' at " +
formatPosition(rule[2][0]) +
'. Ignoring.'
);
continue;
}
@ -183,7 +222,10 @@ function tidyRules(rules, removeUnsupported, adjacentSpace, format, warnings) {
continue;
}
if (removeUnsupported && reduced.indexOf(ASTERISK_FIRST_CHILD_PLUS_HTML_HACK) > -1) {
if (
removeUnsupported &&
reduced.indexOf(ASTERISK_FIRST_CHILD_PLUS_HTML_HACK) > -1
) {
continue;
}
@ -203,7 +245,13 @@ function tidyRules(rules, removeUnsupported, adjacentSpace, format, warnings) {
}
if (list.length == 1 && list[0][1].length === 0) {
warnings.push('Empty selector \'' + list[0][1] + '\' at ' + formatPosition(list[0][2][0]) + '. Ignoring.');
warnings.push(
"Empty selector '" +
list[0][1] +
"' at " +
formatPosition(list[0][2][0]) +
'. Ignoring.'
);
list = [];
}

View File

@ -21,13 +21,21 @@ function _anyIsInherit(values) {
function _colorFilter(validator) {
return function (value) {
return value[1] == 'invert' || validator.isColor(value[1]) || validator.isPrefixed(value[1]);
return (
value[1] == 'invert' ||
validator.isColor(value[1]) ||
validator.isPrefixed(value[1])
);
};
}
function _styleFilter(validator) {
return function (value) {
return value[1] != 'inherit' && validator.isStyleKeyword(value[1]) && !validator.isColorFunction(value[1]);
return (
value[1] != 'inherit' &&
validator.isStyleKeyword(value[1]) &&
!validator.isColorFunction(value[1])
);
};
}
@ -38,42 +46,70 @@ function _wrapDefault(name, property, compactable) {
Token.PROPERTY,
[Token.PROPERTY_NAME, name],
[Token.PROPERTY_VALUE, descriptor.defaultValue[0]],
[Token.PROPERTY_VALUE, descriptor.defaultValue[1]]
[Token.PROPERTY_VALUE, descriptor.defaultValue[1]],
]);
} else if (descriptor.doubleValues && descriptor.defaultValue.length == 1) {
return wrapSingle([
Token.PROPERTY,
[Token.PROPERTY_NAME, name],
[Token.PROPERTY_VALUE, descriptor.defaultValue[0]]
[Token.PROPERTY_VALUE, descriptor.defaultValue[0]],
]);
} else {
return wrapSingle([
Token.PROPERTY,
[Token.PROPERTY_NAME, name],
[Token.PROPERTY_VALUE, descriptor.defaultValue]
[Token.PROPERTY_VALUE, descriptor.defaultValue],
]);
}
}
function _widthFilter(validator) {
return function (value) {
return value[1] != 'inherit' &&
(validator.isWidth(value[1]) || validator.isUnit(value[1]) && !validator.isDynamicUnit(value[1])) &&
return (
value[1] != 'inherit' &&
(validator.isWidth(value[1]) ||
(validator.isUnit(value[1]) && !validator.isDynamicUnit(value[1]))) &&
!validator.isStyleKeyword(value[1]) &&
!validator.isColorFunction(value[1]);
!validator.isColorFunction(value[1])
);
};
}
function animation(property, compactable, validator) {
var duration = _wrapDefault(property.name + '-duration', property, compactable);
var timing = _wrapDefault(property.name + '-timing-function', property, compactable);
var duration = _wrapDefault(
property.name + '-duration',
property,
compactable
);
var timing = _wrapDefault(
property.name + '-timing-function',
property,
compactable
);
var delay = _wrapDefault(property.name + '-delay', property, compactable);
var iteration = _wrapDefault(property.name + '-iteration-count', property, compactable);
var direction = _wrapDefault(property.name + '-direction', property, compactable);
var iteration = _wrapDefault(
property.name + '-iteration-count',
property,
compactable
);
var direction = _wrapDefault(
property.name + '-direction',
property,
compactable
);
var fill = _wrapDefault(property.name + '-fill-mode', property, compactable);
var play = _wrapDefault(property.name + '-play-state', property, compactable);
var name = _wrapDefault(property.name + '-name', property, compactable);
var components = [duration, timing, delay, iteration, direction, fill, play, name];
var components = [
duration,
timing,
delay,
iteration,
direction,
fill,
play,
name,
];
var values = property.value;
var value;
var durationSet = false;
@ -88,12 +124,24 @@ function animation(property, compactable, validator) {
var l;
if (property.value.length == 1 && property.value[0][1] == 'inherit') {
duration.value = timing.value = delay.value = iteration.value = direction.value = fill.value = play.value = name.value = property.value;
duration.value =
timing.value =
delay.value =
iteration.value =
direction.value =
fill.value =
play.value =
name.value =
property.value;
return components;
}
if (values.length > 1 && _anyIsInherit(values)) {
throw new InvalidPropertyError('Invalid animation values at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
throw new InvalidPropertyError(
'Invalid animation values at ' +
formatPosition(values[0][2][0]) +
'. Ignoring.'
);
}
for (i = 0, l = values.length; i < l; i++) {
@ -105,13 +153,23 @@ function animation(property, compactable, validator) {
} else if (validator.isTime(value[1]) && !delaySet) {
delay.value = [value];
delaySet = true;
} else if ((validator.isGlobal(value[1]) || validator.isTimingFunction(value[1])) && !timingSet) {
} else if (
(validator.isGlobal(value[1]) || validator.isTimingFunction(value[1])) &&
!timingSet
) {
timing.value = [value];
timingSet = true;
} else if ((validator.isAnimationIterationCountKeyword(value[1]) || validator.isPositiveNumber(value[1])) && !iterationSet) {
} else if (
(validator.isAnimationIterationCountKeyword(value[1]) ||
validator.isPositiveNumber(value[1])) &&
!iterationSet
) {
iteration.value = [value];
iterationSet = true;
} else if (validator.isAnimationDirectionKeyword(value[1]) && !directionSet) {
} else if (
validator.isAnimationDirectionKeyword(value[1]) &&
!directionSet
) {
direction.value = [value];
directionSet = true;
} else if (validator.isAnimationFillModeKeyword(value[1]) && !fillSet) {
@ -120,11 +178,19 @@ function animation(property, compactable, validator) {
} else if (validator.isAnimationPlayStateKeyword(value[1]) && !playSet) {
play.value = [value];
playSet = true;
} else if ((validator.isAnimationNameKeyword(value[1]) || validator.isIdentifier(value[1])) && !nameSet) {
} else if (
(validator.isAnimationNameKeyword(value[1]) ||
validator.isIdentifier(value[1])) &&
!nameSet
) {
name.value = [value];
nameSet = true;
} else {
throw new InvalidPropertyError('Invalid animation value at ' + formatPosition(value[2][0]) + '. Ignoring.');
throw new InvalidPropertyError(
'Invalid animation value at ' +
formatPosition(value[2][0]) +
'. Ignoring.'
);
}
}
@ -140,7 +206,16 @@ function background(property, compactable, validator) {
var origin = _wrapDefault('background-origin', property, compactable);
var clip = _wrapDefault('background-clip', property, compactable);
var color = _wrapDefault('background-color', property, compactable);
var components = [image, position, size, repeat, attachment, origin, clip, color];
var components = [
image,
position,
size,
repeat,
attachment,
origin,
clip,
color,
];
var values = property.value;
var positionSet = false;
@ -152,7 +227,14 @@ function background(property, compactable, validator) {
if (property.value.length == 1 && property.value[0][1] == 'inherit') {
// NOTE: 'inherit' is not a valid value for background-attachment
color.value = image.value = repeat.value = position.value = size.value = origin.value = clip.value = property.value;
color.value =
image.value =
repeat.value =
position.value =
size.value =
origin.value =
clip.value =
property.value;
return components;
}
@ -166,7 +248,10 @@ function background(property, compactable, validator) {
if (validator.isBackgroundAttachmentKeyword(value[1])) {
attachment.value = [value];
anyValueSet = true;
} else if (validator.isBackgroundClipKeyword(value[1]) || validator.isBackgroundOriginKeyword(value[1])) {
} else if (
validator.isBackgroundClipKeyword(value[1]) ||
validator.isBackgroundOriginKeyword(value[1])
) {
if (clipSet) {
origin.value = [value];
originSet = true;
@ -183,7 +268,12 @@ function background(property, compactable, validator) {
repeatSet = true;
}
anyValueSet = true;
} else if (validator.isBackgroundPositionKeyword(value[1]) || validator.isBackgroundSizeKeyword(value[1]) || validator.isUnit(value[1]) || validator.isDynamicUnit(value[1])) {
} else if (
validator.isBackgroundPositionKeyword(value[1]) ||
validator.isBackgroundSizeKeyword(value[1]) ||
validator.isUnit(value[1]) ||
validator.isDynamicUnit(value[1])
) {
if (i > 0) {
var previousValue = values[i - 1];
@ -193,21 +283,23 @@ function background(property, compactable, validator) {
size.value = [previousValue, value];
i -= 2;
} else {
if (!positionSet)
position.value = [];
if (!positionSet) position.value = [];
position.value.unshift(value);
positionSet = true;
}
} else {
if (!positionSet)
position.value = [];
if (!positionSet) position.value = [];
position.value.unshift(value);
positionSet = true;
}
anyValueSet = true;
} else if ((color.value[0][1] == compactable[color.name].defaultValue || color.value[0][1] == 'none') && (validator.isColor(value[1]) || validator.isPrefixed(value[1]))) {
} else if (
(color.value[0][1] == compactable[color.name].defaultValue ||
color.value[0][1] == 'none') &&
(validator.isColor(value[1]) || validator.isPrefixed(value[1]))
) {
color.value = [value];
anyValueSet = true;
} else if (validator.isUrl(value[1]) || validator.isFunction(value[1])) {
@ -216,11 +308,14 @@ function background(property, compactable, validator) {
}
}
if (clipSet && !originSet)
origin.value = clip.value.slice(0);
if (clipSet && !originSet) origin.value = clip.value.slice(0);
if (!anyValueSet) {
throw new InvalidPropertyError('Invalid background value at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
throw new InvalidPropertyError(
'Invalid background value at ' +
formatPosition(values[0][2][0]) +
'. Ignoring.'
);
}
return components;
@ -238,24 +333,26 @@ function borderRadius(property, compactable) {
}
if (splitAt === 0 || splitAt === values.length - 1) {
throw new InvalidPropertyError('Invalid border-radius value at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
throw new InvalidPropertyError(
'Invalid border-radius value at ' +
formatPosition(values[0][2][0]) +
'. Ignoring.'
);
}
var target = _wrapDefault(property.name, property, compactable);
target.value = splitAt > -1 ?
values.slice(0, splitAt) :
values.slice(0);
target.value = splitAt > -1 ? values.slice(0, splitAt) : values.slice(0);
target.components = fourValues(target, compactable);
var remainder = _wrapDefault(property.name, property, compactable);
remainder.value = splitAt > -1 ?
values.slice(splitAt + 1) :
values.slice(0);
remainder.value = splitAt > -1 ? values.slice(splitAt + 1) : values.slice(0);
remainder.components = fourValues(remainder, compactable);
for (var j = 0; j < 4; j++) {
target.components[j].multiplex = true;
target.components[j].value = target.components[j].value.concat(remainder.components[j].value);
target.components[j].value = target.components[j].value.concat(
remainder.components[j].value
);
}
return target.components;
@ -285,34 +382,77 @@ function font(property, compactable, validator) {
var appendableFamilyName = false;
if (!values[index]) {
throw new InvalidPropertyError('Missing font values at ' + formatPosition(property.all[property.position][1][2][0]) + '. Ignoring.');
throw new InvalidPropertyError(
'Missing font values at ' +
formatPosition(property.all[property.position][1][2][0]) +
'. Ignoring.'
);
}
if (values.length == 1 && values[0][1] == 'inherit') {
style.value = variant.value = weight.value = stretch.value = size.value = height.value = family.value = values;
style.value =
variant.value =
weight.value =
stretch.value =
size.value =
height.value =
family.value =
values;
return components;
}
if (values.length == 1 && (validator.isFontKeyword(values[0][1]) || validator.isGlobal(values[0][1]) || validator.isPrefixed(values[0][1]))) {
if (
values.length == 1 &&
(validator.isFontKeyword(values[0][1]) ||
validator.isGlobal(values[0][1]) ||
validator.isPrefixed(values[0][1]))
) {
values[0][1] = Marker.INTERNAL + values[0][1];
style.value = variant.value = weight.value = stretch.value = size.value = height.value = family.value = values;
style.value =
variant.value =
weight.value =
stretch.value =
size.value =
height.value =
family.value =
values;
return components;
}
if (values.length < 2 || !_anyIsFontSize(values, validator) || !_anyIsFontFamily(values, validator)) {
throw new InvalidPropertyError('Invalid font values at ' + formatPosition(property.all[property.position][1][2][0]) + '. Ignoring.');
if (
values.length < 2 ||
!_anyIsFontSize(values, validator) ||
!_anyIsFontFamily(values, validator)
) {
throw new InvalidPropertyError(
'Invalid font values at ' +
formatPosition(property.all[property.position][1][2][0]) +
'. Ignoring.'
);
}
if (values.length > 1 && _anyIsInherit(values)) {
throw new InvalidPropertyError('Invalid font values at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
throw new InvalidPropertyError(
'Invalid font values at ' +
formatPosition(values[0][2][0]) +
'. Ignoring.'
);
}
// fuzzy match style, variant, weight, and stretch on first elements
while (index < fuzzyMatched) {
isStretchValid = validator.isFontStretchKeyword(values[index][1]) || validator.isGlobal(values[index][1]);
isStyleValid = validator.isFontStyleKeyword(values[index][1]) || validator.isGlobal(values[index][1]);
isVariantValid = validator.isFontVariantKeyword(values[index][1]) || validator.isGlobal(values[index][1]);
isWeightValid = validator.isFontWeightKeyword(values[index][1]) || validator.isGlobal(values[index][1]);
isStretchValid =
validator.isFontStretchKeyword(values[index][1]) ||
validator.isGlobal(values[index][1]);
isStyleValid =
validator.isFontStyleKeyword(values[index][1]) ||
validator.isGlobal(values[index][1]);
isVariantValid =
validator.isFontVariantKeyword(values[index][1]) ||
validator.isGlobal(values[index][1]);
isWeightValid =
validator.isFontWeightKeyword(values[index][1]) ||
validator.isGlobal(values[index][1]);
if (isStyleValid && !isStyleSet) {
style.value = [values[index]];
@ -326,8 +466,17 @@ function font(property, compactable, validator) {
} else if (isStretchValid && !isStretchSet) {
stretch.value = [values[index]];
isStretchSet = true;
} else if (isStyleValid && isStyleSet || isVariantValid && isVariantSet || isWeightValid && isWeightSet || isStretchValid && isStretchSet) {
throw new InvalidPropertyError('Invalid font style / variant / weight / stretch value at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
} else if (
(isStyleValid && isStyleSet) ||
(isVariantValid && isVariantSet) ||
(isWeightValid && isWeightSet) ||
(isStretchValid && isStretchSet)
) {
throw new InvalidPropertyError(
'Invalid font style / variant / weight / stretch value at ' +
formatPosition(values[0][2][0]) +
'. Ignoring.'
);
} else {
break;
}
@ -336,20 +485,38 @@ function font(property, compactable, validator) {
}
// now comes font-size ...
if (validator.isFontSizeKeyword(values[index][1]) || validator.isUnit(values[index][1]) && !validator.isDynamicUnit(values[index][1])) {
if (
validator.isFontSizeKeyword(values[index][1]) ||
(validator.isUnit(values[index][1]) &&
!validator.isDynamicUnit(values[index][1]))
) {
size.value = [values[index]];
isSizeSet = true;
index++;
} else {
throw new InvalidPropertyError('Missing font size at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
throw new InvalidPropertyError(
'Missing font size at ' + formatPosition(values[0][2][0]) + '. Ignoring.'
);
}
if (!values[index]) {
throw new InvalidPropertyError('Missing font family at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
throw new InvalidPropertyError(
'Missing font family at ' +
formatPosition(values[0][2][0]) +
'. Ignoring.'
);
}
// ... and perhaps line-height
if (isSizeSet && values[index] && values[index][1] == Marker.FORWARD_SLASH && values[index + 1] && (validator.isLineHeightKeyword(values[index + 1][1]) || validator.isUnit(values[index + 1][1]) || validator.isNumber(values[index + 1][1]))) {
if (
isSizeSet &&
values[index] &&
values[index][1] == Marker.FORWARD_SLASH &&
values[index + 1] &&
(validator.isLineHeightKeyword(values[index + 1][1]) ||
validator.isUnit(values[index + 1][1]) ||
validator.isNumber(values[index + 1][1]))
) {
height.value = [values[index + 1]];
index++;
index++;
@ -363,7 +530,8 @@ function font(property, compactable, validator) {
appendableFamilyName = false;
} else {
if (appendableFamilyName) {
family.value[family.value.length - 1][1] += Marker.SPACE + values[index][1];
family.value[family.value.length - 1][1] +=
Marker.SPACE + values[index][1];
} else {
family.value.push(values[index]);
}
@ -375,7 +543,11 @@ function font(property, compactable, validator) {
}
if (family.value.length === 0) {
throw new InvalidPropertyError('Missing font family at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
throw new InvalidPropertyError(
'Missing font family at ' +
formatPosition(values[0][2][0]) +
'. Ignoring.'
);
}
return components;
@ -388,7 +560,11 @@ function _anyIsFontSize(values, validator) {
for (i = 0, l = values.length; i < l; i++) {
value = values[i];
if (validator.isFontSizeKeyword(value[1]) || validator.isUnit(value[1]) && !validator.isDynamicUnit(value[1]) || validator.isFunction(value[1])) {
if (
validator.isFontSizeKeyword(value[1]) ||
(validator.isUnit(value[1]) && !validator.isDynamicUnit(value[1])) ||
validator.isFunction(value[1])
) {
return true;
}
}
@ -416,20 +592,16 @@ function fourValues(property, compactable) {
var components = [];
var value = property.value;
if (value.length < 1)
return [];
if (value.length < 1) return [];
if (value.length < 2)
value[1] = value[0].slice(0);
if (value.length < 3)
value[2] = value[0].slice(0);
if (value.length < 4)
value[3] = value[1].slice(0);
if (value.length < 2) value[1] = value[0].slice(0);
if (value.length < 3) value[2] = value[0].slice(0);
if (value.length < 4) value[3] = value[1].slice(0);
for (var i = componentNames.length - 1; i >= 0; i--) {
var component = wrapSingle([
Token.PROPERTY,
[Token.PROPERTY_NAME, componentNames[i]]
[Token.PROPERTY_NAME, componentNames[i]],
]);
component.value = [value[i]];
components.unshift(component);
@ -446,8 +618,7 @@ function multiplex(splitWith) {
// find split commas
for (i = 0, l = values.length; i < l; i++) {
if (values[i][1] == ',')
splitsAt.push(i);
if (values[i][1] == ',') splitsAt.push(i);
}
if (splitsAt.length === 0)
@ -474,7 +645,10 @@ function multiplex(splitWith) {
for (j = 1, m = splitComponents.length; j < m; j++) {
components[i].value.push([Token.PROPERTY_VALUE, Marker.COMMA]);
Array.prototype.push.apply(components[i].value, splitComponents[j][i].value);
Array.prototype.push.apply(
components[i].value,
splitComponents[j][i].value
);
}
}
@ -516,7 +690,11 @@ function listStyle(property, compactable, validator) {
}
// ... and what's left is a `type`
if (values.length > 0 && (validator.isListStyleTypeKeyword(values[0][1]) || validator.isIdentifier(values[0][1]))) {
if (
values.length > 0 &&
(validator.isListStyleTypeKeyword(values[0][1]) ||
validator.isIdentifier(values[0][1]))
) {
type.value = [values[0]];
}
@ -525,8 +703,16 @@ function listStyle(property, compactable, validator) {
function transition(property, compactable, validator) {
var prop = _wrapDefault(property.name + '-property', property, compactable);
var duration = _wrapDefault(property.name + '-duration', property, compactable);
var timing = _wrapDefault(property.name + '-timing-function', property, compactable);
var duration = _wrapDefault(
property.name + '-duration',
property,
compactable
);
var timing = _wrapDefault(
property.name + '-timing-function',
property,
compactable
);
var delay = _wrapDefault(property.name + '-delay', property, compactable);
var components = [prop, duration, timing, delay];
var values = property.value;
@ -544,7 +730,11 @@ function transition(property, compactable, validator) {
}
if (values.length > 1 && _anyIsInherit(values)) {
throw new InvalidPropertyError('Invalid animation values at ' + formatPosition(values[0][2][0]) + '. Ignoring.');
throw new InvalidPropertyError(
'Invalid animation values at ' +
formatPosition(values[0][2][0]) +
'. Ignoring.'
);
}
for (i = 0, l = values.length; i < l; i++) {
@ -556,14 +746,21 @@ function transition(property, compactable, validator) {
} else if (validator.isTime(value[1]) && !delaySet) {
delay.value = [value];
delaySet = true;
} else if ((validator.isGlobal(value[1]) || validator.isTimingFunction(value[1])) && !timingSet) {
} else if (
(validator.isGlobal(value[1]) || validator.isTimingFunction(value[1])) &&
!timingSet
) {
timing.value = [value];
timingSet = true;
} else if (validator.isIdentifier(value[1]) && !propSet) {
prop.value = [value];
propSet = true;
} else {
throw new InvalidPropertyError('Invalid animation value at ' + formatPosition(value[2][0]) + '. Ignoring.');
throw new InvalidPropertyError(
'Invalid animation value at ' +
formatPosition(value[2][0]) +
'. Ignoring.'
);
}
}
@ -575,23 +772,25 @@ function widthStyleColor(property, compactable, validator) {
var components = [
_wrapDefault(descriptor.components[0], property, compactable),
_wrapDefault(descriptor.components[1], property, compactable),
_wrapDefault(descriptor.components[2], property, compactable)
_wrapDefault(descriptor.components[2], property, compactable),
];
var color, style, width;
for (var i = 0; i < 3; i++) {
var component = components[i];
if (component.name.indexOf('color') > 0)
color = component;
else if (component.name.indexOf('style') > 0)
style = component;
else
width = component;
if (component.name.indexOf('color') > 0) color = component;
else if (component.name.indexOf('style') > 0) style = component;
else width = component;
}
if ((property.value.length == 1 && property.value[0][1] == 'inherit') ||
(property.value.length == 3 && property.value[0][1] == 'inherit' && property.value[1][1] == 'inherit' && property.value[2][1] == 'inherit')) {
if (
(property.value.length == 1 && property.value[0][1] == 'inherit') ||
(property.value.length == 3 &&
property.value[0][1] == 'inherit' &&
property.value[1][1] == 'inherit' &&
property.value[2][1] == 'inherit')
) {
color.value = style.value = width.value = [property.value[0]];
return components;
}
@ -604,7 +803,13 @@ function widthStyleColor(property, compactable, validator) {
if (values.length > 0) {
matches = values.filter(_widthFilter(validator));
match = matches.length > 1 && (matches[0][1] == 'none' || matches[0][1] == 'auto') ? matches[1] : matches[0];
match =
(
matches.length > 1 &&
(matches[0][1] == 'none' || matches[0][1] == 'auto')
) ?
matches[1]
: matches[0];
if (match) {
width.value = [match];
values.splice(values.indexOf(match), 1);
@ -640,5 +845,5 @@ module.exports = {
listStyle: listStyle,
multiplex: multiplex,
outline: widthStyleColor,
transition: transition
transition: transition,
};

View File

@ -1,23 +1,39 @@
var understandable = require('./properties/understandable');
function animationIterationCount(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isAnimationIterationCountKeyword(value2) || validator.isPositiveNumber(value2))) {
if (
!understandable(validator, value1, value2, 0, true) &&
!(
validator.isAnimationIterationCountKeyword(value2) ||
validator.isPositiveNumber(value2)
)
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
}
return validator.isAnimationIterationCountKeyword(value2) || validator.isPositiveNumber(value2);
return (
validator.isAnimationIterationCountKeyword(value2) ||
validator.isPositiveNumber(value2)
);
}
function animationName(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isAnimationNameKeyword(value2) || validator.isIdentifier(value2))) {
if (
!understandable(validator, value1, value2, 0, true) &&
!(
validator.isAnimationNameKeyword(value2) || validator.isIdentifier(value2)
)
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
}
return validator.isAnimationNameKeyword(value2) || validator.isIdentifier(value2);
return (
validator.isAnimationNameKeyword(value2) || validator.isIdentifier(value2)
);
}
function areSameFunction(validator, value1, value2) {
@ -32,11 +48,20 @@ function areSameFunction(validator, value1, value2) {
}
function backgroundPosition(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isBackgroundPositionKeyword(value2) || validator.isGlobal(value2))) {
if (
!understandable(validator, value1, value2, 0, true) &&
!(
validator.isBackgroundPositionKeyword(value2) ||
validator.isGlobal(value2)
)
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
} else if (validator.isBackgroundPositionKeyword(value2) || validator.isGlobal(value2)) {
} else if (
validator.isBackgroundPositionKeyword(value2) ||
validator.isGlobal(value2)
) {
return true;
}
@ -44,11 +69,17 @@ function backgroundPosition(validator, value1, value2) {
}
function backgroundSize(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isBackgroundSizeKeyword(value2) || validator.isGlobal(value2))) {
if (
!understandable(validator, value1, value2, 0, true) &&
!(validator.isBackgroundSizeKeyword(value2) || validator.isGlobal(value2))
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
} else if (validator.isBackgroundSizeKeyword(value2) || validator.isGlobal(value2)) {
} else if (
validator.isBackgroundSizeKeyword(value2) ||
validator.isGlobal(value2)
) {
return true;
}
@ -56,13 +87,22 @@ function backgroundSize(validator, value1, value2) {
}
function color(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !validator.isColor(value2)) {
if (
!understandable(validator, value1, value2, 0, true) &&
!validator.isColor(value2)
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
} else if (!validator.colorOpacity && (validator.isRgbColor(value1) || validator.isHslColor(value1))) {
} else if (
!validator.colorOpacity &&
(validator.isRgbColor(value1) || validator.isHslColor(value1))
) {
return false;
} else if (!validator.colorOpacity && (validator.isRgbColor(value2) || validator.isHslColor(value2))) {
} else if (
!validator.colorOpacity &&
(validator.isRgbColor(value2) || validator.isHslColor(value2))
) {
return false;
} else if (validator.isColor(value1) && validator.isColor(value2)) {
return true;
@ -82,7 +122,10 @@ function fontFamily(validator, value1, value2) {
}
function image(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !validator.isImage(value2)) {
if (
!understandable(validator, value1, value2, 0, true) &&
!validator.isImage(value2)
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
@ -96,8 +139,11 @@ function image(validator, value1, value2) {
}
function keyword(propertyName) {
return function(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !validator.isKeyword(propertyName)(value2)) {
return function (validator, value1, value2) {
if (
!understandable(validator, value1, value2, 0, true) &&
!validator.isKeyword(propertyName)(value2)
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
@ -108,19 +154,27 @@ function keyword(propertyName) {
}
function keywordWithGlobal(propertyName) {
return function(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isKeyword(propertyName)(value2) || validator.isGlobal(value2))) {
return function (validator, value1, value2) {
if (
!understandable(validator, value1, value2, 0, true) &&
!(validator.isKeyword(propertyName)(value2) || validator.isGlobal(value2))
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
}
return validator.isKeyword(propertyName)(value2) || validator.isGlobal(value2);
return (
validator.isKeyword(propertyName)(value2) || validator.isGlobal(value2)
);
};
}
function propertyName(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !validator.isIdentifier(value2)) {
if (
!understandable(validator, value1, value2, 0, true) &&
!validator.isIdentifier(value2)
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
@ -130,23 +184,35 @@ function propertyName(validator, value1, value2) {
}
function sameFunctionOrValue(validator, value1, value2) {
return areSameFunction(validator, value1, value2) ?
true :
value1 === value2;
return areSameFunction(validator, value1, value2) ? true : value1 === value2;
}
function textShadow(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isUnit(value2) || validator.isColor(value2) || validator.isGlobal(value2))) {
if (
!understandable(validator, value1, value2, 0, true) &&
!(
validator.isUnit(value2) ||
validator.isColor(value2) ||
validator.isGlobal(value2)
)
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
}
return validator.isUnit(value2) || validator.isColor(value2) || validator.isGlobal(value2);
return (
validator.isUnit(value2) ||
validator.isColor(value2) ||
validator.isGlobal(value2)
);
}
function time(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !validator.isTime(value2)) {
if (
!understandable(validator, value1, value2, 0, true) &&
!validator.isTime(value2)
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
@ -156,7 +222,12 @@ function time(validator, value1, value2) {
return true;
} else if (validator.isTime(value1)) {
return false;
} else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) {
} else if (
validator.isFunction(value1) &&
!validator.isPrefixed(value1) &&
validator.isFunction(value2) &&
!validator.isPrefixed(value2)
) {
return true;
}
@ -164,7 +235,10 @@ function time(validator, value1, value2) {
}
function timingFunction(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isTimingFunction(value2) || validator.isGlobal(value2))) {
if (
!understandable(validator, value1, value2, 0, true) &&
!(validator.isTimingFunction(value2) || validator.isGlobal(value2))
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
@ -174,7 +248,10 @@ function timingFunction(validator, value1, value2) {
}
function unit(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !validator.isUnit(value2)) {
if (
!understandable(validator, value1, value2, 0, true) &&
!validator.isUnit(value2)
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
@ -184,7 +261,12 @@ function unit(validator, value1, value2) {
return true;
} else if (validator.isUnit(value1)) {
return false;
} else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) {
} else if (
validator.isFunction(value1) &&
!validator.isPrefixed(value1) &&
validator.isFunction(value2) &&
!validator.isPrefixed(value2)
) {
return true;
}
@ -194,23 +276,36 @@ function unit(validator, value1, value2) {
function unitOrKeywordWithGlobal(propertyName) {
var byKeyword = keywordWithGlobal(propertyName);
return function(validator, value1, value2) {
return unit(validator, value1, value2) || byKeyword(validator, value1, value2);
return function (validator, value1, value2) {
return (
unit(validator, value1, value2) || byKeyword(validator, value1, value2)
);
};
}
function unitOrNumber(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !(validator.isUnit(value2) || validator.isNumber(value2))) {
if (
!understandable(validator, value1, value2, 0, true) &&
!(validator.isUnit(value2) || validator.isNumber(value2))
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
} else if ((validator.isUnit(value1) || validator.isNumber(value1)) && !(validator.isUnit(value2) || validator.isNumber(value2))) {
} else if (
(validator.isUnit(value1) || validator.isNumber(value1)) &&
!(validator.isUnit(value2) || validator.isNumber(value2))
) {
return false;
} else if (validator.isUnit(value2) || validator.isNumber(value2)) {
return true;
} else if (validator.isUnit(value1) || validator.isNumber(value1)) {
return false;
} else if (validator.isFunction(value1) && !validator.isPrefixed(value1) && validator.isFunction(value2) && !validator.isPrefixed(value2)) {
} else if (
validator.isFunction(value1) &&
!validator.isPrefixed(value1) &&
validator.isFunction(value2) &&
!validator.isPrefixed(value2)
) {
return true;
}
@ -218,7 +313,10 @@ function unitOrNumber(validator, value1, value2) {
}
function zIndex(validator, value1, value2) {
if (!understandable(validator, value1, value2, 0, true) && !validator.isZIndex(value2)) {
if (
!understandable(validator, value1, value2, 0, true) &&
!validator.isZIndex(value2)
) {
return false;
} else if (validator.isVariable(value1) && validator.isVariable(value2)) {
return true;
@ -236,7 +334,7 @@ module.exports = {
time: time,
timingFunction: timingFunction,
unit: unit,
unitOrNumber: unitOrNumber
unitOrNumber: unitOrNumber,
},
property: {
animationDirection: keywordWithGlobal('animation-direction'),
@ -278,6 +376,6 @@ module.exports = {
verticalAlign: unitOrKeywordWithGlobal('vertical-align'),
visibility: keywordWithGlobal('visibility'),
whiteSpace: keywordWithGlobal('white-space'),
zIndex: zIndex
}
zIndex: zIndex,
},
};

View File

@ -19,7 +19,7 @@ function deep(property) {
function shallow(property) {
var cloned = wrapSingle([
Token.PROPERTY,
[Token.PROPERTY_NAME, property.name]
[Token.PROPERTY_NAME, property.name],
]);
cloned.important = property.important;
cloned.hack = property.hack;
@ -29,5 +29,5 @@ function shallow(property) {
module.exports = {
deep: deep,
shallow: shallow
shallow: shallow,
};

File diff suppressed because it is too large Load Diff

View File

@ -20,15 +20,12 @@ function extractProperties(token) {
for (i = 0, l = token[2].length; i < l; i++) {
property = token[2][i];
if (property[0] != Token.PROPERTY)
continue;
if (property[0] != Token.PROPERTY) continue;
name = property[1][1];
if (name.length === 0)
continue;
if (name.length === 0) continue;
if (name.indexOf('--') === 0)
continue;
if (name.indexOf('--') === 0) continue;
value = serializeValue(property, i);
@ -39,7 +36,7 @@ function extractProperties(token) {
token[2][i],
name + ':' + value,
token[1],
inSpecificSelector
inSpecificSelector,
]);
}
} else if (token[0] == Token.NESTED_BLOCK) {
@ -52,22 +49,25 @@ function extractProperties(token) {
}
function findNameRoot(name) {
if (name == 'list-style')
return name;
if (name.indexOf('-radius') > 0)
return 'border-radius';
if (name == 'border-collapse' || name == 'border-spacing' || name == 'border-image')
if (name == 'list-style') return name;
if (name.indexOf('-radius') > 0) return 'border-radius';
if (
name == 'border-collapse' ||
name == 'border-spacing' ||
name == 'border-image'
)
return name;
if (name.indexOf('border-') === 0 && /^border\-\w+\-\w+$/.test(name))
return name.match(/border\-\w+/)[0];
if (name.indexOf('border-') === 0 && /^border\-\w+$/.test(name))
return 'border';
if (name.indexOf('text-') === 0)
return name;
if (name == '-chrome-')
return name;
if (name.indexOf('text-') === 0) return name;
if (name == '-chrome-') return name;
return name.replace(/^\-\w+\-/, '').match(/([a-zA-Z]+)/)[0].toLowerCase();
return name
.replace(/^\-\w+\-/, '')
.match(/([a-zA-Z]+)/)[0]
.toLowerCase();
}
module.exports = extractProperties;

View File

@ -1,7 +1,7 @@
function InvalidPropertyError(message) {
this.name = 'InvalidPropertyError';
this.message = message;
this.stack = (new Error()).stack;
this.stack = new Error().stack;
}
InvalidPropertyError.prototype = Object.create(Error.prototype);

View File

@ -11,7 +11,7 @@ var PSEUDO_CLASSES_WITH_ARGUMENTS = [
':nth-child',
':nth-last-child',
':nth-last-of-type',
':nth-of-type'
':nth-of-type',
];
var RELATION_PATTERN = /[>\+~]/;
var UNMIXABLE_PSEUDO_CLASSES = [
@ -19,22 +19,27 @@ var UNMIXABLE_PSEUDO_CLASSES = [
':before',
':first-letter',
':first-line',
':lang'
':lang',
];
var UNMIXABLE_PSEUDO_ELEMENTS = [
'::after',
'::before',
'::first-letter',
'::first-line'
'::first-line',
];
var Level = {
DOUBLE_QUOTE: 'double-quote',
SINGLE_QUOTE: 'single-quote',
ROOT: 'root'
ROOT: 'root',
};
function isMergeable(selector, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) {
function isMergeable(
selector,
mergeablePseudoClasses,
mergeablePseudoElements,
multiplePseudoMerging
) {
var singleSelectors = split(selector, Marker.COMMA);
var singleSelector;
var i, l;
@ -42,9 +47,18 @@ function isMergeable(selector, mergeablePseudoClasses, mergeablePseudoElements,
for (i = 0, l = singleSelectors.length; i < l; i++) {
singleSelector = singleSelectors[i];
if (singleSelector.length === 0 ||
isDeepSelector(singleSelector) ||
(singleSelector.indexOf(Marker.COLON) > -1 && !areMergeable(singleSelector, extractPseudoFrom(singleSelector), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging))) {
if (
singleSelector.length === 0 ||
isDeepSelector(singleSelector) ||
(singleSelector.indexOf(Marker.COLON) > -1 &&
!areMergeable(
singleSelector,
extractPseudoFrom(singleSelector),
mergeablePseudoClasses,
mergeablePseudoElements,
multiplePseudoMerging
))
) {
return false;
}
}
@ -81,13 +95,19 @@ function extractPseudoFrom(selector) {
} else if (character == Marker.DOUBLE_QUOTE && level == Level.ROOT) {
buffer.push(character);
level = Level.DOUBLE_QUOTE;
} else if (character == Marker.DOUBLE_QUOTE && level == Level.DOUBLE_QUOTE) {
} else if (
character == Marker.DOUBLE_QUOTE &&
level == Level.DOUBLE_QUOTE
) {
buffer.push(character);
level = Level.ROOT;
} else if (character == Marker.SINGLE_QUOTE && level == Level.ROOT) {
buffer.push(character);
level = Level.SINGLE_QUOTE;
} else if (character == Marker.SINGLE_QUOTE && level == Level.SINGLE_QUOTE) {
} else if (
character == Marker.SINGLE_QUOTE &&
level == Level.SINGLE_QUOTE
) {
buffer.push(character);
level = Level.ROOT;
} else if (isQuoted) {
@ -95,7 +115,11 @@ function extractPseudoFrom(selector) {
} else if (character == Marker.OPEN_ROUND_BRACKET) {
buffer.push(character);
roundBracketLevel++;
} else if (character == Marker.CLOSE_ROUND_BRACKET && roundBracketLevel == 1 && isPseudo) {
} else if (
character == Marker.CLOSE_ROUND_BRACKET &&
roundBracketLevel == 1 &&
isPseudo
) {
buffer.push(character);
list.push(buffer.join(''));
roundBracketLevel--;
@ -104,15 +128,28 @@ function extractPseudoFrom(selector) {
} else if (character == Marker.CLOSE_ROUND_BRACKET) {
buffer.push(character);
roundBracketLevel--;
} else if (character == Marker.COLON && roundBracketLevel === 0 && isPseudo && !wasColon) {
} else if (
character == Marker.COLON &&
roundBracketLevel === 0 &&
isPseudo &&
!wasColon
) {
list.push(buffer.join(''));
buffer = [];
buffer.push(character);
} else if (character == Marker.COLON && roundBracketLevel === 0 && !wasColon) {
} else if (
character == Marker.COLON &&
roundBracketLevel === 0 &&
!wasColon
) {
buffer = [];
buffer.push(character);
isPseudo = true;
} else if (character == Marker.SPACE && roundBracketLevel === 0 && isPseudo) {
} else if (
character == Marker.SPACE &&
roundBracketLevel === 0 &&
isPseudo
) {
list.push(buffer.join(''));
buffer = [];
isPseudo = false;
@ -135,11 +172,19 @@ function extractPseudoFrom(selector) {
return list;
}
function areMergeable(selector, matches, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) {
return areAllowed(matches, mergeablePseudoClasses, mergeablePseudoElements) &&
function areMergeable(
selector,
matches,
mergeablePseudoClasses,
mergeablePseudoElements,
multiplePseudoMerging
) {
return (
areAllowed(matches, mergeablePseudoClasses, mergeablePseudoElements) &&
needArguments(matches) &&
(matches.length < 2 || !someIncorrectlyChained(selector, matches)) &&
(matches.length < 2 || multiplePseudoMerging && allMixable(matches));
(matches.length < 2 || (multiplePseudoMerging && allMixable(matches)))
);
}
function areAllowed(matches, mergeablePseudoClasses, mergeablePseudoElements) {
@ -149,11 +194,15 @@ function areAllowed(matches, mergeablePseudoClasses, mergeablePseudoElements) {
for (i = 0, l = matches.length; i < l; i++) {
match = matches[i];
name = match.indexOf(Marker.OPEN_ROUND_BRACKET) > -1 ?
match.substring(0, match.indexOf(Marker.OPEN_ROUND_BRACKET)) :
match;
name =
match.indexOf(Marker.OPEN_ROUND_BRACKET) > -1 ?
match.substring(0, match.indexOf(Marker.OPEN_ROUND_BRACKET))
: match;
if (mergeablePseudoClasses.indexOf(name) === -1 && mergeablePseudoElements.indexOf(name) === -1) {
if (
mergeablePseudoClasses.indexOf(name) === -1 &&
mergeablePseudoElements.indexOf(name) === -1
) {
return false;
}
}
@ -173,9 +222,7 @@ function needArguments(matches) {
bracketOpensAt = match.indexOf(Marker.OPEN_ROUND_BRACKET);
hasArguments = bracketOpensAt > -1;
name = hasArguments ?
match.substring(0, bracketOpensAt) :
match;
name = hasArguments ? match.substring(0, bracketOpensAt) : match;
if (hasArguments && PSEUDO_CLASSES_WITH_ARGUMENTS.indexOf(name) == -1) {
return false;
@ -214,12 +261,14 @@ function someIncorrectlyChained(selector, matches) {
areChained = matchAt + match.length == nextMatchAt;
if (areChained) {
name = match.indexOf(Marker.OPEN_ROUND_BRACKET) > -1 ?
match.substring(0, match.indexOf(Marker.OPEN_ROUND_BRACKET)) :
match;
nextName = nextMatch.indexOf(Marker.OPEN_ROUND_BRACKET) > -1 ?
nextMatch.substring(0, nextMatch.indexOf(Marker.OPEN_ROUND_BRACKET)) :
nextMatch;
name =
match.indexOf(Marker.OPEN_ROUND_BRACKET) > -1 ?
match.substring(0, match.indexOf(Marker.OPEN_ROUND_BRACKET))
: match;
nextName =
nextMatch.indexOf(Marker.OPEN_ROUND_BRACKET) > -1 ?
nextMatch.substring(0, nextMatch.indexOf(Marker.OPEN_ROUND_BRACKET))
: nextMatch;
if (name != NOT_PSEUDO || nextName != NOT_PSEUDO) {
return true;

View File

@ -5,7 +5,8 @@ var optimizeProperties = require('./properties/optimize');
var sortSelectors = require('../level-1/sort-selectors');
var tidyRules = require('../level-1/tidy-rules');
var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel;
var OptimizationLevel =
require('../../options/optimization-level').OptimizationLevel;
var serializeBody = require('../../writer/one-time').body;
var serializeRules = require('../../writer/one-time').rules;
@ -16,11 +17,15 @@ function mergeAdjacent(tokens, context) {
var lastToken = [null, [], []];
var options = context.options;
var adjacentSpace = options.compatibility.selectors.adjacentSpace;
var selectorsSortingMethod = options.level[OptimizationLevel.One].selectorsSortingMethod;
var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses;
var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements;
var selectorsSortingMethod =
options.level[OptimizationLevel.One].selectorsSortingMethod;
var mergeablePseudoClasses =
options.compatibility.selectors.mergeablePseudoClasses;
var mergeablePseudoElements =
options.compatibility.selectors.mergeablePseudoElements;
var mergeLimit = options.compatibility.selectors.mergeLimit;
var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging;
var multiplePseudoMerging =
options.compatibility.selectors.multiplePseudoMerging;
for (var i = 0, l = tokens.length; i < l; i++) {
var token = tokens[i];
@ -30,16 +35,41 @@ function mergeAdjacent(tokens, context) {
continue;
}
if (lastToken[0] == Token.RULE && serializeRules(token[1]) == serializeRules(lastToken[1])) {
if (
lastToken[0] == Token.RULE &&
serializeRules(token[1]) == serializeRules(lastToken[1])
) {
Array.prototype.push.apply(lastToken[2], token[2]);
optimizeProperties(lastToken[2], true, true, context);
token[2] = [];
} else if (lastToken[0] == Token.RULE && serializeBody(token[2]) == serializeBody(lastToken[2]) &&
isMergeable(serializeRules(token[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) &&
isMergeable(serializeRules(lastToken[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) &&
lastToken[1].length < mergeLimit) {
lastToken[1] = tidyRules(lastToken[1].concat(token[1]), false, adjacentSpace, false, context.warnings);
lastToken[1] = lastToken.length > 1 ? sortSelectors(lastToken[1], selectorsSortingMethod) : lastToken[1];
} else if (
lastToken[0] == Token.RULE &&
serializeBody(token[2]) == serializeBody(lastToken[2]) &&
isMergeable(
serializeRules(token[1]),
mergeablePseudoClasses,
mergeablePseudoElements,
multiplePseudoMerging
) &&
isMergeable(
serializeRules(lastToken[1]),
mergeablePseudoClasses,
mergeablePseudoElements,
multiplePseudoMerging
) &&
lastToken[1].length < mergeLimit
) {
lastToken[1] = tidyRules(
lastToken[1].concat(token[1]),
false,
adjacentSpace,
false,
context.warnings
);
lastToken[1] =
lastToken.length > 1 ?
sortSelectors(lastToken[1], selectorsSortingMethod)
: lastToken[1];
token[2] = [];
} else {
lastToken = token;

View File

@ -4,11 +4,13 @@ var extractProperties = require('./extract-properties');
var rulesOverlap = require('./rules-overlap');
var serializeRules = require('../../writer/one-time').rules;
var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel;
var OptimizationLevel =
require('../../options/optimization-level').OptimizationLevel;
var Token = require('../../tokenizer/token');
function mergeMediaQueries(tokens, context) {
var mergeSemantically = context.options.level[OptimizationLevel.Two].mergeSemantically;
var mergeSemantically =
context.options.level[OptimizationLevel.Two].mergeSemantically;
var specificityCache = context.cache.specificity;
var candidates = {};
var reduced = [];
@ -32,15 +34,13 @@ function mergeMediaQueries(tokens, context) {
for (var name in candidates) {
var positions = candidates[name];
positionLoop:
for (var j = positions.length - 1; j > 0; j--) {
positionLoop: for (var j = positions.length - 1; j > 0; j--) {
var positionOne = positions[j];
var tokenOne = tokens[positionOne];
var positionTwo = positions[j - 1];
var tokenTwo = tokens[positionTwo];
directionLoop:
for (var direction = 1; direction >= -1; direction -= 2) {
directionLoop: for (var direction = 1; direction >= -1; direction -= 2) {
var topToBottom = direction == 1;
var from = topToBottom ? positionOne + 1 : positionTwo - 1;
var to = topToBottom ? positionTwo : positionOne;
@ -53,17 +53,27 @@ function mergeMediaQueries(tokens, context) {
var traversedProperties = extractProperties(tokens[from]);
from += delta;
if (mergeSemantically && allSameRulePropertiesCanBeReordered(movedProperties, traversedProperties, specificityCache)) {
if (
mergeSemantically &&
allSameRulePropertiesCanBeReordered(
movedProperties,
traversedProperties,
specificityCache
)
) {
continue;
}
if (!canReorder(movedProperties, traversedProperties, specificityCache))
if (
!canReorder(movedProperties, traversedProperties, specificityCache)
)
continue directionLoop;
}
target[2] = topToBottom ?
source[2].concat(target[2]) :
target[2].concat(source[2]);
target[2] =
topToBottom ?
source[2].concat(target[2])
: target[2].concat(source[2]);
source[2] = [];
reduced.push(target);
@ -75,7 +85,11 @@ function mergeMediaQueries(tokens, context) {
return reduced;
}
function allSameRulePropertiesCanBeReordered(movedProperties, traversedProperties, specificityCache) {
function allSameRulePropertiesCanBeReordered(
movedProperties,
traversedProperties,
specificityCache
) {
var movedProperty;
var movedRule;
var traversedProperty;
@ -91,7 +105,10 @@ function allSameRulePropertiesCanBeReordered(movedProperties, traversedPropertie
traversedProperty = traversedProperties[j];
traversedRule = traversedProperty[5];
if (rulesOverlap(movedRule, traversedRule, true) && !canReorderSingle(movedProperty, traversedProperty, specificityCache)) {
if (
rulesOverlap(movedRule, traversedRule, true) &&
!canReorderSingle(movedProperty, traversedProperty, specificityCache)
) {
return false;
}
}

View File

@ -3,7 +3,8 @@ var isMergeable = require('./is-mergeable');
var sortSelectors = require('../level-1/sort-selectors');
var tidyRules = require('../level-1/tidy-rules');
var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel;
var OptimizationLevel =
require('../../options/optimization-level').OptimizationLevel;
var serializeBody = require('../../writer/one-time').body;
var serializeRules = require('../../writer/one-time').rules;
@ -30,27 +31,38 @@ function removeAnyUnsafeElements(left, candidates) {
var right = candidates[body];
var rightSelector = withoutModifier(serializeRules(right[1]));
if (rightSelector.indexOf(leftSelector) > -1 || leftSelector.indexOf(rightSelector) > -1)
if (
rightSelector.indexOf(leftSelector) > -1 ||
leftSelector.indexOf(rightSelector) > -1
)
delete candidates[body];
}
}
function mergeNonAdjacentByBody(tokens, context) {
var options = context.options;
var mergeSemantically = options.level[OptimizationLevel.Two].mergeSemantically;
var mergeSemantically =
options.level[OptimizationLevel.Two].mergeSemantically;
var adjacentSpace = options.compatibility.selectors.adjacentSpace;
var selectorsSortingMethod = options.level[OptimizationLevel.One].selectorsSortingMethod;
var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses;
var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements;
var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging;
var selectorsSortingMethod =
options.level[OptimizationLevel.One].selectorsSortingMethod;
var mergeablePseudoClasses =
options.compatibility.selectors.mergeablePseudoClasses;
var mergeablePseudoElements =
options.compatibility.selectors.mergeablePseudoElements;
var multiplePseudoMerging =
options.compatibility.selectors.multiplePseudoMerging;
var candidates = {};
for (var i = tokens.length - 1; i >= 0; i--) {
var token = tokens[i];
if (token[0] != Token.RULE)
continue;
if (token[0] != Token.RULE) continue;
if (token[2].length > 0 && (!mergeSemantically && unsafeSelector(serializeRules(token[1]))))
if (
token[2].length > 0 &&
!mergeSemantically &&
unsafeSelector(serializeRules(token[1]))
)
candidates = {};
if (token[2].length > 0 && mergeSemantically && isBemElement(token))
@ -58,13 +70,33 @@ function mergeNonAdjacentByBody(tokens, context) {
var candidateBody = serializeBody(token[2]);
var oldToken = candidates[candidateBody];
if (oldToken &&
isMergeable(serializeRules(token[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) &&
isMergeable(serializeRules(oldToken[1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging)) {
if (
oldToken &&
isMergeable(
serializeRules(token[1]),
mergeablePseudoClasses,
mergeablePseudoElements,
multiplePseudoMerging
) &&
isMergeable(
serializeRules(oldToken[1]),
mergeablePseudoClasses,
mergeablePseudoElements,
multiplePseudoMerging
)
) {
if (token[2].length > 0) {
token[1] = tidyRules(oldToken[1].concat(token[1]), false, adjacentSpace, false, context.warnings);
token[1] = token[1].length > 1 ? sortSelectors(token[1], selectorsSortingMethod) : token[1];
token[1] = tidyRules(
oldToken[1].concat(token[1]),
false,
adjacentSpace,
false,
context.warnings
);
token[1] =
token[1].length > 1 ?
sortSelectors(token[1], selectorsSortingMethod)
: token[1];
} else {
token[1] = oldToken[1].concat(token[1]);
}

View File

@ -14,30 +14,29 @@ function mergeNonAdjacentBySelector(tokens, context) {
var i;
for (i = tokens.length - 1; i >= 0; i--) {
if (tokens[i][0] != Token.RULE)
continue;
if (tokens[i][2].length === 0)
continue;
if (tokens[i][0] != Token.RULE) continue;
if (tokens[i][2].length === 0) continue;
var selector = serializeRules(tokens[i][1]);
allSelectors[selector] = [i].concat(allSelectors[selector] || []);
if (allSelectors[selector].length == 2)
repeatedSelectors.push(selector);
if (allSelectors[selector].length == 2) repeatedSelectors.push(selector);
}
for (i = repeatedSelectors.length - 1; i >= 0; i--) {
var positions = allSelectors[repeatedSelectors[i]];
selectorIterator:
for (var j = positions.length - 1; j > 0; j--) {
selectorIterator: for (var j = positions.length - 1; j > 0; j--) {
var positionOne = positions[j - 1];
var tokenOne = tokens[positionOne];
var positionTwo = positions[j];
var tokenTwo = tokens[positionTwo];
directionIterator:
for (var direction = 1; direction >= -1; direction -= 2) {
directionIterator: for (
var direction = 1;
direction >= -1;
direction -= 2
) {
var topToBottom = direction == 1;
var from = topToBottom ? positionOne + 1 : positionTwo - 1;
var to = topToBottom ? positionTwo : positionOne;
@ -51,14 +50,17 @@ function mergeNonAdjacentBySelector(tokens, context) {
from += delta;
// traversed then moved as we move selectors towards the start
var reorderable = topToBottom ?
canReorder(movedProperties, traversedProperties, specificityCache) :
canReorder(traversedProperties, movedProperties, specificityCache);
var reorderable =
topToBottom ?
canReorder(movedProperties, traversedProperties, specificityCache)
: canReorder(
traversedProperties,
movedProperties,
specificityCache
);
if (!reorderable && !topToBottom)
continue selectorIterator;
if (!reorderable && topToBottom)
continue directionIterator;
if (!reorderable && !topToBottom) continue selectorIterator;
if (!reorderable && topToBottom) continue directionIterator;
}
if (topToBottom) {

View File

@ -11,7 +11,8 @@ var restructure = require('./restructure');
var optimizeProperties = require('./properties/optimize');
var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel;
var OptimizationLevel =
require('../../options/optimization-level').OptimizationLevel;
var Token = require('../../tokenizer/token');
@ -88,20 +89,34 @@ function level2Optimize(tokens, context, withRestructuring) {
reduceNonAdjacent(tokens, context);
}
if (levelOptions.mergeNonAdjacentRules && levelOptions.mergeNonAdjacentRules != 'body') {
if (
levelOptions.mergeNonAdjacentRules &&
levelOptions.mergeNonAdjacentRules != 'body'
) {
mergeNonAdjacentBySelector(tokens, context);
}
if (levelOptions.mergeNonAdjacentRules && levelOptions.mergeNonAdjacentRules != 'selector') {
if (
levelOptions.mergeNonAdjacentRules &&
levelOptions.mergeNonAdjacentRules != 'selector'
) {
mergeNonAdjacentByBody(tokens, context);
}
if (levelOptions.restructureRules && levelOptions.mergeAdjacentRules && withRestructuring) {
if (
levelOptions.restructureRules &&
levelOptions.mergeAdjacentRules &&
withRestructuring
) {
restructure(tokens, context);
mergeAdjacent(tokens, context);
}
if (levelOptions.restructureRules && !levelOptions.mergeAdjacentRules && withRestructuring) {
if (
levelOptions.restructureRules &&
!levelOptions.mergeAdjacentRules &&
withRestructuring
) {
restructure(tokens, context);
}

View File

@ -10,8 +10,9 @@ function everyValuesPair(fn, left, right) {
var position;
for (position = 0; position < total; position++) {
leftValue = left.value[position] && left.value[position][1] || leftValue;
rightValue = right.value[position] && right.value[position][1] || rightValue;
leftValue = (left.value[position] && left.value[position][1]) || leftValue;
rightValue =
(right.value[position] && right.value[position][1]) || rightValue;
if (leftValue == Marker.COMMA || rightValue == Marker.COMMA) {
continue;

View File

@ -3,7 +3,10 @@ var compactable = require('../compactable');
function findComponentIn(shorthand, longhand) {
var comparator = nameComparator(longhand);
return findInDirectComponents(shorthand, comparator) || findInSubComponents(shorthand, comparator);
return (
findInDirectComponents(shorthand, comparator) ||
findInSubComponents(shorthand, comparator)
);
}
function nameComparator(to) {

View File

@ -1,7 +1,6 @@
function hasInherit(property) {
for (var i = property.value.length - 1; i >= 0; i--) {
if (property.value[i][1] == 'inherit')
return true;
if (property.value[i][1] == 'inherit') return true;
}
return false;

View File

@ -1,22 +1,27 @@
var compactable = require('../compactable');
function isComponentOf(property1, property2, shallow) {
return isDirectComponentOf(property1, property2) ||
!shallow && !!compactable[property1.name].shorthandComponents && isSubComponentOf(property1, property2);
return (
isDirectComponentOf(property1, property2) ||
(!shallow &&
!!compactable[property1.name].shorthandComponents &&
isSubComponentOf(property1, property2))
);
}
function isDirectComponentOf(property1, property2) {
var descriptor = compactable[property1.name];
return 'components' in descriptor && descriptor.components.indexOf(property2.name) > -1;
return (
'components' in descriptor &&
descriptor.components.indexOf(property2.name) > -1
);
}
function isSubComponentOf(property1, property2) {
return property1
.components
.some(function (component) {
return isDirectComponentOf(component, property2);
});
return property1.components.some(function (component) {
return isDirectComponentOf(component, property2);
});
}
module.exports = isComponentOf;

View File

@ -69,12 +69,18 @@ function invalidateOrCompact(properties, position, candidates, validator) {
shorthandDescriptor = compactable[shorthandName];
candidateComponents = candidates[shorthandName];
if (invalidatedBy && invalidates(candidates, shorthandName, invalidatedBy)) {
if (
invalidatedBy &&
invalidates(candidates, shorthandName, invalidatedBy)
) {
delete candidates[shorthandName];
continue;
}
if (shorthandDescriptor.components.length > Object.keys(candidateComponents).length) {
if (
shorthandDescriptor.components.length >
Object.keys(candidateComponents).length
) {
continue;
}
@ -91,9 +97,19 @@ function invalidateOrCompact(properties, position, candidates, validator) {
}
if (mixedInherit(candidateComponents)) {
replaceWithInheritBestFit(properties, candidateComponents, shorthandName, validator);
replaceWithInheritBestFit(
properties,
candidateComponents,
shorthandName,
validator
);
} else {
replaceWithShorthand(properties, candidateComponents, shorthandName, validator);
replaceWithShorthand(
properties,
candidateComponents,
shorthandName,
validator
);
}
}
}
@ -103,7 +119,10 @@ function invalidates(candidates, shorthandName, invalidatedBy) {
var invalidatedByDescriptor = compactable[invalidatedBy.name];
var componentName;
if ('overridesShorthands' in shorthandDescriptor && shorthandDescriptor.overridesShorthands.indexOf(invalidatedBy.name) > -1) {
if (
'overridesShorthands' in shorthandDescriptor &&
shorthandDescriptor.overridesShorthands.indexOf(invalidatedBy.name) > -1
) {
return true;
}
@ -123,7 +142,10 @@ function mixedImportance(components) {
var componentName;
for (componentName in components) {
if (undefined !== important && components[componentName].important != important) {
if (
undefined !== important &&
components[componentName].important != important
) {
return true;
}
@ -138,7 +160,7 @@ function overridable(components, shorthandName, validator) {
var newValuePlaceholder = [
Token.PROPERTY,
[Token.PROPERTY_NAME, shorthandName],
[Token.PROPERTY_VALUE, descriptor.defaultValue]
[Token.PROPERTY_VALUE, descriptor.defaultValue],
];
var newProperty = wrapSingle(newValuePlaceholder);
var component;
@ -151,7 +173,13 @@ function overridable(components, shorthandName, validator) {
component = components[descriptor.components[i]];
mayOverride = compactable[component.name].canOverride;
if (!everyValuesPair(mayOverride.bind(null, validator), newProperty.components[i], component)) {
if (
!everyValuesPair(
mayOverride.bind(null, validator),
newProperty.components[i],
component
)
) {
return false;
}
}
@ -175,7 +203,10 @@ function mergeable(components) {
continue;
}
restoreFromOptimizing([component.all[component.position]], restoreWithComponents);
restoreFromOptimizing(
[component.all[component.position]],
restoreWithComponents
);
values = descriptor.restore(component, compactable);
currentCount = values.length;
@ -208,13 +239,29 @@ function mixedInherit(components) {
return false;
}
function replaceWithInheritBestFit(properties, candidateComponents, shorthandName, validator) {
var viaLonghands = buildSequenceWithInheritLonghands(candidateComponents, shorthandName, validator);
var viaShorthand = buildSequenceWithInheritShorthand(candidateComponents, shorthandName, validator);
function replaceWithInheritBestFit(
properties,
candidateComponents,
shorthandName,
validator
) {
var viaLonghands = buildSequenceWithInheritLonghands(
candidateComponents,
shorthandName,
validator
);
var viaShorthand = buildSequenceWithInheritShorthand(
candidateComponents,
shorthandName,
validator
);
var longhandTokensSequence = viaLonghands[0];
var shorthandTokensSequence = viaShorthand[0];
var isLonghandsShorter = serializeBody(longhandTokensSequence).length < serializeBody(shorthandTokensSequence).length;
var newTokensSequence = isLonghandsShorter ? longhandTokensSequence : shorthandTokensSequence;
var isLonghandsShorter =
serializeBody(longhandTokensSequence).length <
serializeBody(shorthandTokensSequence).length;
var newTokensSequence =
isLonghandsShorter ? longhandTokensSequence : shorthandTokensSequence;
var newProperty = isLonghandsShorter ? viaLonghands[1] : viaShorthand[1];
var newComponents = isLonghandsShorter ? viaLonghands[2] : viaShorthand[2];
var all = candidateComponents[Object.keys(candidateComponents)[0]].all;
@ -248,7 +295,11 @@ function replaceWithInheritBestFit(properties, candidateComponents, shorthandNam
}
}
function buildSequenceWithInheritLonghands(components, shorthandName, validator) {
function buildSequenceWithInheritLonghands(
components,
shorthandName,
validator
) {
var tokensSequence = [];
var inheritComponents = {};
var nonInheritComponents = {};
@ -256,7 +307,7 @@ function buildSequenceWithInheritLonghands(components, shorthandName, validator)
var shorthandToken = [
Token.PROPERTY,
[Token.PROPERTY_NAME, shorthandName],
[Token.PROPERTY_VALUE, descriptor.defaultValue]
[Token.PROPERTY_VALUE, descriptor.defaultValue],
];
var newProperty = wrapSingle(shorthandToken);
var component;
@ -345,7 +396,11 @@ function metadataSorter(metadata1, metadata2) {
}
}
function buildSequenceWithInheritShorthand(components, shorthandName, validator) {
function buildSequenceWithInheritShorthand(
components,
shorthandName,
validator
) {
var tokensSequence = [];
var inheritComponents = {};
var nonInheritComponents = {};
@ -353,7 +408,7 @@ function buildSequenceWithInheritShorthand(components, shorthandName, validator)
var shorthandToken = [
Token.PROPERTY,
[Token.PROPERTY_NAME, shorthandName],
[Token.PROPERTY_VALUE, 'inherit']
[Token.PROPERTY_VALUE, 'inherit'],
];
var newProperty = wrapSingle(shorthandToken);
var component;
@ -399,14 +454,19 @@ function findTokenIn(tokens, componentName) {
}
}
function replaceWithShorthand(properties, candidateComponents, shorthandName, validator) {
function replaceWithShorthand(
properties,
candidateComponents,
shorthandName,
validator
) {
var descriptor = compactable[shorthandName];
var nameMetadata;
var valueMetadata;
var newValuePlaceholder = [
Token.PROPERTY,
[Token.PROPERTY_NAME, shorthandName],
[Token.PROPERTY_VALUE, descriptor.defaultValue]
[Token.PROPERTY_VALUE, descriptor.defaultValue],
];
var all;

View File

@ -8,11 +8,16 @@ var wrapForOptimizing = require('../../wrap-for-optimizing').all;
var removeUnused = require('../../remove-unused');
var restoreFromOptimizing = require('../../restore-from-optimizing');
var OptimizationLevel = require('../../../options/optimization-level').OptimizationLevel;
var OptimizationLevel =
require('../../../options/optimization-level').OptimizationLevel;
function optimizeProperties(properties, withOverriding, withMerging, context) {
var levelOptions = context.options.level[OptimizationLevel.Two];
var _properties = wrapForOptimizing(properties, false, levelOptions.skipProperties);
var _properties = wrapForOptimizing(
properties,
false,
levelOptions.skipProperties
);
var _property;
var i, l;
@ -21,7 +26,12 @@ function optimizeProperties(properties, withOverriding, withMerging, context) {
for (i = 0, l = _properties.length; i < l; i++) {
_property = _properties[i];
if (_property.block) {
optimizeProperties(_property.value[0][1], withOverriding, withMerging, context);
optimizeProperties(
_property.value[0][1],
withOverriding,
withMerging,
context
);
}
}
@ -30,7 +40,12 @@ function optimizeProperties(properties, withOverriding, withMerging, context) {
}
if (withOverriding && levelOptions.overrideProperties) {
overrideProperties(_properties, withMerging, context.options.compatibility, context.validator);
overrideProperties(
_properties,
withMerging,
context.options.compatibility,
context.validator
);
}
restoreFromOptimizing(_properties, restoreWithComponents);

View File

@ -22,12 +22,15 @@ function wouldBreakCompatibility(property, validator) {
for (var i = 0; i < property.components.length; i++) {
var component = property.components[i];
var descriptor = compactable[component.name];
var canOverride = descriptor && descriptor.canOverride || canOverride.sameValue;
var canOverride =
(descriptor && descriptor.canOverride) || canOverride.sameValue;
var _component = shallowClone(component);
_component.value = [[Token.PROPERTY_VALUE, descriptor.defaultValue]];
if (!everyValuesPair(canOverride.bind(null, validator), _component, component)) {
if (
!everyValuesPair(canOverride.bind(null, validator), _component, component)
) {
return true;
}
}
@ -54,12 +57,9 @@ function overrideSimple(property, by) {
}
function override(property, by) {
if (by.multiplex)
overrideByMultiplex(property, by);
else if (property.multiplex)
overrideIntoMultiplex(property, by);
else
overrideSimple(property, by);
if (by.multiplex) overrideByMultiplex(property, by);
else if (property.multiplex) overrideIntoMultiplex(property, by);
else overrideSimple(property, by);
}
function overrideShorthand(property, by) {
@ -96,9 +96,11 @@ function turnShorthandValueIntoMultiplex(property, size) {
function turnLonghandValueIntoMultiplex(property, size) {
var descriptor = compactable[property.name];
var withRealValue = descriptor.intoMultiplexMode == 'real';
var withValue = descriptor.intoMultiplexMode == 'real' ?
property.value.slice(0) :
(descriptor.intoMultiplexMode == 'placeholder' ? descriptor.placeholderValue : descriptor.defaultValue);
var withValue =
descriptor.intoMultiplexMode == 'real' ? property.value.slice(0)
: descriptor.intoMultiplexMode == 'placeholder' ?
descriptor.placeholderValue
: descriptor.defaultValue;
var i = multiplexSize(property);
var j;
var m = withValue.length;
@ -108,10 +110,14 @@ function turnLonghandValueIntoMultiplex(property, size) {
if (Array.isArray(withValue)) {
for (j = 0; j < m; j++) {
property.value.push(withRealValue ? withValue[j] : [Token.PROPERTY_VALUE, withValue[j]]);
property.value.push(
withRealValue ? withValue[j] : [Token.PROPERTY_VALUE, withValue[j]]
);
}
} else {
property.value.push(withRealValue ? withValue : [Token.PROPERTY_VALUE, withValue]);
property.value.push(
withRealValue ? withValue : [Token.PROPERTY_VALUE, withValue]
);
}
}
}
@ -120,8 +126,7 @@ function multiplexSize(component) {
var size = 0;
for (var i = 0, l = component.value.length; i < l; i++) {
if (component.value[i][1] == Marker.COMMA)
size++;
if (component.value[i][1] == Marker.COMMA) size++;
}
return size + 1;
@ -130,7 +135,7 @@ function multiplexSize(component) {
function lengthOf(property) {
var fakeAsArray = [
Token.PROPERTY,
[Token.PROPERTY_NAME, property.name]
[Token.PROPERTY_NAME, property.name],
].concat(property.value);
return serializeProperty([fakeAsArray], 0).length;
}
@ -142,10 +147,8 @@ function moreSameShorthands(properties, startAt, name) {
var count = 0;
for (var i = startAt; i >= 0; i--) {
if (properties[i].name == name && !properties[i].unused)
count++;
if (count > 1)
break;
if (properties[i].name == name && !properties[i].unused) count++;
if (count > 1) break;
}
return count > 1;
@ -153,7 +156,10 @@ function moreSameShorthands(properties, startAt, name) {
function overridingFunction(shorthand, validator) {
for (var i = 0, l = shorthand.components.length; i < l; i++) {
if (!anyValue(validator.isUrl, shorthand.components[i]) && anyValue(validator.isFunction, shorthand.components[i])) {
if (
!anyValue(validator.isUrl, shorthand.components[i]) &&
anyValue(validator.isFunction, shorthand.components[i])
) {
return true;
}
}
@ -163,18 +169,19 @@ function overridingFunction(shorthand, validator) {
function anyValue(fn, property) {
for (var i = 0, l = property.value.length; i < l; i++) {
if (property.value[i][1] == Marker.COMMA)
continue;
if (property.value[i][1] == Marker.COMMA) continue;
if (fn(property.value[i][1]))
return true;
if (fn(property.value[i][1])) return true;
}
return false;
}
function wouldResultInLongerValue(left, right) {
if (!left.multiplex && !right.multiplex || left.multiplex && right.multiplex)
if (
(!left.multiplex && !right.multiplex) ||
(left.multiplex && right.multiplex)
)
return false;
var multiplex = left.multiplex ? left : right;
@ -210,19 +217,20 @@ function isCompactable(property) {
}
function noneOverrideHack(left, right) {
return !left.multiplex &&
return (
!left.multiplex &&
(left.name == 'background' || left.name == 'background-image') &&
right.multiplex &&
(right.name == 'background' || right.name == 'background-image') &&
anyLayerIsNone(right.value);
anyLayerIsNone(right.value)
);
}
function anyLayerIsNone(values) {
var layers = intoLayers(values);
for (var i = 0, l = layers.length; i < l; i++) {
if (layers[i].length == 1 && layers[i][0][1] == 'none')
return true;
if (layers[i].length == 1 && layers[i][0][1] == 'none') return true;
}
return false;
@ -253,55 +261,54 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
var overridable;
var i, j, k;
propertyLoop:
for (i = properties.length - 1; i >= 0; i--) {
propertyLoop: for (i = properties.length - 1; i >= 0; i--) {
right = properties[i];
if (!isCompactable(right))
continue;
if (!isCompactable(right)) continue;
if (right.block)
continue;
if (right.block) continue;
mayOverride = compactable[right.name].canOverride;
traverseLoop:
for (j = i - 1; j >= 0; j--) {
traverseLoop: for (j = i - 1; j >= 0; j--) {
left = properties[j];
if (!isCompactable(left))
continue;
if (!isCompactable(left)) continue;
if (left.block)
continue;
if (left.block) continue;
if (left.unused || right.unused)
continue;
if (left.unused || right.unused) continue;
if (left.hack && !right.hack && !right.important || !left.hack && !left.important && right.hack)
if (
(left.hack && !right.hack && !right.important) ||
(!left.hack && !left.important && right.hack)
)
continue;
if (left.important == right.important && left.hack[0] != right.hack[0])
continue;
if (left.important == right.important && (left.hack[0] != right.hack[0] || (left.hack[1] && left.hack[1] != right.hack[1])))
if (
left.important == right.important &&
(left.hack[0] != right.hack[0] ||
(left.hack[1] && left.hack[1] != right.hack[1]))
)
continue;
if (hasInherit(right))
continue;
if (hasInherit(right)) continue;
if (noneOverrideHack(left, right))
continue;
if (noneOverrideHack(left, right)) continue;
if (right.shorthand && isComponentOf(right, left)) {
// maybe `left` can be overridden by `right` which is a shorthand?
if (!right.important && left.important)
continue;
if (!right.important && left.important) continue;
if (!sameVendorPrefixesIn([left], right.components))
continue;
if (!sameVendorPrefixesIn([left], right.components)) continue;
if (!anyValue(validator.isFunction, left) && overridingFunction(right, validator))
if (
!anyValue(validator.isFunction, left) &&
overridingFunction(right, validator)
)
continue;
if (!isMergeableShorthand(right)) {
@ -311,10 +318,15 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
component = findComponentIn(right, left);
mayOverride = compactable[left.name].canOverride;
if (everyValuesPair(mayOverride.bind(null, validator), left, component)) {
if (
everyValuesPair(mayOverride.bind(null, validator), left, component)
) {
left.unused = true;
}
} else if (right.shorthand && overridesNonComponentShorthand(right, left)) {
} else if (
right.shorthand &&
overridesNonComponentShorthand(right, left)
) {
// `right` is a shorthand while `left` can be overriden by it, think `border` and `border-top`
if (!right.important && left.important) {
continue;
@ -324,29 +336,40 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
continue;
}
if (!anyValue(validator.isFunction, left) && overridingFunction(right, validator)) {
if (
!anyValue(validator.isFunction, left) &&
overridingFunction(right, validator)
) {
continue;
}
overriddenComponents = left.shorthand ?
left.components:
[left];
overriddenComponents = left.shorthand ? left.components : [left];
for (k = overriddenComponents.length - 1; k >= 0; k--) {
overriddenComponent = overriddenComponents[k];
overridingComponent = findComponentIn(right, overriddenComponent);
mayOverride = compactable[overriddenComponent.name].canOverride;
if (!everyValuesPair(mayOverride.bind(null, validator), left, overridingComponent)) {
if (
!everyValuesPair(
mayOverride.bind(null, validator),
left,
overridingComponent
)
) {
continue traverseLoop;
}
}
left.unused = true;
} else if (withMerging && left.shorthand && !right.shorthand && isComponentOf(left, right, true)) {
} else if (
withMerging &&
left.shorthand &&
!right.shorthand &&
isComponentOf(left, right, true)
) {
// maybe `right` can be pulled into `left` which is a shorthand?
if (right.important && !left.important)
continue;
if (right.important && !left.important) continue;
if (!right.important && left.important) {
right.unused = true;
@ -354,34 +377,41 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
}
// Pending more clever algorithm in #527
if (moreSameShorthands(properties, i - 1, left.name))
continue;
if (moreSameShorthands(properties, i - 1, left.name)) continue;
if (overridingFunction(left, validator))
continue;
if (overridingFunction(left, validator)) continue;
if (!isMergeableShorthand(left))
continue;
if (!isMergeableShorthand(left)) continue;
component = findComponentIn(left, right);
if (everyValuesPair(mayOverride.bind(null, validator), component, right)) {
if (
everyValuesPair(mayOverride.bind(null, validator), component, right)
) {
var disabledBackgroundMerging =
!compatibility.properties.backgroundClipMerging && component.name.indexOf('background-clip') > -1 ||
!compatibility.properties.backgroundOriginMerging && component.name.indexOf('background-origin') > -1 ||
!compatibility.properties.backgroundSizeMerging && component.name.indexOf('background-size') > -1;
var nonMergeableValue = compactable[right.name].nonMergeableValue === right.value[0][1];
(!compatibility.properties.backgroundClipMerging &&
component.name.indexOf('background-clip') > -1) ||
(!compatibility.properties.backgroundOriginMerging &&
component.name.indexOf('background-origin') > -1) ||
(!compatibility.properties.backgroundSizeMerging &&
component.name.indexOf('background-size') > -1);
var nonMergeableValue =
compactable[right.name].nonMergeableValue === right.value[0][1];
if (disabledBackgroundMerging || nonMergeableValue)
if (disabledBackgroundMerging || nonMergeableValue) continue;
if (
!compatibility.properties.merging &&
wouldBreakCompatibility(left, validator)
)
continue;
if (!compatibility.properties.merging && wouldBreakCompatibility(left, validator))
if (
component.value[0][1] != right.value[0][1] &&
(hasInherit(left) || hasInherit(right))
)
continue;
if (component.value[0][1] != right.value[0][1] && (hasInherit(left) || hasInherit(right)))
continue;
if (wouldResultInLongerValue(left, right))
continue;
if (wouldResultInLongerValue(left, right)) continue;
if (!left.multiplex && right.multiplex)
turnIntoMultiplex(left, multiplexSize(right));
@ -389,11 +419,15 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
override(component, right);
left.dirty = true;
}
} else if (withMerging && left.shorthand && right.shorthand && left.name == right.name) {
} else if (
withMerging &&
left.shorthand &&
right.shorthand &&
left.name == right.name
) {
// merge if all components can be merged
if (!left.multiplex && right.multiplex)
continue;
if (!left.multiplex && right.multiplex) continue;
if (!right.important && left.important) {
right.unused = true;
@ -415,21 +449,33 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
var rightComponent = right.components[k];
mayOverride = compactable[leftComponent.name].canOverride;
if (!everyValuesPair(mayOverride.bind(null, validator), leftComponent, rightComponent))
if (
!everyValuesPair(
mayOverride.bind(null, validator),
leftComponent,
rightComponent
)
)
continue propertyLoop;
}
overrideShorthand(left, right);
left.dirty = true;
} else if (withMerging && left.shorthand && right.shorthand && isComponentOf(left, right)) {
} else if (
withMerging &&
left.shorthand &&
right.shorthand &&
isComponentOf(left, right)
) {
// border is a shorthand but any of its components is a shorthand too
if (!left.important && right.important)
continue;
if (!left.important && right.important) continue;
component = findComponentIn(left, right);
mayOverride = compactable[right.name].canOverride;
if (!everyValuesPair(mayOverride.bind(null, validator), component, right))
if (
!everyValuesPair(mayOverride.bind(null, validator), component, right)
)
continue;
if (left.important && !right.important) {
@ -438,8 +484,7 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
}
var rightRestored = compactable[right.name].restore(right, compactable);
if (rightRestored.length > 1)
continue;
if (rightRestored.length > 1) continue;
component = findComponentIn(left, right);
override(component, right);
@ -454,11 +499,21 @@ function overrideProperties(properties, withMerging, compatibility, validator) {
overridingComponent = right.components[k];
mayOverride = compactable[overridingComponent.name].canOverride;
overridable = overridable && everyValuesPair(mayOverride.bind(null, validator), overriddenComponent, overridingComponent);
overridable =
overridable &&
everyValuesPair(
mayOverride.bind(null, validator),
overriddenComponent,
overridingComponent
);
}
} else {
mayOverride = compactable[right.name].canOverride;
overridable = everyValuesPair(mayOverride.bind(null, validator), left, right);
overridable = everyValuesPair(
mayOverride.bind(null, validator),
left,
right
);
}
if (left.important && !right.important && overridable) {

View File

@ -1,9 +1,11 @@
var compactable = require('../compactable');
function overridesNonComponentShorthand(property1, property2) {
return property1.name in compactable &&
return (
property1.name in compactable &&
'overridesShorthands' in compactable[property1.name] &&
compactable[property1.name].overridesShorthands.indexOf(property2.name) > -1;
compactable[property1.name].overridesShorthands.indexOf(property2.name) > -1
);
}
module.exports = overridesNonComponentShorthand;

View File

@ -14,12 +14,20 @@ function populateComponents(properties, validator, warnings) {
property.dirty = true;
try {
property.components = descriptor.breakUp(property, compactable, validator);
property.components = descriptor.breakUp(
property,
compactable,
validator
);
if (descriptor.shorthandComponents) {
for (j = 0, m = property.components.length; j < m; j++) {
component = property.components[j];
component.components = compactable[component.name].breakUp(component, compactable, validator);
component.components = compactable[component.name].breakUp(
component,
compactable,
validator
);
}
}
} catch (e) {
@ -33,8 +41,7 @@ function populateComponents(properties, validator, warnings) {
if (property.components.length > 0)
property.multiplex = property.components[0].multiplex;
else
property.unused = true;
else property.unused = true;
}
}
}

View File

@ -5,7 +5,10 @@ function understandable(validator, value1, value2, _position, isPaired) {
return false;
}
if (isPaired && validator.isVariable(value1) !== validator.isVariable(value2)) {
if (
isPaired &&
validator.isVariable(value1) !== validator.isVariable(value2)
) {
return false;
}

View File

@ -19,5 +19,5 @@ function same(value1, value2) {
module.exports = {
unique: unique,
same: same
same: same,
};

View File

@ -11,9 +11,12 @@ var serializeRules = require('../../writer/one-time').rules;
function reduceNonAdjacent(tokens, context) {
var options = context.options;
var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses;
var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements;
var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging;
var mergeablePseudoClasses =
options.compatibility.selectors.mergeablePseudoClasses;
var mergeablePseudoElements =
options.compatibility.selectors.mergeablePseudoElements;
var multiplePseudoMerging =
options.compatibility.selectors.multiplePseudoMerging;
var candidates = {};
var repeated = [];
@ -27,26 +30,31 @@ function reduceNonAdjacent(tokens, context) {
}
var selectorAsString = serializeRules(token[1]);
var isComplexAndNotSpecial = token[1].length > 1 &&
isMergeable(selectorAsString, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging);
var isComplexAndNotSpecial =
token[1].length > 1 &&
isMergeable(
selectorAsString,
mergeablePseudoClasses,
mergeablePseudoElements,
multiplePseudoMerging
);
var wrappedSelectors = wrappedSelectorsFrom(token[1]);
var selectors = isComplexAndNotSpecial ?
[selectorAsString].concat(wrappedSelectors) :
[selectorAsString];
var selectors =
isComplexAndNotSpecial ?
[selectorAsString].concat(wrappedSelectors)
: [selectorAsString];
for (var j = 0, m = selectors.length; j < m; j++) {
var selector = selectors[j];
if (!candidates[selector])
candidates[selector] = [];
else
repeated.push(selector);
if (!candidates[selector]) candidates[selector] = [];
else repeated.push(selector);
candidates[selector].push({
where: i,
list: wrappedSelectors,
isPartial: isComplexAndNotSpecial && j > 0,
isComplex: isComplexAndNotSpecial && j === 0
isComplex: isComplexAndNotSpecial && j === 0,
});
}
}
@ -65,31 +73,45 @@ function wrappedSelectorsFrom(list) {
return wrapped;
}
function reduceSimpleNonAdjacentCases(tokens, repeated, candidates, options, context) {
function reduceSimpleNonAdjacentCases(
tokens,
repeated,
candidates,
options,
context
) {
function filterOut(idx, bodies) {
return data[idx].isPartial && bodies.length === 0;
}
function reduceBody(token, newBody, processedCount, tokenIdx) {
if (!data[processedCount - tokenIdx - 1].isPartial)
token[2] = newBody;
if (!data[processedCount - tokenIdx - 1].isPartial) token[2] = newBody;
}
for (var i = 0, l = repeated.length; i < l; i++) {
var selector = repeated[i];
var data = candidates[selector];
reduceSelector(tokens, data, {
filterOut: filterOut,
callback: reduceBody
}, options, context);
reduceSelector(
tokens,
data,
{
filterOut: filterOut,
callback: reduceBody,
},
options,
context
);
}
}
function reduceComplexNonAdjacentCases(tokens, candidates, options, context) {
var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses;
var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements;
var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging;
var mergeablePseudoClasses =
options.compatibility.selectors.mergeablePseudoClasses;
var mergeablePseudoElements =
options.compatibility.selectors.mergeablePseudoElements;
var multiplePseudoMerging =
options.compatibility.selectors.multiplePseudoMerging;
var localContext = {};
function filterOut(idx) {
@ -97,23 +119,28 @@ function reduceComplexNonAdjacentCases(tokens, candidates, options, context) {
}
function collectReducedBodies(token, newBody, processedCount, tokenIdx) {
if (tokenIdx === 0)
localContext.reducedBodies.push(newBody);
if (tokenIdx === 0) localContext.reducedBodies.push(newBody);
}
allSelectors:
for (var complexSelector in candidates) {
allSelectors: for (var complexSelector in candidates) {
var into = candidates[complexSelector];
if (!into[0].isComplex)
continue;
if (!into[0].isComplex) continue;
var intoPosition = into[into.length - 1].where;
var intoToken = tokens[intoPosition];
var reducedBodies = [];
var selectors = isMergeable(complexSelector, mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging) ?
into[0].list :
[complexSelector];
var selectors =
(
isMergeable(
complexSelector,
mergeablePseudoClasses,
mergeablePseudoElements,
multiplePseudoMerging
)
) ?
into[0].list
: [complexSelector];
localContext.intoPosition = intoPosition;
localContext.reducedBodies = reducedBodies;
@ -122,17 +149,25 @@ function reduceComplexNonAdjacentCases(tokens, candidates, options, context) {
var selector = selectors[j];
var data = candidates[selector];
if (data.length < 2)
continue allSelectors;
if (data.length < 2) continue allSelectors;
localContext.data = data;
reduceSelector(tokens, data, {
filterOut: filterOut,
callback: collectReducedBodies
}, options, context);
reduceSelector(
tokens,
data,
{
filterOut: filterOut,
callback: collectReducedBodies,
},
options,
context
);
if (serializeBody(reducedBodies[reducedBodies.length - 1]) != serializeBody(reducedBodies[0]))
if (
serializeBody(reducedBodies[reducedBodies.length - 1]) !=
serializeBody(reducedBodies[0])
)
continue allSelectors;
}
@ -146,8 +181,7 @@ function reduceSelector(tokens, data, context, options, outerContext) {
var processedTokens = [];
for (var j = data.length - 1; j >= 0; j--) {
if (context.filterOut(j, bodies))
continue;
if (context.filterOut(j, bodies)) continue;
var where = data[j].where;
var token = tokens[where];
@ -165,13 +199,23 @@ function reduceSelector(tokens, data, context, options, outerContext) {
var tokenIdx = processedCount - 1;
while (tokenIdx >= 0) {
if ((tokenIdx === 0 || (bodies[propertyIdx] && bodiesAsList[tokenIdx].indexOf(bodies[propertyIdx]) > -1)) && propertyIdx > -1) {
if (
(tokenIdx === 0 ||
(bodies[propertyIdx] &&
bodiesAsList[tokenIdx].indexOf(bodies[propertyIdx]) > -1)) &&
propertyIdx > -1
) {
propertyIdx--;
continue;
}
var newBody = bodies.splice(propertyIdx + 1);
context.callback(tokens[processedTokens[tokenIdx]], newBody, processedCount, tokenIdx);
context.callback(
tokens[processedTokens[tokenIdx]],
newBody,
processedCount,
tokenIdx
);
tokenIdx--;
}

View File

@ -11,15 +11,12 @@ function removeDuplicates(tokens) {
for (var i = 0, l = tokens.length; i < l; i++) {
token = tokens[i];
if (token[0] != Token.RULE)
continue;
if (token[0] != Token.RULE) continue;
id = serializeRules(token[1]);
if (matched[id] && matched[id].length == 1)
moreThanOnce.push(id);
else
matched[id] = matched[id] || [];
if (matched[id] && matched[id].length == 1) moreThanOnce.push(id);
else matched[id] = matched[id] || [];
matched[id].push(i);
}
@ -32,10 +29,8 @@ function removeDuplicates(tokens) {
token = tokens[matched[id][j]];
body = serializeBody(token[2]);
if (bodies.indexOf(body) > -1)
token[2] = [];
else
bodies.push(body);
if (bodies.indexOf(body) > -1) token[2] = [];
else bodies.push(body);
}
}
}

View File

@ -18,7 +18,12 @@ function normalize(value) {
}
function removeUnusedAtRules(tokens, context) {
removeUnusedAtRule(tokens, matchCounterStyle, markCounterStylesAsUsed, context);
removeUnusedAtRule(
tokens,
matchCounterStyle,
markCounterStylesAsUsed,
context
);
removeUnusedAtRule(tokens, matchFontFace, markFontFacesAsUsed, context);
removeUnusedAtRule(tokens, matchKeyframe, markKeyframesAsUsed, context);
removeUnusedAtRule(tokens, matchNamespace, markNamespacesAsUsed, context);
@ -71,7 +76,10 @@ function markUsedAtRules(tokens, markCallback, atRules, context) {
function matchCounterStyle(token, atRules) {
var match;
if (token[0] == Token.AT_RULE_BLOCK && token[1][0][1].indexOf('@counter-style') === 0) {
if (
token[0] == Token.AT_RULE_BLOCK &&
token[1][0][1].indexOf('@counter-style') === 0
) {
match = token[1][0][1].split(' ')[1];
atRules[match] = atRules[match] || [];
atRules[match].push(token);
@ -89,7 +97,11 @@ function markCounterStylesAsUsed(atRules) {
if (property[1][1] == 'list-style') {
wrappedProperty = wrapForOptimizing(property);
populateComponents([wrappedProperty], context.validator, context.warnings);
populateComponents(
[wrappedProperty],
context.validator,
context.warnings
);
if (wrappedProperty.components[0].value[0][1] in atRules) {
delete atRules[property[2][1]];
@ -138,7 +150,11 @@ function markFontFacesAsUsed(atRules) {
if (property[1][1] == 'font') {
wrappedProperty = wrapForOptimizing(property);
populateComponents([wrappedProperty], context.validator, context.warnings);
populateComponents(
[wrappedProperty],
context.validator,
context.warnings
);
component = wrappedProperty.components[6];
for (j = 0, m = component.value.length; j < m; j++) {
@ -188,7 +204,11 @@ function markKeyframesAsUsed(atRules) {
if (animationRegex.test(property[1][1])) {
wrappedProperty = wrapForOptimizing(property);
populateComponents([wrappedProperty], context.validator, context.warnings);
populateComponents(
[wrappedProperty],
context.validator,
context.warnings
);
component = wrappedProperty.components[7];
for (j = 0, m = component.value.length; j < m; j++) {
@ -222,7 +242,10 @@ function matchNamespace(token, atRules) {
}
function markNamespacesAsUsed(atRules) {
var namespaceRegex = new RegExp(Object.keys(atRules).join('\\\||') + '\\\|', 'g');
var namespaceRegex = new RegExp(
Object.keys(atRules).join('\\\||') + '\\\|',
'g'
);
return function (token) {
var match;

View File

@ -4,13 +4,13 @@ var rulesOverlap = require('./rules-overlap');
var specificitiesOverlap = require('./specificities-overlap');
var FLEX_PROPERTIES = /align\-items|box\-align|box\-pack|flex|justify/;
var BORDER_PROPERTIES = /^border\-(top|right|bottom|left|color|style|width|radius)/;
var BORDER_PROPERTIES =
/^border\-(top|right|bottom|left|color|style|width|radius)/;
function canReorder(left, right, cache) {
for (var i = right.length - 1; i >= 0; i--) {
for (var j = left.length - 1; j >= 0; j--) {
if (!canReorderSingle(left[j], right[i], cache))
return false;
if (!canReorderSingle(left[j], right[i], cache)) return false;
}
}
@ -29,30 +29,73 @@ function canReorderSingle(left, right, cache) {
var rightSelector = right[5];
var rightInSpecificSelector = right[6];
if (leftName == 'font' && rightName == 'line-height' || rightName == 'font' && leftName == 'line-height')
if (
(leftName == 'font' && rightName == 'line-height') ||
(rightName == 'font' && leftName == 'line-height')
)
return false;
if (FLEX_PROPERTIES.test(leftName) && FLEX_PROPERTIES.test(rightName))
return false;
if (leftNameRoot == rightNameRoot && unprefixed(leftName) == unprefixed(rightName) && (vendorPrefixed(leftName) ^ vendorPrefixed(rightName)))
if (
leftNameRoot == rightNameRoot &&
unprefixed(leftName) == unprefixed(rightName) &&
vendorPrefixed(leftName) ^ vendorPrefixed(rightName)
)
return false;
if (leftNameRoot == 'border' && BORDER_PROPERTIES.test(rightNameRoot) && (leftName == 'border' || leftName == rightNameRoot || (leftValue != rightValue && sameBorderComponent(leftName, rightName))))
if (
leftNameRoot == 'border' &&
BORDER_PROPERTIES.test(rightNameRoot) &&
(leftName == 'border' ||
leftName == rightNameRoot ||
(leftValue != rightValue && sameBorderComponent(leftName, rightName)))
)
return false;
if (rightNameRoot == 'border' && BORDER_PROPERTIES.test(leftNameRoot) && (rightName == 'border' || rightName == leftNameRoot || (leftValue != rightValue && sameBorderComponent(leftName, rightName))))
if (
rightNameRoot == 'border' &&
BORDER_PROPERTIES.test(leftNameRoot) &&
(rightName == 'border' ||
rightName == leftNameRoot ||
(leftValue != rightValue && sameBorderComponent(leftName, rightName)))
)
return false;
if (leftNameRoot == 'border' && rightNameRoot == 'border' && leftName != rightName && (isSideBorder(leftName) && isStyleBorder(rightName) || isStyleBorder(leftName) && isSideBorder(rightName)))
if (
leftNameRoot == 'border' &&
rightNameRoot == 'border' &&
leftName != rightName &&
((isSideBorder(leftName) && isStyleBorder(rightName)) ||
(isStyleBorder(leftName) && isSideBorder(rightName)))
)
return false;
if (leftNameRoot != rightNameRoot)
if (leftNameRoot != rightNameRoot) return true;
if (
leftName == rightName &&
leftNameRoot == rightNameRoot &&
(leftValue == rightValue ||
withDifferentVendorPrefix(leftValue, rightValue))
)
return true;
if (leftName == rightName && leftNameRoot == rightNameRoot && (leftValue == rightValue || withDifferentVendorPrefix(leftValue, rightValue)))
if (
leftName != rightName &&
leftNameRoot == rightNameRoot &&
leftName != leftNameRoot &&
rightName != rightNameRoot
)
return true;
if (leftName != rightName && leftNameRoot == rightNameRoot && leftName != leftNameRoot && rightName != rightNameRoot)
if (
leftName != rightName &&
leftNameRoot == rightNameRoot &&
leftValue == rightValue
)
return true;
if (leftName != rightName && leftNameRoot == rightNameRoot && leftValue == rightValue)
return true;
if (rightInSpecificSelector && leftInSpecificSelector && !inheritable(leftNameRoot) && !inheritable(rightNameRoot) && !rulesOverlap(rightSelector, leftSelector, false))
return true;
if (!specificitiesOverlap(leftSelector, rightSelector, cache))
if (
rightInSpecificSelector &&
leftInSpecificSelector &&
!inheritable(leftNameRoot) &&
!inheritable(rightNameRoot) &&
!rulesOverlap(rightSelector, leftSelector, false)
)
return true;
if (!specificitiesOverlap(leftSelector, rightSelector, cache)) return true;
return false;
}
@ -70,15 +113,26 @@ function sameBorderComponent(name1, name2) {
}
function isSideBorder(name) {
return name == 'border-top' || name == 'border-right' || name == 'border-bottom' || name == 'border-left';
return (
name == 'border-top' ||
name == 'border-right' ||
name == 'border-bottom' ||
name == 'border-left'
);
}
function isStyleBorder(name) {
return name == 'border-color' || name == 'border-style' || name == 'border-width';
return (
name == 'border-color' || name == 'border-style' || name == 'border-width'
);
}
function withDifferentVendorPrefix(value1, value2) {
return vendorPrefixed(value1) && vendorPrefixed(value2) && value1.split('-')[1] != value2.split('-')[2];
return (
vendorPrefixed(value1) &&
vendorPrefixed(value2) &&
value1.split('-')[1] != value2.split('-')[2]
);
}
function inheritable(name) {
@ -89,5 +143,5 @@ function inheritable(name) {
module.exports = {
canReorder: canReorder,
canReorderSingle: canReorderSingle
canReorderSingle: canReorderSingle,
};

View File

@ -7,7 +7,11 @@ function isInheritOnly(values) {
for (var i = 0, l = values.length; i < l; i++) {
var value = values[i][1];
if (value != 'inherit' && value != Marker.COMMA && value != Marker.FORWARD_SLASH)
if (
value != 'inherit' &&
value != Marker.COMMA &&
value != Marker.FORWARD_SLASH
)
return false;
}
@ -27,9 +31,18 @@ function background(property, compactable, lastInMultiplex) {
var descriptor = compactable[component.name];
if (descriptor.doubleValues && descriptor.defaultValue.length == 1) {
return component.value[0][1] == descriptor.defaultValue[0] && (component.value[1] ? component.value[1][1] == descriptor.defaultValue[0] : true);
return (
component.value[0][1] == descriptor.defaultValue[0] &&
(component.value[1] ?
component.value[1][1] == descriptor.defaultValue[0]
: true)
);
} else if (descriptor.doubleValues && descriptor.defaultValue.length != 1) {
return component.value[0][1] == descriptor.defaultValue[0] && (component.value[1] ? component.value[1][1] : component.value[0][1]) == descriptor.defaultValue[1];
return (
component.value[0][1] == descriptor.defaultValue[0] &&
(component.value[1] ? component.value[1][1] : component.value[0][1]) ==
descriptor.defaultValue[1]
);
} else {
return component.value[0][1] == descriptor.defaultValue;
}
@ -45,10 +58,13 @@ function background(property, compactable, lastInMultiplex) {
needsOne = component.value[0][1] == originComponent.value[0][1];
needsBoth = !needsOne && (
(isOriginDefault && !isDefault) ||
(!isOriginDefault && !isDefault) ||
(!isOriginDefault && isDefault && component.value[0][1] != originComponent.value[0][1]));
needsBoth =
!needsOne &&
((isOriginDefault && !isDefault) ||
(!isOriginDefault && !isDefault) ||
(!isOriginDefault &&
isDefault &&
component.value[0][1] != originComponent.value[0][1]));
if (needsOne) {
restoreValue(originComponent);
@ -64,8 +80,10 @@ function background(property, compactable, lastInMultiplex) {
needsOne = !isPositionDefault && isDefault;
needsBoth = !needsOne &&
(isPositionDefault && !isDefault || !isPositionDefault && !isDefault);
needsBoth =
!needsOne &&
((isPositionDefault && !isDefault) ||
(!isPositionDefault && !isDefault));
if (needsOne) {
restoreValue(positionComponent);
@ -79,21 +97,30 @@ function background(property, compactable, lastInMultiplex) {
i--;
} else {
if (isDefault || compactable[component.name].multiplexLastOnly && !lastInMultiplex)
if (
isDefault ||
(compactable[component.name].multiplexLastOnly && !lastInMultiplex)
)
continue;
restoreValue(component);
}
}
if (restored.length === 0 && property.value.length == 1 && property.value[0][1] == '0')
if (
restored.length === 0 &&
property.value.length == 1 &&
property.value[0][1] == '0'
)
restored.push(property.value[0]);
if (restored.length === 0)
restored.push([Token.PROPERTY_VALUE, compactable[property.name].defaultValue]);
restored.push([
Token.PROPERTY_VALUE,
compactable[property.name].defaultValue,
]);
if (isInheritOnly(restored))
return [restored[0]];
if (isInheritOnly(restored)) return [restored[0]];
return restored;
}
@ -121,14 +148,24 @@ function borderRadius(property, compactable) {
var horizontalValues = fourValues(horizontal, compactable);
var verticalValues = fourValues(vertical, compactable);
if (horizontalValues.length == verticalValues.length &&
horizontalValues[0][1] == verticalValues[0][1] &&
(horizontalValues.length > 1 ? horizontalValues[1][1] == verticalValues[1][1] : true) &&
(horizontalValues.length > 2 ? horizontalValues[2][1] == verticalValues[2][1] : true) &&
(horizontalValues.length > 3 ? horizontalValues[3][1] == verticalValues[3][1] : true)) {
if (
horizontalValues.length == verticalValues.length &&
horizontalValues[0][1] == verticalValues[0][1] &&
(horizontalValues.length > 1 ?
horizontalValues[1][1] == verticalValues[1][1]
: true) &&
(horizontalValues.length > 2 ?
horizontalValues[2][1] == verticalValues[2][1]
: true) &&
(horizontalValues.length > 3 ?
horizontalValues[3][1] == verticalValues[3][1]
: true)
) {
return horizontalValues;
} else {
return horizontalValues.concat([[Token.PROPERTY_VALUE, Marker.FORWARD_SLASH]]).concat(verticalValues);
return horizontalValues
.concat([[Token.PROPERTY_VALUE, Marker.FORWARD_SLASH]])
.concat(verticalValues);
}
} else {
return fourValues(property, compactable);
@ -143,7 +180,9 @@ function font(property, compactable) {
var fontFamilyIndex = 0;
if (property.value[0][1].indexOf(Marker.INTERNAL) === 0) {
property.value[0][1] = property.value[0][1].substring(Marker.INTERNAL.length);
property.value[0][1] = property.value[0][1].substring(
Marker.INTERNAL.length
);
return property.value;
}
@ -163,8 +202,13 @@ function font(property, compactable) {
componentIndex++;
// then may come line-height
if (components[componentIndex].value[0][1] != compactable[components[componentIndex].name].defaultValue) {
Array.prototype.push.apply(restored, [[Token.PROPERTY_VALUE, Marker.FORWARD_SLASH]]);
if (
components[componentIndex].value[0][1] !=
compactable[components[componentIndex].name].defaultValue
) {
Array.prototype.push.apply(restored, [
[Token.PROPERTY_VALUE, Marker.FORWARD_SLASH],
]);
Array.prototype.push.apply(restored, components[componentIndex].value);
}
@ -195,7 +239,11 @@ function fourValues(property) {
var value3 = components[2].value[0];
var value4 = components[3].value[0];
if (value1[1] == value2[1] && value1[1] == value3[1] && value1[1] == value4[1]) {
if (
value1[1] == value2[1] &&
value1[1] == value3[1] &&
value1[1] == value4[1]
) {
return [value1];
} else if (value1[1] == value3[1] && value2[1] == value4[1]) {
return [value1, value2];
@ -208,8 +256,7 @@ function fourValues(property) {
function multiplex(restoreWith) {
return function (property, compactable) {
if (!property.multiplex)
return restoreWith(property, compactable, true);
if (!property.multiplex) return restoreWith(property, compactable, true);
var multiplexSize = 0;
var restored = [];
@ -218,8 +265,7 @@ function multiplex(restoreWith) {
// At this point we don't know what's the multiplex size, e.g. how many background layers are there
for (i = 0, l = property.components[0].value.length; i < l; i++) {
if (property.components[0].value[i][1] == Marker.COMMA)
multiplexSize++;
if (property.components[0].value[i][1] == Marker.COMMA) multiplexSize++;
}
for (i = 0; i <= multiplexSize; i++) {
@ -233,7 +279,12 @@ function multiplex(restoreWith) {
// The trick is some properties has more than one value, so we iterate over values looking for
// a multiplex separator - a comma
for (var k = componentMultiplexSoFar[_component.name] || 0, n = componentToClone.value.length; k < n; k++) {
for (
var k = componentMultiplexSoFar[_component.name] || 0,
n = componentToClone.value.length;
k < n;
k++
) {
if (componentToClone.value[k][1] == Marker.COMMA) {
componentMultiplexSoFar[_component.name] = k + 1;
break;
@ -264,16 +315,22 @@ function withoutDefaults(property, compactable) {
var component = components[i];
var descriptor = compactable[component.name];
if (component.value[0][1] != descriptor.defaultValue || ('keepUnlessDefault' in descriptor) && !isDefault(components, compactable, descriptor.keepUnlessDefault)) {
if (
component.value[0][1] != descriptor.defaultValue ||
('keepUnlessDefault' in descriptor &&
!isDefault(components, compactable, descriptor.keepUnlessDefault))
) {
restored.unshift(component.value[0]);
}
}
if (restored.length === 0)
restored.push([Token.PROPERTY_VALUE, compactable[property.name].defaultValue]);
restored.push([
Token.PROPERTY_VALUE,
compactable[property.name].defaultValue,
]);
if (isInheritOnly(restored))
return [restored[0]];
if (isInheritOnly(restored)) return [restored[0]];
return restored;
}
@ -285,7 +342,10 @@ function isDefault(components, compactable, propertyName) {
for (i = 0, l = components.length; i < l; i++) {
component = components[i];
if (component.name == propertyName && component.value[0][1] == compactable[propertyName].defaultValue) {
if (
component.name == propertyName &&
component.value[0][1] == compactable[propertyName].defaultValue
) {
return true;
}
}
@ -299,5 +359,5 @@ module.exports = {
font: font,
fourValues: fourValues,
multiplex: multiplex,
withoutDefaults: withoutDefaults
withoutDefaults: withoutDefaults,
};

View File

@ -23,10 +23,13 @@ function cloneAndMergeSelectors(propertyA, propertyB) {
function restructure(tokens, context) {
var options = context.options;
var mergeablePseudoClasses = options.compatibility.selectors.mergeablePseudoClasses;
var mergeablePseudoElements = options.compatibility.selectors.mergeablePseudoElements;
var mergeablePseudoClasses =
options.compatibility.selectors.mergeablePseudoClasses;
var mergeablePseudoElements =
options.compatibility.selectors.mergeablePseudoElements;
var mergeLimit = options.compatibility.selectors.mergeLimit;
var multiplePseudoMerging = options.compatibility.selectors.multiplePseudoMerging;
var multiplePseudoMerging =
options.compatibility.selectors.multiplePseudoMerging;
var specificityCache = context.cache.specificity;
var movableTokens = {};
var movedProperties = [];
@ -40,7 +43,10 @@ function restructure(tokens, context) {
var fit = allFits[i][0];
var id = addToCache(movedProperty, fit);
if (multiPropertyMoveCache[id].length > 1 && processMultiPropertyMove(position, multiPropertyMoveCache[id])) {
if (
multiPropertyMoveCache[id].length > 1 &&
processMultiPropertyMove(position, multiPropertyMoveCache[id])
) {
removeAllMatchingFromCache(id);
break;
}
@ -87,18 +93,26 @@ function restructure(tokens, context) {
var mergeableTokens = [];
for (var i = sourceTokens.length - 1; i >= 0; i--) {
if (!isMergeable(serializeRules(sourceTokens[i][1]), mergeablePseudoClasses, mergeablePseudoElements, multiplePseudoMerging)) {
if (
!isMergeable(
serializeRules(sourceTokens[i][1]),
mergeablePseudoClasses,
mergeablePseudoElements,
multiplePseudoMerging
)
) {
continue;
}
mergeableTokens.unshift(sourceTokens[i]);
if (sourceTokens[i][2].length > 0 && uniqueTokensWithBody.indexOf(sourceTokens[i]) == -1)
if (
sourceTokens[i][2].length > 0 &&
uniqueTokensWithBody.indexOf(sourceTokens[i]) == -1
)
uniqueTokensWithBody.push(sourceTokens[i]);
}
return uniqueTokensWithBody.length > 1 ?
mergeableTokens :
[];
return uniqueTokensWithBody.length > 1 ? mergeableTokens : [];
}
function shortenIfPossible(position, movedProperty) {
@ -110,15 +124,14 @@ function restructure(tokens, context) {
var qualifiedTokens = [];
var mergeableTokens = tokensToMerge(movableTokens[key]);
if (mergeableTokens.length < 2)
return;
if (mergeableTokens.length < 2) return;
var allFits = findAllFits(mergeableTokens, valueSize, 1);
var bestFit = allFits[0];
if (bestFit[1] > 0)
return sendToMultiPropertyMoveCache(position, movedProperty, allFits);
for (var i = bestFit[0].length - 1; i >=0; i--) {
for (var i = bestFit[0].length - 1; i >= 0; i--) {
allSelectors = bestFit[0][i][1].concat(allSelectors);
qualifiedTokens.unshift(bestFit[0][i]);
}
@ -128,21 +141,42 @@ function restructure(tokens, context) {
}
function fitSorter(fit1, fit2) {
return fit1[1] > fit2[1] ? 1 : (fit1[1] == fit2[1] ? 0 : -1);
return (
fit1[1] > fit2[1] ? 1
: fit1[1] == fit2[1] ? 0
: -1
);
}
function findAllFits(mergeableTokens, propertySize, propertiesCount) {
var combinations = allCombinations(mergeableTokens, propertySize, propertiesCount, maxCombinationsLevel - 1);
var combinations = allCombinations(
mergeableTokens,
propertySize,
propertiesCount,
maxCombinationsLevel - 1
);
return combinations.sort(fitSorter);
}
function allCombinations(tokensVariant, propertySize, propertiesCount, level) {
var differenceVariants = [[tokensVariant, sizeDifference(tokensVariant, propertySize, propertiesCount)]];
function allCombinations(
tokensVariant,
propertySize,
propertiesCount,
level
) {
var differenceVariants = [
[
tokensVariant,
sizeDifference(tokensVariant, propertySize, propertiesCount),
],
];
if (tokensVariant.length > 2 && level > 0) {
for (var i = tokensVariant.length - 1; i >= 0; i--) {
var subVariant = Array.prototype.slice.call(tokensVariant, 0);
subVariant.splice(i, 1);
differenceVariants = differenceVariants.concat(allCombinations(subVariant, propertySize, propertiesCount, level - 1));
differenceVariants = differenceVariants.concat(
allCombinations(subVariant, propertySize, propertiesCount, level - 1)
);
}
}
@ -152,12 +186,20 @@ function restructure(tokens, context) {
function sizeDifference(tokensVariant, propertySize, propertiesCount) {
var allSelectorsSize = 0;
for (var i = tokensVariant.length - 1; i >= 0; i--) {
allSelectorsSize += tokensVariant[i][2].length > propertiesCount ? serializeRules(tokensVariant[i][1]).length : -1;
allSelectorsSize +=
tokensVariant[i][2].length > propertiesCount ?
serializeRules(tokensVariant[i][1]).length
: -1;
}
return allSelectorsSize - (tokensVariant.length - 1) * propertySize + 1;
}
function dropAsNewTokenAt(position, properties, allSelectors, mergeableTokens) {
function dropAsNewTokenAt(
position,
properties,
allSelectors,
mergeableTokens
) {
var i, j, k, m;
var allProperties = [];
@ -173,7 +215,10 @@ function restructure(tokens, context) {
var mergeablePropertyName = mergeableProperty[1][1];
var propertyName = property[0];
var propertyBody = property[4];
if (mergeablePropertyName == propertyName && serializeBody([mergeableProperty]) == propertyBody) {
if (
mergeablePropertyName == propertyName &&
serializeBody([mergeableProperty]) == propertyBody
) {
mergeableToken[2].splice(j, 1);
break;
}
@ -206,28 +251,27 @@ function restructure(tokens, context) {
var j, k;
var mergeableTokens = tokensToMerge(movableTokens[key]);
if (mergeableTokens.length < 2)
return;
if (mergeableTokens.length < 2) return;
movableLoop:
for (var value in movableTokens) {
movableLoop: for (var value in movableTokens) {
var tokensList = movableTokens[value];
for (j = mergeableTokens.length - 1; j >= 0; j--) {
if (tokensList.indexOf(mergeableTokens[j]) == -1)
continue movableLoop;
if (tokensList.indexOf(mergeableTokens[j]) == -1) continue movableLoop;
}
candidates.push(value);
}
if (candidates.length < 2)
return false;
if (candidates.length < 2) return false;
for (j = candidates.length - 1; j >= 0; j--) {
for (k = movedProperties.length - 1; k >= 0; k--) {
if (movedProperties[k][4] == candidates[j]) {
propertiesAndMergableTokens.unshift([movedProperties[k], mergeableTokens]);
propertiesAndMergableTokens.unshift([
movedProperties[k],
mergeableTokens,
]);
break;
}
}
@ -251,8 +295,7 @@ function restructure(tokens, context) {
var mergeableTokens = propertiesAndMergableTokens[0][1];
var bestFit = findAllFits(mergeableTokens, valueSize, properties.length)[0];
if (bestFit[1] > 0)
return false;
if (bestFit[1] > 0) return false;
var allSelectors = [];
var qualifiedTokens = [];
@ -277,11 +320,14 @@ function restructure(tokens, context) {
return true;
}
function boundToAnotherPropertyInCurrrentToken(property, movedProperty, token) {
function boundToAnotherPropertyInCurrrentToken(
property,
movedProperty,
token
) {
var propertyName = property[0];
var movedPropertyName = movedProperty[0];
if (propertyName != movedPropertyName)
return false;
if (propertyName != movedPropertyName) return false;
var key = movedProperty[4];
var toMove = movableTokens[key];
@ -325,8 +371,17 @@ function restructure(tokens, context) {
for (k = 0; k < movedCount; k++) {
var movedProperty = movedProperties[k];
if (movedToBeDropped.indexOf(k) == -1 && (!canReorderSingle(property, movedProperty, specificityCache) && !boundToAnotherPropertyInCurrrentToken(property, movedProperty, token) ||
movableTokens[movedProperty[4]] && movableTokens[movedProperty[4]].length === mergeLimit)) {
if (
movedToBeDropped.indexOf(k) == -1 &&
((!canReorderSingle(property, movedProperty, specificityCache) &&
!boundToAnotherPropertyInCurrrentToken(
property,
movedProperty,
token
)) ||
(movableTokens[movedProperty[4]] &&
movableTokens[movedProperty[4]].length === mergeLimit))
) {
dropPropertiesAt(i + 1, movedProperty, token);
if (movedToBeDropped.indexOf(k) == -1) {
@ -336,7 +391,8 @@ function restructure(tokens, context) {
}
if (!movedSameProperty) {
movedSameProperty = property[0] == movedProperty[0] && property[1] == movedProperty[1];
movedSameProperty =
property[0] == movedProperty[0] && property[1] == movedProperty[1];
if (movedSameProperty) {
samePropertyAt = k;
@ -344,12 +400,15 @@ function restructure(tokens, context) {
}
}
if (!isRule || unmovableInCurrentToken.indexOf(j) > -1)
continue;
if (!isRule || unmovableInCurrentToken.indexOf(j) > -1) continue;
var key = property[4];
if (movedSameProperty && movedProperties[samePropertyAt][5].length + property[5].length > mergeLimit) {
if (
movedSameProperty &&
movedProperties[samePropertyAt][5].length + property[5].length >
mergeLimit
) {
dropPropertiesAt(i + 1, movedProperties[samePropertyAt]);
movedProperties.splice(samePropertyAt, 1);
movableTokens[key] = [token];
@ -360,7 +419,10 @@ function restructure(tokens, context) {
}
if (movedSameProperty) {
movedProperties[samePropertyAt] = cloneAndMergeSelectors(movedProperties[samePropertyAt], property);
movedProperties[samePropertyAt] = cloneAndMergeSelectors(
movedProperties[samePropertyAt],
property
);
} else {
movedProperties.push(property);
}
@ -373,12 +435,20 @@ function restructure(tokens, context) {
}
}
var position = tokens[0] && tokens[0][0] == Token.AT_RULE && tokens[0][1].indexOf('@charset') === 0 ? 1 : 0;
var position =
(
tokens[0] &&
tokens[0][0] == Token.AT_RULE &&
tokens[0][1].indexOf('@charset') === 0
) ?
1
: 0;
for (; position < tokens.length - 1; position++) {
var isImportRule = tokens[position][0] === Token.AT_RULE && tokens[position][1].indexOf('@import') === 0;
var isImportRule =
tokens[position][0] === Token.AT_RULE &&
tokens[position][1].indexOf('@import') === 0;
var isComment = tokens[position][0] === Token.COMMENT;
if (!(isImportRule || isComment))
break;
if (!(isImportRule || isComment)) break;
}
for (i = 0; i < movedProperties.length; i++) {

View File

@ -12,7 +12,11 @@ function specificitiesOverlap(selector1, selector2, cache) {
for (j = 0, m = selector2.length; j < m; j++) {
specificity2 = findSpecificity(selector2[j][1], cache);
if (specificity1[0] === specificity2[0] && specificity1[1] === specificity2[1] && specificity1[2] === specificity2[2]) {
if (
specificity1[0] === specificity2[0] &&
specificity1[1] === specificity2[1] &&
specificity1[2] === specificity2[2]
) {
return true;
}
}

View File

@ -6,7 +6,7 @@ var Selector = {
DOT: '.',
HASH: '#',
NON_ADJACENT_SIBLING: '~',
PSEUDO: ':'
PSEUDO: ':',
};
var LETTER_PATTERN = /[a-zA-Z]/;
@ -30,13 +30,29 @@ function specificity(selector) {
if (isEscaped) {
// noop
} else if (character == Marker.SINGLE_QUOTE && !isDoubleQuoted && !isSingleQuoted) {
} else if (
character == Marker.SINGLE_QUOTE &&
!isDoubleQuoted &&
!isSingleQuoted
) {
isSingleQuoted = true;
} else if (character == Marker.SINGLE_QUOTE && !isDoubleQuoted && isSingleQuoted) {
} else if (
character == Marker.SINGLE_QUOTE &&
!isDoubleQuoted &&
isSingleQuoted
) {
isSingleQuoted = false;
} else if (character == Marker.DOUBLE_QUOTE && !isDoubleQuoted && !isSingleQuoted) {
} else if (
character == Marker.DOUBLE_QUOTE &&
!isDoubleQuoted &&
!isSingleQuoted
) {
isDoubleQuoted = true;
} else if (character == Marker.DOUBLE_QUOTE && isDoubleQuoted && !isSingleQuoted) {
} else if (
character == Marker.DOUBLE_QUOTE &&
isDoubleQuoted &&
!isSingleQuoted
) {
isDoubleQuoted = false;
} else if (isSingleQuoted || isDoubleQuoted) {
continue;
@ -44,27 +60,41 @@ function specificity(selector) {
// noop
} else if (character == Marker.OPEN_ROUND_BRACKET) {
roundBracketLevel++;
} else if (character == Marker.CLOSE_ROUND_BRACKET && roundBracketLevel == 1) {
} else if (
character == Marker.CLOSE_ROUND_BRACKET &&
roundBracketLevel == 1
) {
roundBracketLevel--;
withinNotPseudoClass = false;
} else if (character == Marker.CLOSE_ROUND_BRACKET) {
roundBracketLevel--;
} else if (character == Selector.HASH) {
result[0]++;
} else if (character == Selector.DOT || character == Marker.OPEN_SQUARE_BRACKET) {
} else if (
character == Selector.DOT ||
character == Marker.OPEN_SQUARE_BRACKET
) {
result[1]++;
} else if (character == Selector.PSEUDO && !wasPseudoClass && !isNotPseudoClass(selector, i)) {
} else if (
character == Selector.PSEUDO &&
!wasPseudoClass &&
!isNotPseudoClass(selector, i)
) {
result[1]++;
withinNotPseudoClass = false;
} else if (character == Selector.PSEUDO) {
withinNotPseudoClass = true;
} else if ((i === 0 || couldIntroduceNewTypeSelector) && LETTER_PATTERN.test(character)) {
} else if (
(i === 0 || couldIntroduceNewTypeSelector) &&
LETTER_PATTERN.test(character)
) {
result[2]++;
}
isEscaped = character == Marker.BACK_SLASH;
wasPseudoClass = character == Selector.PSEUDO;
couldIntroduceNewTypeSelector = !isEscaped && SEPARATOR_PATTERN.test(character);
couldIntroduceNewTypeSelector =
!isEscaped && SEPARATOR_PATTERN.test(character);
}
return result;

View File

@ -60,7 +60,8 @@ function restoreHack(property) {
} else if (property.hack[0] == Hack.ASTERISK) {
property.name = ASTERISK_HACK + property.name;
} else if (property.hack[0] == Hack.BACKSLASH) {
property.value[property.value.length - 1][1] += BACKSLASH_HACK + property.hack[1];
property.value[property.value.length - 1][1] +=
BACKSLASH_HACK + property.hack[1];
} else if (property.hack[0] == Hack.BANG) {
property.value[property.value.length - 1][1] += Marker.SPACE + BANG_HACK;
}

View File

@ -1,16 +1,25 @@
var functionNoVendorRegexStr = '[A-Z]+(\\-|[A-Z]|[0-9])+\\(.*?\\)';
var functionVendorRegexStr = '\\-(\\-|[A-Z]|[0-9])+\\(.*?\\)';
var variableRegexStr = 'var\\(\\-\\-[^\\)]+\\)';
var functionAnyRegexStr = '(' + variableRegexStr + '|' + functionNoVendorRegexStr + '|' + functionVendorRegexStr + ')';
var functionAnyRegexStr =
'(' +
variableRegexStr +
'|' +
functionNoVendorRegexStr +
'|' +
functionVendorRegexStr +
')';
var calcRegex = new RegExp('^(\\-moz\\-|\\-webkit\\-)?calc\\([^\\)]+\\)$', 'i');
var decimalRegex = /[0-9]/;
var functionAnyRegex = new RegExp('^' + functionAnyRegexStr + '$', 'i');
var hslColorRegex = /^hsl\(\s{0,31}[\-\.]?\d+\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+%\s{0,31}\)|hsla\(\s{0,31}[\-\.]?\d+\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+\s{0,31}\)$/i;
var hslColorRegex =
/^hsl\(\s{0,31}[\-\.]?\d+\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+%\s{0,31}\)|hsla\(\s{0,31}[\-\.]?\d+\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+%\s{0,31},\s{0,31}\.?\d+\s{0,31}\)$/i;
var identifierRegex = /^(\-[a-z0-9_][a-z0-9\-_]*|[a-z][a-z0-9\-_]*)$/i;
var namedEntityRegex = /^[a-z]+$/i;
var prefixRegex = /^-([a-z0-9]|-)*$/i;
var rgbColorRegex = /^rgb\(\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31}\)|rgba\(\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\.\d]+\s{0,31}\)$/i;
var rgbColorRegex =
/^rgb\(\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31}\)|rgba\(\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\d]{1,3}\s{0,31},\s{0,31}[\.\d]+\s{0,31}\)$/i;
var timingFunctionRegex = /^(cubic\-bezier|steps)\([^\)]+\)$/;
var validTimeUnits = ['ms', 's'];
var urlRegex = /^url\([\s\S]+\)$/i;
@ -26,11 +35,7 @@ var MINUS_SIGN = '-';
var PLUS_SIGN = '+';
var Keywords = {
'^': [
'inherit',
'initial',
'unset'
],
'^': ['inherit', 'initial', 'unset'],
'*-style': [
'auto',
'dashed',
@ -42,7 +47,7 @@ var Keywords = {
'none',
'outset',
'ridge',
'solid'
'solid',
],
'*-timing-function': [
'ease',
@ -51,56 +56,28 @@ var Keywords = {
'ease-out',
'linear',
'step-end',
'step-start'
'step-start',
],
'animation-direction': [
'alternate',
'alternate-reverse',
'normal',
'reverse'
],
'animation-fill-mode': [
'backwards',
'both',
'forwards',
'none'
],
'animation-iteration-count': [
'infinite'
],
'animation-name': [
'none'
],
'animation-play-state': [
'paused',
'running'
],
'background-attachment': [
'fixed',
'inherit',
'local',
'scroll'
'reverse',
],
'animation-fill-mode': ['backwards', 'both', 'forwards', 'none'],
'animation-iteration-count': ['infinite'],
'animation-name': ['none'],
'animation-play-state': ['paused', 'running'],
'background-attachment': ['fixed', 'inherit', 'local', 'scroll'],
'background-clip': [
'border-box',
'content-box',
'inherit',
'padding-box',
'text'
],
'background-origin': [
'border-box',
'content-box',
'inherit',
'padding-box'
],
'background-position': [
'bottom',
'center',
'left',
'right',
'top'
'text',
],
'background-origin': ['border-box', 'content-box', 'inherit', 'padding-box'],
'background-position': ['bottom', 'center', 'left', 'right', 'top'],
'background-repeat': [
'no-repeat',
'inherit',
@ -108,31 +85,14 @@ var Keywords = {
'repeat-x',
'repeat-y',
'round',
'space'
'space',
],
'background-size': [
'auto',
'cover',
'contain'
],
'border-collapse': [
'collapse',
'inherit',
'separate'
],
'bottom': [
'auto'
],
'clear': [
'both',
'left',
'none',
'right'
],
'color': [
'transparent'
],
'cursor': [
'background-size': ['auto', 'cover', 'contain'],
'border-collapse': ['collapse', 'inherit', 'separate'],
bottom: ['auto'],
clear: ['both', 'left', 'none', 'right'],
color: ['transparent'],
cursor: [
'all-scroll',
'auto',
'col-resize',
@ -155,9 +115,9 @@ var Keywords = {
'text',
'vertical-text',
'w-resize',
'wait'
'wait',
],
'display': [
display: [
'block',
'inline',
'inline-block',
@ -172,24 +132,18 @@ var Keywords = {
'table-footer-group',
'table-header-group',
'table-row',
'table-row-group'
'table-row-group',
],
'float': [
'left',
'none',
'right'
],
'left': [
'auto'
],
'font': [
float: ['left', 'none', 'right'],
left: ['auto'],
font: [
'caption',
'icon',
'menu',
'message-box',
'small-caption',
'status-bar',
'unset'
'unset',
],
'font-size': [
'large',
@ -200,7 +154,7 @@ var Keywords = {
'x-large',
'x-small',
'xx-large',
'xx-small'
'xx-small',
],
'font-stretch': [
'condensed',
@ -211,17 +165,10 @@ var Keywords = {
'semi-condensed',
'semi-expanded',
'ultra-condensed',
'ultra-expanded'
],
'font-style': [
'italic',
'normal',
'oblique'
],
'font-variant': [
'normal',
'small-caps'
'ultra-expanded',
],
'font-style': ['italic', 'normal', 'oblique'],
'font-variant': ['normal', 'small-caps'],
'font-weight': [
'100',
'200',
@ -235,15 +182,10 @@ var Keywords = {
'bold',
'bolder',
'lighter',
'normal'
],
'line-height': [
'normal'
],
'list-style-position': [
'inside',
'outside'
'normal',
],
'line-height': ['normal'],
'list-style-position': ['inside', 'outside'],
'list-style-type': [
'armenian',
'circle',
@ -260,43 +202,21 @@ var Keywords = {
'square',
'upper-alpha',
'upper-latin',
'upper-roman'
],
'overflow': [
'auto',
'hidden',
'scroll',
'visible'
],
'position': [
'absolute',
'fixed',
'relative',
'static'
],
'right': [
'auto'
'upper-roman',
],
overflow: ['auto', 'hidden', 'scroll', 'visible'],
position: ['absolute', 'fixed', 'relative', 'static'],
right: ['auto'],
'text-align': [
'center',
'justify',
'left',
'left|right', // this is the default value of list-style-type, see comment in compactable.js
'right'
],
'text-decoration': [
'line-through',
'none',
'overline',
'underline'
],
'text-overflow': [
'clip',
'ellipsis'
],
'top': [
'auto'
'right',
],
'text-decoration': ['line-through', 'none', 'overline', 'underline'],
'text-overflow': ['clip', 'ellipsis'],
top: ['auto'],
'vertical-align': [
'baseline',
'bottom',
@ -305,25 +225,11 @@ var Keywords = {
'super',
'text-bottom',
'text-top',
'top'
'top',
],
'visibility': [
'collapse',
'hidden',
'visible'
],
'white-space': [
'normal',
'nowrap',
'pre'
],
'width': [
'inherit',
'initial',
'medium',
'thick',
'thin'
]
visibility: ['collapse', 'hidden', 'visible'],
'white-space': ['normal', 'nowrap', 'pre'],
width: ['inherit', 'initial', 'medium', 'thick', 'thin'],
};
var Units = [
@ -342,17 +248,17 @@ var Units = [
'vm',
'vmax',
'vmin',
'vw'
'vw',
];
function isColor(value) {
return value != 'auto' &&
(
isKeyword('color')(value) ||
return (
value != 'auto' &&
(isKeyword('color')(value) ||
isHexColor(value) ||
isColorFunction(value) ||
isNamedEntity(value)
);
isNamedEntity(value))
);
}
function isColorFunction(value) {
@ -368,7 +274,12 @@ function isFunction(value) {
}
function isHexColor(value) {
return threeValueColorRegex.test(value) || fourValueColorRegex.test(value) || sixValueColorRegex.test(value) || eightValueColorRegex.test(value);
return (
threeValueColorRegex.test(value) ||
fourValueColorRegex.test(value) ||
sixValueColorRegex.test(value) ||
eightValueColorRegex.test(value)
);
}
function isHslColor(value) {
@ -384,7 +295,7 @@ function isImage(value) {
}
function isKeyword(propertyName) {
return function(value) {
return function (value) {
return Keywords[propertyName].indexOf(value) > -1;
};
}
@ -406,8 +317,7 @@ function isPrefixed(value) {
}
function isPositiveNumber(value) {
return isNumber(value) &&
parseFloat(value) >= 0;
return isNumber(value) && parseFloat(value) >= 0;
}
function isVariable(value) {
@ -417,8 +327,11 @@ function isVariable(value) {
function isTime(value) {
var numberUpTo = scanForNumber(value);
return numberUpTo == value.length && parseInt(value) === 0 ||
numberUpTo > -1 && validTimeUnits.indexOf(value.slice(numberUpTo + 1)) > -1;
return (
(numberUpTo == value.length && parseInt(value) === 0) ||
(numberUpTo > -1 &&
validTimeUnits.indexOf(value.slice(numberUpTo + 1)) > -1)
);
}
function isTimingFunction() {
@ -432,10 +345,12 @@ function isTimingFunction() {
function isUnit(validUnits, value) {
var numberUpTo = scanForNumber(value);
return numberUpTo == value.length && parseInt(value) === 0 ||
numberUpTo > -1 && validUnits.indexOf(value.slice(numberUpTo + 1)) > -1 ||
return (
(numberUpTo == value.length && parseInt(value) === 0) ||
(numberUpTo > -1 && validUnits.indexOf(value.slice(numberUpTo + 1)) > -1) ||
value == 'auto' ||
value == 'inherit';
value == 'inherit'
);
}
function isUrl(value) {
@ -443,9 +358,7 @@ function isUrl(value) {
}
function isZIndex(value) {
return value == 'auto' ||
isNumber(value) ||
isKeyword('^')(value);
return value == 'auto' || isNumber(value) || isKeyword('^')(value);
}
function scanForNumber(value) {
@ -459,7 +372,11 @@ function scanForNumber(value) {
if (i === 0 && (character == PLUS_SIGN || character == MINUS_SIGN)) {
hasSign = true;
} else if (i > 0 && hasSign && (character == PLUS_SIGN || character == MINUS_SIGN)) {
} else if (
i > 0 &&
hasSign &&
(character == PLUS_SIGN || character == MINUS_SIGN)
) {
return i - 1;
} else if (character == DECIMAL_DOT && !hasDot) {
hasDot = true;
@ -477,7 +394,9 @@ function scanForNumber(value) {
function validator(compatibility) {
var validUnits = Units.slice(0).filter(function (value) {
return !(value in compatibility.units) || compatibility.units[value] === true;
return (
!(value in compatibility.units) || compatibility.units[value] === true
);
});
return {
@ -522,7 +441,7 @@ function validator(compatibility) {
isUrl: isUrl,
isVariable: isVariable,
isWidth: isKeyword('width'),
isZIndex: isZIndex
isZIndex: isZIndex,
};
}

View File

@ -14,7 +14,7 @@ var Match = {
IMPORTANT_WORD_PATTERN: new RegExp('important$', 'i'),
SUFFIX_BANG_PATTERN: /!$/,
UNDERSCORE: '_',
VARIABLE_REFERENCE_PATTERN: /var\(--.+\)$/
VARIABLE_REFERENCE_PATTERN: /var\(--.+\)$/,
};
function wrapAll(properties, includeVariable, skipProperties) {
@ -78,7 +78,10 @@ function isMultiplex(property) {
for (i = 3, l = property.length; i < l; i++) {
value = property[i];
if (value[0] == Token.PROPERTY_VALUE && (value[1] == Marker.COMMA || value[1] == Marker.FORWARD_SLASH)) {
if (
value[0] == Token.PROPERTY_VALUE &&
(value[1] == Marker.COMMA || value[1] == Marker.FORWARD_SLASH)
) {
return true;
}
}
@ -95,13 +98,30 @@ function hackFrom(property) {
match = [Hack.UNDERSCORE];
} else if (name[0] == Match.ASTERISK) {
match = [Hack.ASTERISK];
} else if (lastValue[1][0] == Match.BANG && !lastValue[1].match(Match.IMPORTANT_WORD_PATTERN)) {
} else if (
lastValue[1][0] == Match.BANG &&
!lastValue[1].match(Match.IMPORTANT_WORD_PATTERN)
) {
match = [Hack.BANG];
} else if (lastValue[1].indexOf(Match.BANG) > 0 && !lastValue[1].match(Match.IMPORTANT_WORD_PATTERN) && Match.BANG_SUFFIX_PATTERN.test(lastValue[1])) {
} else if (
lastValue[1].indexOf(Match.BANG) > 0 &&
!lastValue[1].match(Match.IMPORTANT_WORD_PATTERN) &&
Match.BANG_SUFFIX_PATTERN.test(lastValue[1])
) {
match = [Hack.BANG];
} else if (lastValue[1].indexOf(Match.BACKSLASH) > 0 && lastValue[1].indexOf(Match.BACKSLASH) == lastValue[1].length - Match.BACKSLASH.length - 1) {
match = [Hack.BACKSLASH, lastValue[1].substring(lastValue[1].indexOf(Match.BACKSLASH) + 1)];
} else if (lastValue[1].indexOf(Match.BACKSLASH) === 0 && lastValue[1].length == 2) {
} else if (
lastValue[1].indexOf(Match.BACKSLASH) > 0 &&
lastValue[1].indexOf(Match.BACKSLASH) ==
lastValue[1].length - Match.BACKSLASH.length - 1
) {
match = [
Hack.BACKSLASH,
lastValue[1].substring(lastValue[1].indexOf(Match.BACKSLASH) + 1),
];
} else if (
lastValue[1].indexOf(Match.BACKSLASH) === 0 &&
lastValue[1].length == 2
) {
match = [Hack.BACKSLASH, lastValue[1].substring(1)];
}
@ -109,13 +129,15 @@ function hackFrom(property) {
}
function isImportant(property) {
if (property.length < 3)
return false;
if (property.length < 3) return false;
var lastValue = property[property.length - 1];
if (Match.IMPORTANT_TOKEN_PATTERN.test(lastValue[1])) {
return true;
} else if (Match.IMPORTANT_WORD_PATTERN.test(lastValue[1]) && Match.SUFFIX_BANG_PATTERN.test(property[property.length - 2][1])) {
} else if (
Match.IMPORTANT_WORD_PATTERN.test(lastValue[1]) &&
Match.SUFFIX_BANG_PATTERN.test(property[property.length - 2][1])
) {
return true;
}
@ -130,7 +152,10 @@ function stripImportant(property) {
lastValue[1] = lastValue[1].replace(Match.IMPORTANT_TOKEN_PATTERN, '');
} else {
lastValue[1] = lastValue[1].replace(Match.IMPORTANT_WORD_PATTERN, '');
oneButLastValue[1] = oneButLastValue[1].replace(Match.SUFFIX_BANG_PATTERN, '');
oneButLastValue[1] = oneButLastValue[1].replace(
Match.SUFFIX_BANG_PATTERN,
''
);
}
if (lastValue[1].length === 0) {
@ -149,7 +174,12 @@ function stripPrefixHack(property) {
function stripSuffixHack(property, hackFrom) {
var lastValue = property[property.length - 1];
lastValue[1] = lastValue[1]
.substring(0, lastValue[1].indexOf(hackFrom[0] == Hack.BACKSLASH ? Match.BACKSLASH : Match.BANG))
.substring(
0,
lastValue[1].indexOf(
hackFrom[0] == Hack.BACKSLASH ? Match.BACKSLASH : Match.BANG
)
)
.trim();
if (lastValue[1].length === 0) {
@ -181,11 +211,11 @@ function wrapSingle(property) {
position: 0,
shorthand: false,
unused: false,
value: property.slice(2)
value: property.slice(2),
};
}
module.exports = {
all: wrapAll,
single: wrapSingle
single: wrapSingle,
};