eachDeclarationBlock.cjs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 typeGuards = require('./typeGuards.cjs');
  5. /** @typedef {import('postcss').Root} Root */
  6. /** @typedef {import('postcss').Root} Document */
  7. /** @typedef {import('postcss').Node} PostcssNode */
  8. /** @typedef {import('postcss').Container} PostcssContainerNode */
  9. /** @typedef {import('postcss').Declaration} Declaration */
  10. /** @typedef {(callbackFn: (decl: Declaration, index: number, decls: Declaration[]) => void) => void} EachDeclaration */
  11. /**
  12. * @param {PostcssNode} node
  13. * @returns {node is PostcssContainerNode}
  14. */
  15. function isContainerNode(node) {
  16. return typeGuards.isRule(node) || typeGuards.isAtRule(node) || typeGuards.isRoot(node);
  17. }
  18. /**
  19. * In order to accommodate nested blocks (postcss-nested),
  20. * we need to run a shallow loop (instead of eachDecl() or eachRule(),
  21. * which loop recursively) and allow each nested block to accumulate
  22. * its own list of properties -- so that a property in a nested rule
  23. * does not conflict with the same property in the parent rule
  24. * executes a provided function once for each declaration block.
  25. *
  26. * @param {Root | Document} root - root element of file.
  27. * @param {(eachDecl: EachDeclaration) => void} callback - Function to execute for each declaration block
  28. *
  29. * @returns {void}
  30. */
  31. function eachDeclarationBlock(root, callback) {
  32. /**
  33. * @param {PostcssNode} statement
  34. *
  35. * @returns {void}
  36. */
  37. function each(statement) {
  38. if (!isContainerNode(statement)) return;
  39. if (statement.nodes && statement.nodes.length) {
  40. /** @type {Declaration[]} */
  41. const decls = [];
  42. for (const node of statement.nodes) {
  43. if (node.type === 'decl') {
  44. decls.push(node);
  45. }
  46. each(node);
  47. }
  48. if (decls.length) {
  49. callback(decls.forEach.bind(decls));
  50. }
  51. }
  52. }
  53. each(root);
  54. }
  55. module.exports = eachDeclarationBlock;