You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

204 lines
6.4 KiB

7 years ago
7 years ago
10 years ago
7 years ago
7 years ago
7 years ago
  1. 'use strict';
  2. var postcss = require('postcss');
  3. var objectAssign = require('object-assign');
  4. var { createPropListMatcher } = require('./src/prop-list-matcher');
  5. var { getUnitRegexp } = require('./src/pixel-unit-regexp');
  6. var defaults = {
  7. unitToConvert: 'px',
  8. viewportWidth: 320,
  9. viewportHeight: 568, // not now used; TODO: need for different units and math for different properties
  10. unitPrecision: 5,
  11. viewportUnit: 'vw',
  12. fontViewportUnit: 'vw', // vmin is more suitable.
  13. selectorBlackList: [],
  14. propList: ['*'],
  15. minPixelValue: 1,
  16. mediaQuery: false,
  17. replace: true,
  18. landscape: false,
  19. landscapeUnit: 'vw',
  20. landscapeWidth: 568
  21. };
  22. var ignoreNextComment = 'px-to-viewport-ignore-next';
  23. var ignorePrevComment = 'px-to-viewport-ignore';
  24. module.exports = postcss.plugin('postcss-px-to-viewport', function (options) {
  25. var opts = objectAssign({}, defaults, options);
  26. checkRegExpOrArray(opts, 'exclude');
  27. checkRegExpOrArray(opts, 'include');
  28. var pxRegex = getUnitRegexp(opts.unitToConvert);
  29. var satisfyPropList = createPropListMatcher(opts.propList);
  30. var landscapeRules = [];
  31. return function (css, result) {
  32. css.walkRules(function (rule) {
  33. // Add exclude option to ignore some files like 'node_modules'
  34. var file = rule.source && rule.source.input.file;
  35. if (opts.include && file) {
  36. if (Object.prototype.toString.call(opts.include) === '[object RegExp]') {
  37. if (!opts.include.test(file)) return;
  38. } else if (Object.prototype.toString.call(opts.include) === '[object Array]') {
  39. var flag = false;
  40. for (var i = 0; i < opts.include.length; i++) {
  41. if (opts.include[i].test(file)) {
  42. flag = true;
  43. break;
  44. }
  45. }
  46. if (!flag) return;
  47. }
  48. }
  49. if (opts.exclude && file) {
  50. if (Object.prototype.toString.call(opts.exclude) === '[object RegExp]') {
  51. if (opts.exclude.test(file)) return;
  52. } else if (Object.prototype.toString.call(opts.exclude) === '[object Array]') {
  53. for (var i = 0; i < opts.exclude.length; i++) {
  54. if (opts.exclude[i].test(file)) return;
  55. }
  56. }
  57. }
  58. if (blacklistedSelector(opts.selectorBlackList, rule.selector)) return;
  59. if (opts.landscape && !rule.parent.params) {
  60. var landscapeRule = rule.clone().removeAll();
  61. rule.walkDecls(function(decl) {
  62. if (decl.value.indexOf(opts.unitToConvert) === -1) return;
  63. if (!satisfyPropList(decl.prop)) return;
  64. landscapeRule.append(decl.clone({
  65. value: decl.value.replace(pxRegex, createPxReplace(opts, opts.landscapeUnit, opts.landscapeWidth))
  66. }));
  67. });
  68. if (landscapeRule.nodes.length > 0) {
  69. landscapeRules.push(landscapeRule);
  70. }
  71. }
  72. if (!validateParams(rule.parent.params, opts.mediaQuery)) return;
  73. rule.walkDecls(function(decl, i) {
  74. if (decl.value.indexOf(opts.unitToConvert) === -1) return;
  75. if (!satisfyPropList(decl.prop)) return;
  76. var prev = decl.prev();
  77. // prev declaration is ignore conversion comment at same line
  78. if (prev && prev.type === 'comment' && prev.text === ignoreNextComment) {
  79. // remove comment
  80. prev.remove();
  81. return;
  82. }
  83. var next = decl.next();
  84. // next declaration is ignore conversion comment at same line
  85. if (next && next.type === 'comment' && next.text === ignorePrevComment) {
  86. if (/\n/.test(next.raws.before)) {
  87. result.warn('Unexpected comment /* ' + ignorePrevComment + ' */ must be after declaration at same line.', { node: next });
  88. } else {
  89. // remove comment
  90. next.remove();
  91. return;
  92. }
  93. }
  94. var unit;
  95. var size;
  96. var params = rule.parent.params;
  97. if (opts.landscape && params && params.indexOf('landscape') !== -1) {
  98. unit = opts.landscapeUnit;
  99. size = opts.landscapeWidth;
  100. } else {
  101. unit = getUnit(decl.prop, opts);
  102. size = opts.viewportWidth;
  103. }
  104. var value = decl.value.replace(pxRegex, createPxReplace(opts, unit, size));
  105. if (declarationExists(decl.parent, decl.prop, value)) return;
  106. if (opts.replace) {
  107. decl.value = value;
  108. } else {
  109. decl.parent.insertAfter(i, decl.clone({ value: value }));
  110. }
  111. });
  112. });
  113. if (landscapeRules.length > 0) {
  114. var landscapeRoot = new postcss.atRule({ params: '(orientation: landscape)', name: 'media' });
  115. landscapeRules.forEach(function(rule) {
  116. landscapeRoot.append(rule);
  117. });
  118. css.append(landscapeRoot);
  119. }
  120. };
  121. });
  122. function getUnit(prop, opts) {
  123. return prop.indexOf('font') === -1 ? opts.viewportUnit : opts.fontViewportUnit;
  124. }
  125. function createPxReplace(opts, viewportUnit, viewportSize) {
  126. return function (m, $1) {
  127. if (!$1) return m;
  128. var pixels = parseFloat($1);
  129. if (pixels <= opts.minPixelValue) return m;
  130. var parsedVal = toFixed((pixels / viewportSize * 100), opts.unitPrecision);
  131. return parsedVal === 0 ? '0' : parsedVal + viewportUnit;
  132. };
  133. }
  134. function error(decl, message) {
  135. throw decl.error(message, { plugin: 'postcss-px-to-viewport' });
  136. }
  137. function checkRegExpOrArray(options, optionName) {
  138. var option = options[optionName];
  139. if (!option) return;
  140. if (Object.prototype.toString.call(option) === '[object RegExp]') return;
  141. if (Object.prototype.toString.call(option) === '[object Array]') {
  142. var bad = false;
  143. for (var i = 0; i < option.length; i++) {
  144. if (Object.prototype.toString.call(option[i]) !== '[object RegExp]') {
  145. bad = true;
  146. break;
  147. }
  148. }
  149. if (!bad) return;
  150. }
  151. throw new Error('options.' + optionName + ' should be RegExp or Array of RegExp.');
  152. }
  153. function toFixed(number, precision) {
  154. var multiplier = Math.pow(10, precision + 1),
  155. wholeNumber = Math.floor(number * multiplier);
  156. return Math.round(wholeNumber / 10) * 10 / multiplier;
  157. }
  158. function blacklistedSelector(blacklist, selector) {
  159. if (typeof selector !== 'string') return;
  160. return blacklist.some(function (regex) {
  161. if (typeof regex === 'string') return selector.indexOf(regex) !== -1;
  162. return selector.match(regex);
  163. });
  164. }
  165. function declarationExists(decls, prop, value) {
  166. return decls.some(function (decl) {
  167. return (decl.prop === prop && decl.value === value);
  168. });
  169. }
  170. function validateParams(params, mediaQuery) {
  171. return !params || (params && mediaQuery);
  172. }