{"version":3,"file":"fixer.rewrite-to-expected-ast.mjs","sources":["../../../../../src/rules/css/grouped-declarations/fixer.rewrite-to-expected-ast.ts"],"sourcesContent":["import type { AtRule, Declaration, Root, Rule } from \"postcss\";\n\nimport type { GroupOrder } from \"./config.order\";\nimport { defaultOrder } from \"./config.order\";\nimport type {\n  DeclarationGroup,\n  DeclarationScope,\n} from \"./util.extract-declaration-scopes\";\nimport {\n  findGroupOrderForProperty,\n  findPropertyIndexInGroupOrder,\n} from \"./util.find-group-order-for-property\";\n\nexport function rewriteToExpectedAST(\n  cssAST: Root,\n  declarationRootScope: DeclarationScope,\n): Root {\n  const clonedAst = cssAST.clone();\n  clonedAst.nodes = [];\n  insertDeclarationScopeToAST(declarationRootScope, clonedAst);\n\n  function insertDeclarationScopeToAST(\n    scope: DeclarationScope,\n    rootNode: Root | Rule | AtRule,\n  ) {\n    rootNode.nodes ??= [];\n\n    for (let i = 0; i < scope.comments.length; i++) {\n      const isFirstComment = i === 0;\n      const comment = scope.comments[i];\n\n      if (!comment) {\n        continue;\n      }\n\n      if (isFirstComment) {\n        const newLines = rootNode.nodes.length === 0 ? 1 : 2;\n\n        comment.raws = {\n          ...comment.raws,\n          before: `${\"\\n\".repeat(newLines)}${\" \".repeat(\n            comment.raws.before?.replace(/\\n/g, \"\").length ?? 0,\n          )}`,\n        };\n      }\n\n      rootNode.push(comment);\n    }\n\n    if (scope.container) {\n      const newLines =\n        rootNode.nodes.length === 0 || scope.comments.length > 0 ? 1 : 2;\n      scope.container.raws = {\n        ...scope.container.raws,\n        before: `${\"\\n\".repeat(newLines)}${\" \".repeat(\n          scope.container.raws.before?.replace(/\\n/g, \"\").length ?? 0,\n        )}`,\n      };\n\n      scope.container.nodes = [];\n      rootNode.push(scope.container);\n    }\n\n    const orderedGroups = constructOrderedGroups(scope.groups);\n\n    // In case all groups (except css variables and CSS-in-JS statements)\n    // contains at most one item, then groups should be collapsed.\n    const collapseGroups = orderedGroups\n      .slice(1)\n      .reduce(\n        (acc, curr) =>\n          curr.declarations.length <= 1 && curr.comments.length === 0 && acc,\n        true,\n      );\n\n    // In case we're collapsing groups, then CssInJs should be separate from\n    // the rest of the content.\n    let separatedCssInJS = !collapseGroups;\n\n    const relevantNodeArray = scope.container\n      ? scope.container.nodes ?? []\n      : rootNode.nodes ?? [];\n\n    for (\n      let declarationGroupIndex = 0;\n      declarationGroupIndex < orderedGroups.length;\n      declarationGroupIndex++\n    ) {\n      const declarationGroup = orderedGroups[declarationGroupIndex];\n\n      if (\n        !declarationGroup ||\n        (declarationGroup.comments.length === 0 &&\n          declarationGroup.declarations.length === 0)\n      ) {\n        continue;\n      }\n\n      for (let i = 0; i < declarationGroup.comments.length; i++) {\n        const isFirstComment = i === 0;\n        const comment = declarationGroup.comments[i];\n\n        if (!comment) {\n          continue;\n        }\n\n        if (isFirstComment) {\n          const newLines = relevantNodeArray.length === 0 ? 1 : 2;\n          comment.raws = {\n            ...comment.raws,\n            before: `${\"\\n\".repeat(newLines)}${\" \".repeat(\n              comment.raws.before?.replace(/\\n/g, \"\").length ?? 0,\n            )}`,\n          };\n        }\n\n        relevantNodeArray.push(comment);\n      }\n\n      for (let i = 0; i < declarationGroup.declarations.length; i++) {\n        const declaration = declarationGroup.declarations[i];\n\n        if (!declaration) {\n          continue;\n        }\n\n        declaration.raws = {\n          ...declaration.raws,\n          before: `${\"\\n\".repeat(\n            // The first declaration may have an additional line-break to\n            // separate it from the previous group.\n            // However, if the current declaration has a comment, then it should\n            // just have one line-break as normally.\n            i === 0 &&\n              relevantNodeArray.length !== 0 &&\n              declarationGroup.comments.length === 0 &&\n              // if we should collapse groups, then no newline should be added\n              // (except between normal props and css vars / css-in-js\n              // statements)\n              (!collapseGroups ||\n                (declarationGroupIndex > 0 && !separatedCssInJS))\n              ? 2\n              : 1,\n          )}${\" \".repeat(\n            declaration.raws.before?.replace(/[^ ]/g, \"\").length ?? 0,\n          )}`,\n        };\n      }\n\n      relevantNodeArray.push(...declarationGroup.declarations);\n\n      if (declarationGroupIndex > 0) {\n        separatedCssInJS = true;\n      }\n    }\n\n    // Recursively add all nested scopes to the current parent\n    for (const nestedScope of scope.scopes) {\n      insertDeclarationScopeToAST(nestedScope, scope.container ?? clonedAst);\n    }\n  }\n\n  return clonedAst;\n}\n\nfunction constructOrderedGroups(\n  originalGroups: DeclarationGroup[],\n): DeclarationGroup[] {\n  const sortedGroups: DeclarationGroup[] = new Array(defaultOrder.length + 1)\n    .fill(undefined)\n    .map(() => ({ declarations: [], comments: [] }));\n\n  for (const declarationGroup of originalGroups) {\n    // Groups containing a group should always positioned last in the current\n    // declaration scope.\n    if (declarationGroup.comments.length > 0) {\n      sortedGroups.push(declarationGroup);\n      continue;\n    }\n\n    for (const declaration of declarationGroup.declarations) {\n      // The current declaration should always go into the first group which\n      // explictly contains it.\n      const relevantGroupOrderIndex = defaultOrder.findIndex(\n        findGroupOrderForProperty(declaration.prop),\n      );\n\n      if (relevantGroupOrderIndex === -1) {\n        sortedGroups[defaultOrder.length]?.declarations.push(declaration);\n      } else {\n        sortedGroups[relevantGroupOrderIndex]?.declarations.push(declaration);\n      }\n    }\n  }\n\n  // Now that we've added all declarations to their relevant groups, then ensure\n  // that each group is internally sorted based on the provided group order\n  for (let i = 0; i < defaultOrder.length; i++) {\n    const order = defaultOrder[i];\n    const group = sortedGroups[i];\n\n    if (group && order) {\n      group.declarations = orderGroup(order, group.declarations);\n    }\n  }\n\n  // The final group, which contains all non-matching properties, should be\n  // sorted alphabetically.\n  sortedGroups[defaultOrder.length]?.declarations.sort((a, b) =>\n    a.prop.localeCompare(b.prop),\n  );\n\n  return sortedGroups;\n}\n\nfunction orderGroup(order: GroupOrder, group: Declaration[]): Declaration[] {\n  return [...group].sort((a, b) => {\n    const aOrder = findPropertyIndexInGroupOrder(order, a.prop) ?? -1;\n    const bOrder = findPropertyIndexInGroupOrder(order, b.prop) ?? -1;\n\n    // const aValueIsCustomProp =\n    //   a.value === a.value.match(/custom-prop__(.*?)__/)?.[0];\n    // const bValueIsCustomProp =\n    //   b.value === b.value.match(/custom-prop__(.*?)__/)?.[0];\n\n    // // In case any values in the group contains JS properties, then ensure to\n    // // put these first, ensuring that subsequent declarations can overwrite\n    // // values from the customly inserted JS, if required.\n    // if (aValueIsCustomProp && !bValueIsCustomProp) {\n    //   return -1;\n    // } else if (!aValueIsCustomProp && bValueIsCustomProp) {\n    //   return 1;\n    // }\n\n    return aOrder - bOrder;\n  });\n}\n"],"names":[],"mappings":";;;AAaO,SAAS,oBAAA,CACd,QACA,oBAAA,EACM;AACN,EAAA,MAAM,SAAA,GAAY,OAAO,KAAA,EAAM;AAC/B,EAAA,SAAA,CAAU,QAAQ,EAAC;AACnB,EAAA,2BAAA,CAA4B,sBAAsB,SAAS,CAAA;AAE3D,EAAA,SAAS,2BAAA,CACP,OACA,QAAA,EACA;AACA,IAAA,QAAA,CAAS,UAAU,EAAC;AAEpB,IAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,QAAA,CAAS,QAAQ,CAAA,EAAA,EAAK;AAC9C,MAAA,MAAM,iBAAiB,CAAA,KAAM,CAAA;AAC7B,MAAA,MAAM,OAAA,GAAU,KAAA,CAAM,QAAA,CAAS,CAAC,CAAA;AAEhC,MAAA,IAAI,CAAC,OAAA,EAAS;AACZ,QAAA;AAAA,MACF;AAEA,MAAA,IAAI,cAAA,EAAgB;AAClB,QAAA,MAAM,QAAA,GAAW,QAAA,CAAS,KAAA,CAAM,MAAA,KAAW,IAAI,CAAA,GAAI,CAAA;AAEnD,QAAA,OAAA,CAAQ,IAAA,GAAO;AAAA,UACb,GAAG,OAAA,CAAQ,IAAA;AAAA,UACX,QAAQ,CAAA,EAAG,IAAA,CAAK,OAAO,QAAQ,CAAC,GAAG,GAAA,CAAI,MAAA;AAAA,YACrC,QAAQ,IAAA,CAAK,MAAA,EAAQ,QAAQ,KAAA,EAAO,EAAE,EAAE,MAAA,IAAU;AAAA,WACnD,CAAA;AAAA,SACH;AAAA,MACF;AA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