index.es.mjs 2.2 KB

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