optimize.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. var shortenHex = require('./shorten-hex');
  2. var shortenHsl = require('./shorten-hsl');
  3. var shortenRgb = require('./shorten-rgb');
  4. var sortSelectors = require('./sort-selectors');
  5. var tidyRules = require('./tidy-rules');
  6. var tidyBlock = require('./tidy-block');
  7. var tidyAtRule = require('./tidy-at-rule');
  8. var Hack = require('../hack');
  9. var removeUnused = require('../remove-unused');
  10. var restoreFromOptimizing = require('../restore-from-optimizing');
  11. var wrapForOptimizing = require('../wrap-for-optimizing').all;
  12. var OptimizationLevel = require('../../options/optimization-level').OptimizationLevel;
  13. var Token = require('../../tokenizer/token');
  14. var Marker = require('../../tokenizer/marker');
  15. var formatPosition = require('../../utils/format-position');
  16. var split = require('../../utils/split');
  17. var serializeRules = require('../../writer/one-time').rules;
  18. var IgnoreProperty = 'ignore-property';
  19. var CHARSET_TOKEN = '@charset';
  20. var CHARSET_REGEXP = new RegExp('^' + CHARSET_TOKEN, 'i');
  21. var DEFAULT_ROUNDING_PRECISION = require('../../options/rounding-precision').DEFAULT;
  22. var WHOLE_PIXEL_VALUE = /(?:^|\s|\()(-?\d+)px/;
  23. var TIME_VALUE = /^(\-?[\d\.]+)(m?s)$/;
  24. var HEX_VALUE_PATTERN = /[0-9a-f]/i;
  25. var PROPERTY_NAME_PATTERN = /^(?:\-chrome\-|\-[\w\-]+\w|\w[\w\-]+\w|\-\-\S+)$/;
  26. var IMPORT_PREFIX_PATTERN = /^@import/i;
  27. var QUOTED_PATTERN = /^('.*'|".*")$/;
  28. var QUOTED_BUT_SAFE_PATTERN = /^['"][a-zA-Z][a-zA-Z\d\-_]+['"]$/;
  29. var URL_PREFIX_PATTERN = /^url\(/i;
  30. var LOCAL_PREFIX_PATTERN = /^local\(/i;
  31. var VARIABLE_NAME_PATTERN = /^--\S+$/;
  32. function isLocal(value){
  33. return LOCAL_PREFIX_PATTERN.test(value);
  34. }
  35. function isNegative(value) {
  36. return value && value[1][0] == '-' && parseFloat(value[1]) < 0;
  37. }
  38. function isQuoted(value) {
  39. return QUOTED_PATTERN.test(value);
  40. }
  41. function isUrl(value) {
  42. return URL_PREFIX_PATTERN.test(value);
  43. }
  44. function normalizeUrl(value) {
  45. return value
  46. .replace(URL_PREFIX_PATTERN, 'url(')
  47. .replace(/\\?\n|\\?\r\n/g, '');
  48. }
  49. function optimizeBackground(property) {
  50. var values = property.value;
  51. if (values.length == 1 && values[0][1] == 'none') {
  52. values[0][1] = '0 0';
  53. }
  54. if (values.length == 1 && values[0][1] == 'transparent') {
  55. values[0][1] = '0 0';
  56. }
  57. }
  58. function optimizeBorderRadius(property) {
  59. var values = property.value;
  60. var spliceAt;
  61. if (values.length == 3 && values[1][1] == '/' && values[0][1] == values[2][1]) {
  62. spliceAt = 1;
  63. } else if (values.length == 5 && values[2][1] == '/' && values[0][1] == values[3][1] && values[1][1] == values[4][1]) {
  64. spliceAt = 2;
  65. } 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]) {
  66. spliceAt = 3;
  67. } 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]) {
  68. spliceAt = 4;
  69. }
  70. if (spliceAt) {
  71. property.value.splice(spliceAt);
  72. property.dirty = true;
  73. }
  74. }
  75. /**
  76. * @param {string} name
  77. * @param {string} value
  78. * @param {Object} compatibility
  79. * @return {string}
  80. */
  81. function optimizeColors(name, value, compatibility) {
  82. if (!value.match(/#|rgb|hsl/gi)) {
  83. return shortenHex(value);
  84. }
  85. value = value
  86. .replace(/(rgb|hsl)a?\((\-?\d+),(\-?\d+\%?),(\-?\d+\%?),(0*[1-9]+[0-9]*(\.?\d*)?)\)/gi, function (match, colorFn, p1, p2, p3, alpha) {
  87. return (parseInt(alpha, 10) >= 1 ? colorFn + '(' + [p1,p2,p3].join(',') + ')' : match);
  88. })
  89. .replace(/rgb\((\-?\d+),(\-?\d+),(\-?\d+)\)/gi, function (match, red, green, blue) {
  90. return shortenRgb(red, green, blue);
  91. })
  92. .replace(/hsl\((-?\d+),(-?\d+)%?,(-?\d+)%?\)/gi, function (match, hue, saturation, lightness) {
  93. return shortenHsl(hue, saturation, lightness);
  94. })
  95. .replace(/(^|[^='"])#([0-9a-f]{6})/gi, function (match, prefix, color, at, inputValue) {
  96. var suffix = inputValue[at + match.length];
  97. if (suffix && HEX_VALUE_PATTERN.test(suffix)) {
  98. return match;
  99. } else if (color[0] == color[1] && color[2] == color[3] && color[4] == color[5]) {
  100. return (prefix + '#' + color[0] + color[2] + color[4]).toLowerCase();
  101. } else {
  102. return (prefix + '#' + color).toLowerCase();
  103. }
  104. })
  105. .replace(/(^|[^='"])#([0-9a-f]{3})/gi, function (match, prefix, color) {
  106. return prefix + '#' + color.toLowerCase();
  107. })
  108. .replace(/(rgb|rgba|hsl|hsla)\(([^\)]+)\)/gi, function (match, colorFunction, colorDef) {
  109. var tokens = colorDef.split(',');
  110. var colorFnLowercase = colorFunction && colorFunction.toLowerCase();
  111. var applies = (colorFnLowercase == 'hsl' && tokens.length == 3) ||
  112. (colorFnLowercase == 'hsla' && tokens.length == 4) ||
  113. (colorFnLowercase == 'rgb' && tokens.length === 3 && colorDef.indexOf('%') > 0) ||
  114. (colorFnLowercase == 'rgba' && tokens.length == 4 && colorDef.indexOf('%') > 0);
  115. if (!applies) {
  116. return match;
  117. }
  118. if (tokens[1].indexOf('%') == -1) {
  119. tokens[1] += '%';
  120. }
  121. if (tokens[2].indexOf('%') == -1) {
  122. tokens[2] += '%';
  123. }
  124. return colorFunction + '(' + tokens.join(',') + ')';
  125. });
  126. if (compatibility.colors.opacity && name.indexOf('background') == -1) {
  127. value = value.replace(/(?:rgba|hsla)\(0,0%?,0%?,0\)/g, function (match) {
  128. if (split(value, ',').pop().indexOf('gradient(') > -1) {
  129. return match;
  130. }
  131. return 'transparent';
  132. });
  133. }
  134. return shortenHex(value);
  135. }
  136. function optimizeFilter(property) {
  137. if (property.value.length == 1) {
  138. property.value[0][1] = property.value[0][1].replace(/progid:DXImageTransform\.Microsoft\.(Alpha|Chroma)(\W)/, function (match, filter, suffix) {
  139. return filter.toLowerCase() + suffix;
  140. });
  141. }
  142. property.value[0][1] = property.value[0][1]
  143. .replace(/,(\S)/g, ', $1')
  144. .replace(/ ?= ?/g, '=');
  145. }
  146. function optimizeFontWeight(property, atIndex) {
  147. var value = property.value[atIndex][1];
  148. if (value == 'normal') {
  149. value = '400';
  150. } else if (value == 'bold') {
  151. value = '700';
  152. }
  153. property.value[atIndex][1] = value;
  154. }
  155. function optimizeMultipleZeros(property) {
  156. var values = property.value;
  157. var spliceAt;
  158. if (values.length == 4 && values[0][1] === '0' && values[1][1] === '0' && values[2][1] === '0' && values[3][1] === '0') {
  159. if (property.name.indexOf('box-shadow') > -1) {
  160. spliceAt = 2;
  161. } else {
  162. spliceAt = 1;
  163. }
  164. }
  165. if (spliceAt) {
  166. property.value.splice(spliceAt);
  167. property.dirty = true;
  168. }
  169. }
  170. function optimizeOutline(property) {
  171. var values = property.value;
  172. if (values.length == 1 && values[0][1] == 'none') {
  173. values[0][1] = '0';
  174. }
  175. }
  176. function optimizePixelLengths(_, value, compatibility) {
  177. if (!WHOLE_PIXEL_VALUE.test(value)) {
  178. return value;
  179. }
  180. return value.replace(WHOLE_PIXEL_VALUE, function (match, val) {
  181. var newValue;
  182. var intVal = parseInt(val);
  183. if (intVal === 0) {
  184. return match;
  185. }
  186. if (compatibility.properties.shorterLengthUnits && compatibility.units.pt && intVal * 3 % 4 === 0) {
  187. newValue = intVal * 3 / 4 + 'pt';
  188. }
  189. if (compatibility.properties.shorterLengthUnits && compatibility.units.pc && intVal % 16 === 0) {
  190. newValue = intVal / 16 + 'pc';
  191. }
  192. if (compatibility.properties.shorterLengthUnits && compatibility.units.in && intVal % 96 === 0) {
  193. newValue = intVal / 96 + 'in';
  194. }
  195. if (newValue) {
  196. newValue = match.substring(0, match.indexOf(val)) + newValue;
  197. }
  198. return newValue && newValue.length < match.length ? newValue : match;
  199. });
  200. }
  201. function optimizePrecision(_, value, precisionOptions) {
  202. if (!precisionOptions.enabled || value.indexOf('.') === -1) {
  203. return value;
  204. }
  205. return value
  206. .replace(precisionOptions.decimalPointMatcher, '$1$2$3')
  207. .replace(precisionOptions.zeroMatcher, function (match, integerPart, fractionPart, unit) {
  208. var multiplier = precisionOptions.units[unit].multiplier;
  209. var parsedInteger = parseInt(integerPart);
  210. var integer = isNaN(parsedInteger) ? 0 : parsedInteger;
  211. var fraction = parseFloat(fractionPart);
  212. return Math.round((integer + fraction) * multiplier) / multiplier + unit;
  213. });
  214. }
  215. function optimizeTimeUnits(_, value) {
  216. if (!TIME_VALUE.test(value))
  217. return value;
  218. return value.replace(TIME_VALUE, function (match, val, unit) {
  219. var newValue;
  220. if (unit == 'ms') {
  221. newValue = parseInt(val) / 1000 + 's';
  222. } else if (unit == 's') {
  223. newValue = parseFloat(val) * 1000 + 'ms';
  224. }
  225. return newValue.length < match.length ? newValue : match;
  226. });
  227. }
  228. function optimizeUnits(name, value, unitsRegexp) {
  229. if (/^(?:\-moz\-calc|\-webkit\-calc|calc|rgb|hsl|rgba|hsla)\(/.test(value)) {
  230. return value;
  231. }
  232. if (name == 'flex' || name == '-ms-flex' || name == '-webkit-flex' || name == 'flex-basis' || name == '-webkit-flex-basis') {
  233. return value;
  234. }
  235. if (value.indexOf('%') > 0 && (name == 'height' || name == 'max-height' || name == 'width' || name == 'max-width')) {
  236. return value;
  237. }
  238. return value
  239. .replace(unitsRegexp, '$1' + '0' + '$2')
  240. .replace(unitsRegexp, '$1' + '0' + '$2');
  241. }
  242. function optimizeWhitespace(name, value) {
  243. if (name.indexOf('filter') > -1 || value.indexOf(' ') == -1 || value.indexOf('expression') === 0) {
  244. return value;
  245. }
  246. if (value.indexOf(Marker.SINGLE_QUOTE) > -1 || value.indexOf(Marker.DOUBLE_QUOTE) > -1) {
  247. return value;
  248. }
  249. value = value.replace(/\s+/g, ' ');
  250. if (value.indexOf('calc') > -1) {
  251. value = value.replace(/\) ?\/ ?/g, ')/ ');
  252. }
  253. return value
  254. .replace(/(\(;?)\s+/g, '$1')
  255. .replace(/\s+(;?\))/g, '$1')
  256. .replace(/, /g, ',');
  257. }
  258. function optimizeZeroDegUnit(_, value) {
  259. if (value.indexOf('0deg') == -1) {
  260. return value;
  261. }
  262. return value.replace(/\(0deg\)/g, '(0)');
  263. }
  264. function optimizeZeroUnits(name, value) {
  265. if (value.indexOf('0') == -1) {
  266. return value;
  267. }
  268. if (value.indexOf('-') > -1) {
  269. value = value
  270. .replace(/([^\w\d\-]|^)\-0([^\.]|$)/g, '$10$2')
  271. .replace(/([^\w\d\-]|^)\-0([^\.]|$)/g, '$10$2');
  272. }
  273. return value
  274. .replace(/(^|\s)0+([1-9])/g, '$1$2')
  275. .replace(/(^|\D)\.0+(\D|$)/g, '$10$2')
  276. .replace(/(^|\D)\.0+(\D|$)/g, '$10$2')
  277. .replace(/\.([1-9]*)0+(\D|$)/g, function (match, nonZeroPart, suffix) {
  278. return (nonZeroPart.length > 0 ? '.' : '') + nonZeroPart + suffix;
  279. })
  280. .replace(/(^|\D)0\.(\d)/g, '$1.$2');
  281. }
  282. function removeQuotes(name, value) {
  283. if (name == 'content' || name.indexOf('font-variation-settings') > -1 || name.indexOf('font-feature-settings') > -1 || name == 'grid' || name.indexOf('grid-') > -1) {
  284. return value;
  285. }
  286. return QUOTED_BUT_SAFE_PATTERN.test(value) ?
  287. value.substring(1, value.length - 1) :
  288. value;
  289. }
  290. function removeUrlQuotes(value) {
  291. return /^url\(['"].+['"]\)$/.test(value) && !/^url\(['"].*[\*\s\(\)'"].*['"]\)$/.test(value) && !/^url\(['"]data:[^;]+;charset/.test(value) ?
  292. value.replace(/["']/g, '') :
  293. value;
  294. }
  295. function transformValue(propertyName, propertyValue, rule, transformCallback) {
  296. var selector = serializeRules(rule);
  297. var transformedValue = transformCallback(propertyName, propertyValue, selector);
  298. if (transformedValue === undefined) {
  299. return propertyValue;
  300. } else if (transformedValue === false) {
  301. return IgnoreProperty;
  302. } else {
  303. return transformedValue;
  304. }
  305. }
  306. //
  307. function optimizeBody(rule, properties, context) {
  308. var options = context.options;
  309. var levelOptions = options.level[OptimizationLevel.One];
  310. var property, name, type, value;
  311. var valueIsUrl;
  312. var propertyToken;
  313. var _properties = wrapForOptimizing(properties, true);
  314. propertyLoop:
  315. for (var i = 0, l = _properties.length; i < l; i++) {
  316. property = _properties[i];
  317. name = property.name;
  318. if (!PROPERTY_NAME_PATTERN.test(name)) {
  319. propertyToken = property.all[property.position];
  320. context.warnings.push('Invalid property name \'' + name + '\' at ' + formatPosition(propertyToken[1][2][0]) + '. Ignoring.');
  321. property.unused = true;
  322. }
  323. if (property.value.length === 0) {
  324. propertyToken = property.all[property.position];
  325. context.warnings.push('Empty property \'' + name + '\' at ' + formatPosition(propertyToken[1][2][0]) + '. Ignoring.');
  326. property.unused = true;
  327. }
  328. if (property.hack && (
  329. (property.hack[0] == Hack.ASTERISK || property.hack[0] == Hack.UNDERSCORE) && !options.compatibility.properties.iePrefixHack ||
  330. property.hack[0] == Hack.BACKSLASH && !options.compatibility.properties.ieSuffixHack ||
  331. property.hack[0] == Hack.BANG && !options.compatibility.properties.ieBangHack)) {
  332. property.unused = true;
  333. }
  334. if (levelOptions.removeNegativePaddings && name.indexOf('padding') === 0 && (isNegative(property.value[0]) || isNegative(property.value[1]) || isNegative(property.value[2]) || isNegative(property.value[3]))) {
  335. property.unused = true;
  336. }
  337. if (!options.compatibility.properties.ieFilters && isLegacyFilter(property)) {
  338. property.unused = true;
  339. }
  340. if (property.unused) {
  341. continue;
  342. }
  343. if (property.block) {
  344. optimizeBody(rule, property.value[0][1], context);
  345. continue;
  346. }
  347. if (VARIABLE_NAME_PATTERN.test(name)) {
  348. continue;
  349. }
  350. for (var j = 0, m = property.value.length; j < m; j++) {
  351. type = property.value[j][0];
  352. value = property.value[j][1];
  353. valueIsUrl = isUrl(value);
  354. if (type == Token.PROPERTY_BLOCK) {
  355. property.unused = true;
  356. context.warnings.push('Invalid value token at ' + formatPosition(value[0][1][2][0]) + '. Ignoring.');
  357. break;
  358. }
  359. if (valueIsUrl && !context.validator.isUrl(value)) {
  360. property.unused = true;
  361. context.warnings.push('Broken URL \'' + value + '\' at ' + formatPosition(property.value[j][2][0]) + '. Ignoring.');
  362. break;
  363. }
  364. if (valueIsUrl) {
  365. value = levelOptions.normalizeUrls ?
  366. normalizeUrl(value) :
  367. value;
  368. value = !options.compatibility.properties.urlQuotes ?
  369. removeUrlQuotes(value) :
  370. value;
  371. } else if (isQuoted(value) || isLocal(value)) {
  372. value = levelOptions.removeQuotes ?
  373. removeQuotes(name, value) :
  374. value;
  375. } else {
  376. value = levelOptions.removeWhitespace ?
  377. optimizeWhitespace(name, value) :
  378. value;
  379. value = optimizePrecision(name, value, options.precision);
  380. value = optimizePixelLengths(name, value, options.compatibility);
  381. value = levelOptions.replaceTimeUnits ?
  382. optimizeTimeUnits(name, value) :
  383. value;
  384. value = levelOptions.replaceZeroUnits ?
  385. optimizeZeroUnits(name, value) :
  386. value;
  387. if (options.compatibility.properties.zeroUnits) {
  388. value = optimizeZeroDegUnit(name, value);
  389. value = optimizeUnits(name, value, options.unitsRegexp);
  390. }
  391. if (options.compatibility.properties.colors) {
  392. value = optimizeColors(name, value, options.compatibility);
  393. }
  394. }
  395. value = transformValue(name, value, rule, levelOptions.transform);
  396. if (value === IgnoreProperty) {
  397. property.unused = true;
  398. continue propertyLoop;
  399. }
  400. property.value[j][1] = value;
  401. }
  402. if (levelOptions.replaceMultipleZeros) {
  403. optimizeMultipleZeros(property);
  404. }
  405. if (name == 'background' && levelOptions.optimizeBackground) {
  406. optimizeBackground(property);
  407. } else if (name.indexOf('border') === 0 && name.indexOf('radius') > 0 && levelOptions.optimizeBorderRadius) {
  408. optimizeBorderRadius(property);
  409. } else if (name == 'filter'&& levelOptions.optimizeFilter && options.compatibility.properties.ieFilters) {
  410. optimizeFilter(property);
  411. } else if (name == 'font-weight' && levelOptions.optimizeFontWeight) {
  412. optimizeFontWeight(property, 0);
  413. } else if (name == 'outline' && levelOptions.optimizeOutline) {
  414. optimizeOutline(property);
  415. }
  416. }
  417. restoreFromOptimizing(_properties);
  418. removeUnused(_properties);
  419. removeComments(properties, options);
  420. }
  421. function removeComments(tokens, options) {
  422. var token;
  423. var i;
  424. for (i = 0; i < tokens.length; i++) {
  425. token = tokens[i];
  426. if (token[0] != Token.COMMENT) {
  427. continue;
  428. }
  429. optimizeComment(token, options);
  430. if (token[1].length === 0) {
  431. tokens.splice(i, 1);
  432. i--;
  433. }
  434. }
  435. }
  436. function optimizeComment(token, options) {
  437. if (token[1][2] == Marker.EXCLAMATION && (options.level[OptimizationLevel.One].specialComments == 'all' || options.commentsKept < options.level[OptimizationLevel.One].specialComments)) {
  438. options.commentsKept++;
  439. return;
  440. }
  441. token[1] = [];
  442. }
  443. function cleanupCharsets(tokens) {
  444. var hasCharset = false;
  445. for (var i = 0, l = tokens.length; i < l; i++) {
  446. var token = tokens[i];
  447. if (token[0] != Token.AT_RULE)
  448. continue;
  449. if (!CHARSET_REGEXP.test(token[1]))
  450. continue;
  451. if (hasCharset || token[1].indexOf(CHARSET_TOKEN) == -1) {
  452. tokens.splice(i, 1);
  453. i--;
  454. l--;
  455. } else {
  456. hasCharset = true;
  457. tokens.splice(i, 1);
  458. tokens.unshift([Token.AT_RULE, token[1].replace(CHARSET_REGEXP, CHARSET_TOKEN)]);
  459. }
  460. }
  461. }
  462. function buildUnitRegexp(options) {
  463. var units = ['px', 'em', 'ex', 'cm', 'mm', 'in', 'pt', 'pc', '%'];
  464. var otherUnits = ['ch', 'rem', 'vh', 'vm', 'vmax', 'vmin', 'vw'];
  465. otherUnits.forEach(function (unit) {
  466. if (options.compatibility.units[unit]) {
  467. units.push(unit);
  468. }
  469. });
  470. return new RegExp('(^|\\s|\\(|,)0(?:' + units.join('|') + ')(\\W|$)', 'g');
  471. }
  472. function buildPrecisionOptions(roundingPrecision) {
  473. var precisionOptions = {
  474. matcher: null,
  475. units: {},
  476. };
  477. var optimizable = [];
  478. var unit;
  479. var value;
  480. for (unit in roundingPrecision) {
  481. value = roundingPrecision[unit];
  482. if (value != DEFAULT_ROUNDING_PRECISION) {
  483. precisionOptions.units[unit] = {};
  484. precisionOptions.units[unit].value = value;
  485. precisionOptions.units[unit].multiplier = Math.pow(10, value);
  486. optimizable.push(unit);
  487. }
  488. }
  489. if (optimizable.length > 0) {
  490. precisionOptions.enabled = true;
  491. precisionOptions.decimalPointMatcher = new RegExp('(\\d)\\.($|' + optimizable.join('|') + ')($|\\W)', 'g');
  492. precisionOptions.zeroMatcher = new RegExp('(\\d*)(\\.\\d+)(' + optimizable.join('|') + ')', 'g');
  493. }
  494. return precisionOptions;
  495. }
  496. function isImport(token) {
  497. return IMPORT_PREFIX_PATTERN.test(token[1]);
  498. }
  499. function isLegacyFilter(property) {
  500. var value;
  501. if (property.name == 'filter' || property.name == '-ms-filter') {
  502. value = property.value[0][1];
  503. return value.indexOf('progid') > -1 ||
  504. value.indexOf('alpha') === 0 ||
  505. value.indexOf('chroma') === 0;
  506. } else {
  507. return false;
  508. }
  509. }
  510. function level1Optimize(tokens, context) {
  511. var options = context.options;
  512. var levelOptions = options.level[OptimizationLevel.One];
  513. var ie7Hack = options.compatibility.selectors.ie7Hack;
  514. var adjacentSpace = options.compatibility.selectors.adjacentSpace;
  515. var spaceAfterClosingBrace = options.compatibility.properties.spaceAfterClosingBrace;
  516. var format = options.format;
  517. var mayHaveCharset = false;
  518. var afterRules = false;
  519. options.unitsRegexp = options.unitsRegexp || buildUnitRegexp(options);
  520. options.precision = options.precision || buildPrecisionOptions(levelOptions.roundingPrecision);
  521. options.commentsKept = options.commentsKept || 0;
  522. for (var i = 0, l = tokens.length; i < l; i++) {
  523. var token = tokens[i];
  524. switch (token[0]) {
  525. case Token.AT_RULE:
  526. token[1] = isImport(token) && afterRules ? '' : token[1];
  527. token[1] = levelOptions.tidyAtRules ? tidyAtRule(token[1]) : token[1];
  528. mayHaveCharset = true;
  529. break;
  530. case Token.AT_RULE_BLOCK:
  531. optimizeBody(token[1], token[2], context);
  532. afterRules = true;
  533. break;
  534. case Token.NESTED_BLOCK:
  535. token[1] = levelOptions.tidyBlockScopes ? tidyBlock(token[1], spaceAfterClosingBrace) : token[1];
  536. level1Optimize(token[2], context);
  537. afterRules = true;
  538. break;
  539. case Token.COMMENT:
  540. optimizeComment(token, options);
  541. break;
  542. case Token.RULE:
  543. token[1] = levelOptions.tidySelectors ? tidyRules(token[1], !ie7Hack, adjacentSpace, format, context.warnings) : token[1];
  544. token[1] = token[1].length > 1 ? sortSelectors(token[1], levelOptions.selectorsSortingMethod) : token[1];
  545. optimizeBody(token[1], token[2], context);
  546. afterRules = true;
  547. break;
  548. }
  549. if (token[0] == Token.COMMENT && token[1].length === 0 || levelOptions.removeEmpty && (token[1].length === 0 || (token[2] && token[2].length === 0))) {
  550. tokens.splice(i, 1);
  551. i--;
  552. l--;
  553. }
  554. }
  555. if (levelOptions.cleanupCharsets && mayHaveCharset) {
  556. cleanupCharsets(tokens);
  557. }
  558. return tokens;
  559. }
  560. module.exports = level1Optimize;