index.cjs.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  3. var postcss = _interopDefault(require('postcss'));
  4. var valueParser = _interopDefault(require('postcss-values-parser'));
  5. var index = postcss.plugin('postcss-double-position-gradients', opts => {
  6. const preserve = 'preserve' in Object(opts) ? Boolean(opts.preserve) : true;
  7. return root => {
  8. // walk every declaration
  9. root.walkDecls(decl => {
  10. const originalValue = decl.value; // if the declaration value contains a gradient
  11. if (gradientFunctionRegExp.test(originalValue)) {
  12. const ast = valueParser(originalValue).parse(); // walk every function in the declaration value
  13. ast.walkFunctionNodes(fn => {
  14. // if the function is a gradient
  15. if (gradientFunctionNameRegExp.test(fn.value)) {
  16. const nodes = fn.nodes.slice(1, -1); // walk every argument to the function
  17. nodes.forEach((node, index) => {
  18. const node1back = Object(nodes[index - 1]);
  19. const node2back = Object(nodes[index - 2]);
  20. const isDoublePositionLength = node2back.type && node1back.type === 'number' && node.type === 'number'; // if the argument concludes a double-position gradient
  21. if (isDoublePositionLength) {
  22. // insert the fallback colors
  23. const color = node2back.clone();
  24. const comma = valueParser.comma({
  25. value: ',',
  26. raws: {
  27. after: ' '
  28. }
  29. });
  30. fn.insertBefore(node, comma);
  31. fn.insertBefore(node, color);
  32. }
  33. });
  34. }
  35. });
  36. const modifiedValue = ast.toString(); // if the value has changed due to double-position gradients
  37. if (originalValue !== modifiedValue) {
  38. // add the fallback value
  39. decl.cloneBefore({
  40. value: modifiedValue
  41. }); // conditionally remove the double-position gradient
  42. if (!preserve) {
  43. decl.remove();
  44. }
  45. }
  46. }
  47. });
  48. };
  49. });
  50. const gradientFunctionRegExp = /(repeating-)?(conic|linear|radial)-gradient\([\W\w]*\)/i;
  51. const gradientFunctionNameRegExp = /^(repeating-)?(conic|linear|radial)-gradient$/i;
  52. module.exports = index;
  53. //# sourceMappingURL=index.cjs.js.map