nodeContextLookup.cjs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. /**
  5. * Create a collection of Maps that serve to contextualize a given node.
  6. * This is useful to ensure that you only compare nodes that share a certain
  7. * context.
  8. *
  9. * All nodes are initially contextualized by their input source.
  10. * From there, you can contextualize them however you want.
  11. *
  12. * For a usage example, see `selector-no-descending-specificity`.
  13. */
  14. function nodeContextLookup() {
  15. const contextMap = new Map();
  16. return {
  17. /**
  18. * @param {import('postcss').Node} node
  19. * @param {any[]} subContexts
  20. * @returns {Map<any, any>}
  21. */
  22. getContext(node, ...subContexts) {
  23. if (!node.source) throw new Error('The node source must be present');
  24. const nodeSource = node.source.input.from;
  25. const baseContext = creativeGetMap(contextMap, nodeSource);
  26. return subContexts.reduce((result, context) => creativeGetMap(result, context), baseContext);
  27. },
  28. };
  29. }
  30. /**
  31. * @param {Map<any, any>} someMap
  32. * @param {any} someThing
  33. */
  34. function creativeGetMap(someMap, someThing) {
  35. if (!someMap.has(someThing)) {
  36. someMap.set(someThing, new Map());
  37. }
  38. return someMap.get(someThing);
  39. }
  40. module.exports = nodeContextLookup;