Skip to content

Commit

Permalink
Merge pull request #693 from prettier/simplify
Browse files Browse the repository at this point in the history
Inline sort attributes by key
  • Loading branch information
kddnewton authored Jul 7, 2023
2 parents cef22c9 + e8f73cb commit 210a685
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 100 deletions.
31 changes: 29 additions & 2 deletions src/printer.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as doc from "prettier/doc";
import embed from "./embed.js";
import sortAttributesByKey from "./util/sortAttributesByKey.js";

const { fill, group, hardline, indent, join, line, literalline, softline } =
doc.builders;
Expand Down Expand Up @@ -380,7 +379,35 @@ function printElement(path, opts, print) {
);

if (opts.xmlSortAttributesByKey) {
sortAttributesByKey(attributes);
attributes.sort((left, right) => {
const leftAttr = left.node.children.Name[0].image;
const rightAttr = right.node.children.Name[0].image;

// Check if the attributes are xmlns.
if (leftAttr === "xmlns") return -1;
if (rightAttr === "xmlns") return 1;

// Check if they are both in namespaces.
if (leftAttr.includes(":") && rightAttr.includes(":")) {
const [leftNS, leftKey] = leftAttr.split(":");
const [rightNS, rightKey] = rightAttr.split(":");

// If namespaces are equal, compare keys
if (leftNS === rightNS) return leftKey.localeCompare(rightKey);

// Handle the 1 but not both being an xmlns
if (leftNS === "xmlns") return -1;
if (rightNS === "xlmns") return 1;

return leftNS.localeCompare(rightNS);
}

// Check if the attributes have namespaces.
if (leftAttr.includes(":")) return -1;
if (rightAttr.includes(":")) return 1;

return leftAttr.localeCompare(rightAttr);
});
}

const separator = opts.singleAttributePerLine ? hardline : line;
Expand Down
98 changes: 0 additions & 98 deletions src/util/sortAttributesByKey.js

This file was deleted.

0 comments on commit 210a685

Please sign in to comment.