index.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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. module.exports = postcss.plugin('postcss-px-to-viewport', function (options) {
  23. var opts = objectAssign({}, defaults, options);
  24. var pxRegex = getUnitRegexp(opts.unitToConvert);
  25. var satisfyPropList = createPropListMatcher(opts.propList);
  26. var landscapeRules = [];
  27. return function (css) {
  28. css.walkRules(function (rule) {
  29. // Add exclude option to ignore some files like 'node_modules'
  30. var file = rule.source && rule.source.input.file;
  31. if (opts.exclude && file) {
  32. if (Object.prototype.toString.call(opts.exclude) === '[object RegExp]') {
  33. if (isExclude(opts.exclude, file)) return;
  34. } else if (Object.prototype.toString.call(opts.exclude) === '[object Array]') {
  35. for (let i = 0; i < opts.exclude.length; i++) {
  36. if (isExclude(opts.exclude[i], file)) return;
  37. }
  38. } else {
  39. throw new Error('options.exclude should be RegExp or Array.');
  40. }
  41. }
  42. if (blacklistedSelector(opts.selectorBlackList, rule.selector)) return;
  43. if (opts.landscape && !rule.parent.params) {
  44. var landscapeRule = rule.clone().removeAll();
  45. rule.walkDecls(function(decl) {
  46. if (decl.value.indexOf(opts.unitToConvert) === -1) return;
  47. if (!satisfyPropList(decl.prop)) return;
  48. landscapeRule.append(decl.clone({
  49. value: decl.value.replace(pxRegex, createPxReplace(opts, opts.landscapeUnit, opts.landscapeWidth))
  50. }));
  51. });
  52. if (landscapeRule.nodes.length > 0) {
  53. landscapeRules.push(landscapeRule);
  54. }
  55. }
  56. if (!validateParams(rule.parent.params, opts.mediaQuery)) return;
  57. rule.walkDecls(function(decl, i) {
  58. if (decl.value.indexOf(opts.unitToConvert) === -1) return;
  59. if (!satisfyPropList(decl.prop)) return;
  60. var unit;
  61. var size;
  62. var params = rule.parent.params;
  63. if (opts.landscape && params && params.indexOf('landscape') !== -1) {
  64. unit = opts.landscapeUnit;
  65. size = opts.landscapeWidth;
  66. } else {
  67. unit = getUnit(decl.prop, opts);
  68. size = opts.viewportWidth;
  69. }
  70. var value = decl.value.replace(pxRegex, createPxReplace(opts, unit, size));
  71. if (declarationExists(decl.parent, decl.prop, value)) return;
  72. if (opts.replace) {
  73. decl.value = value;
  74. } else {
  75. decl.parent.insertAfter(i, decl.clone({ value: value }));
  76. }
  77. });
  78. });
  79. if (landscapeRules.length > 0) {
  80. var landscapeRoot = new postcss.atRule({ params: '(orientation: landscape)', name: 'media' });
  81. landscapeRules.forEach(function(rule) {
  82. landscapeRoot.append(rule);
  83. });
  84. css.append(landscapeRoot);
  85. }
  86. };
  87. });
  88. function getUnit(prop, opts) {
  89. return prop.indexOf('font') === -1 ? opts.viewportUnit : opts.fontViewportUnit;
  90. }
  91. function createPxReplace(opts, viewportUnit, viewportSize) {
  92. return function (m, $1) {
  93. if (!$1) return m;
  94. var pixels = parseFloat($1);
  95. if (pixels <= opts.minPixelValue) return m;
  96. var parsedVal = toFixed((pixels / viewportSize * 100), opts.unitPrecision);
  97. return parsedVal === 0 ? '0' : parsedVal + viewportUnit;
  98. };
  99. }
  100. function toFixed(number, precision) {
  101. var multiplier = Math.pow(10, precision + 1),
  102. wholeNumber = Math.floor(number * multiplier);
  103. return Math.round(wholeNumber / 10) * 10 / multiplier;
  104. }
  105. function blacklistedSelector(blacklist, selector) {
  106. if (typeof selector !== 'string') return;
  107. return blacklist.some(function (regex) {
  108. if (typeof regex === 'string') return selector.indexOf(regex) !== -1;
  109. return selector.match(regex);
  110. });
  111. }
  112. function isExclude(reg, file) {
  113. if (Object.prototype.toString.call(reg) !== '[object RegExp]') {
  114. throw new Error('options.exclude should be RegExp.');
  115. }
  116. return file.match(reg) !== null;
  117. }
  118. function declarationExists(decls, prop, value) {
  119. return decls.some(function (decl) {
  120. return (decl.prop === prop && decl.value === value);
  121. });
  122. }
  123. function validateParams(params, mediaQuery) {
  124. return !params || (params && mediaQuery);
  125. }