4
0

isFirstNested.mjs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { hasSource, isComment, isDocument, isRoot } from './typeGuards.mjs';
  2. /**
  3. * @param {import('postcss').Node} statement
  4. * @returns {boolean}
  5. */
  6. export default function isFirstNested(statement) {
  7. const parentNode = statement.parent;
  8. if (parentNode === undefined) {
  9. return false;
  10. }
  11. if (isRoot(parentNode) && !isInDocument(parentNode)) {
  12. return false;
  13. }
  14. if (statement === parentNode.first) {
  15. return true;
  16. }
  17. /*
  18. * Search for the statement in the parent's nodes, ignoring comment
  19. * nodes on the same line as the parent's opening brace.
  20. */
  21. const parentNodes = parentNode.nodes;
  22. if (!parentNodes) {
  23. return false;
  24. }
  25. const firstNode = parentNodes[0];
  26. if (!firstNode) {
  27. return false;
  28. }
  29. if (
  30. !isComment(firstNode) ||
  31. (typeof firstNode.raws.before === 'string' && firstNode.raws.before.includes('\n'))
  32. ) {
  33. return false;
  34. }
  35. if (!hasSource(firstNode) || !firstNode.source.start) {
  36. return false;
  37. }
  38. const openingBraceLine = firstNode.source.start.line;
  39. if (!firstNode.source.end || openingBraceLine !== firstNode.source.end.line) {
  40. return false;
  41. }
  42. for (const [index, node] of parentNodes.entries()) {
  43. if (index === 0) {
  44. continue;
  45. }
  46. if (node === statement) {
  47. return true;
  48. }
  49. if (
  50. !isComment(node) ||
  51. (hasSource(node) && node.source.end && node.source.end.line !== openingBraceLine)
  52. ) {
  53. return false;
  54. }
  55. }
  56. /* istanbul ignore next: Should always return in the loop */
  57. return false;
  58. }
  59. /**
  60. * @param {import('postcss').Node} node
  61. * @returns {boolean}
  62. */
  63. function isInDocument({ parent }) {
  64. return Boolean(parent && isDocument(parent));
  65. }