functionArgumentsSearch.cjs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // NOTICE: This file is generated by Rollup. To modify it,
  2. // please instead edit the ESM counterpart and rebuild with Rollup (npm run build).
  3. 'use strict';
  4. const balancedMatch = require('balanced-match');
  5. const valueParser = require('postcss-value-parser');
  6. const validateTypes = require('./validateTypes.cjs');
  7. /** @typedef {(expression: string, expressionIndex: number, funcNode: valueParser.FunctionNode, parsedValue: valueParser.ParsedValue) => void} Callback */
  8. /**
  9. * Search a CSS string for functions by name.
  10. * For every match, invoke the callback, passing the function's
  11. * "argument(s) string" (whatever is inside the parentheses)
  12. * as an argument.
  13. *
  14. * Callback will be called once for every matching function found,
  15. * with the function's "argument(s) string" and its starting index
  16. * as the arguments.
  17. *
  18. * @param {string} source
  19. * @param {string | RegExp} functionName
  20. * @param {Callback} callback
  21. * @returns {valueParser.ParsedValue}
  22. */
  23. function functionArgumentsSearch(source, functionName, callback) {
  24. const parsedValue = valueParser(source);
  25. return parsedValue.walk((node) => {
  26. if (node.type !== 'function') return;
  27. const { value } = node;
  28. if (validateTypes.isString(functionName) && value !== functionName) return;
  29. if (validateTypes.isRegExp(functionName) && !functionName.test(node.value)) return;
  30. const parensMatch = balancedMatch('(', ')', source.slice(node.sourceIndex));
  31. validateTypes.assert(parensMatch);
  32. const expression = parensMatch.body;
  33. const parenLength = 1; // == '('
  34. const expressionIndex = node.sourceIndex + value.length + parenLength;
  35. callback(expression, expressionIndex, node, parsedValue);
  36. });
  37. }
  38. module.exports = functionArgumentsSearch;