Smarter formatting of HTML class attribute (#7865)

* html: break class attr onto multiple lines, but try keeping consecutive classes with the same prefix on one line

* add changelog

* add more tests

* improve doc structure to fix an issue with the closing quote

* Update changelog_unreleased/html/pr-7865.md

Co-Authored-By: Jed Fox <git@twopointzero.us>

* handle classes with leading _ and -

* update snapshots

* Lint

* Update pr-7865.md

* Update changelog entry

Co-authored-by: Jed Fox <git@twopointzero.us>
Co-authored-by: fisker Cheung <lionkay@gmail.com>
This commit is contained in:
authored and GitHub committed 2021-01-18 15:50:52 +02:00
1 parent c8cbbb0a79
commit 7cf524fa03
10 files changed
+561 -66

No files matched your search

+44 -2
View File
@@ -2,7 +2,7 @@
const parseSrcset = require("parse-srcset");
const {
builders: { ifBreak, join, line },
builders: { group, ifBreak, indent, join, line, softline },
} = require("../document");
function printImgSrcset(value) {
@@ -59,8 +59,50 @@ function printImgSrcset(value) {
);
}
const prefixDelimiters = ["__", "--", "_", "-"];
function getClassPrefix(className) {
const startIndex = className.search(/[^_-]/);
if (startIndex !== -1) {
for (const delimiter of prefixDelimiters) {
const delimiterIndex = className.indexOf(delimiter, startIndex);
if (delimiterIndex !== -1) {
return className.slice(0, delimiterIndex);
}
}
}
return className;
}
function printClassNames(value) {
return value.trim().split(/\s+/).join(" ");
const classNames = value.trim().split(/\s+/);
// Try keeping consecutive classes with the same prefix on one line.
const groupedByPrefix = [];
let previousPrefix;
for (let i = 0; i < classNames.length; i++) {
const prefix = getClassPrefix(classNames[i]);
if (
prefix !== previousPrefix &&
// "home-link" and "home-link_blue_yes" should be considered same-prefix
prefix !== classNames[i - 1]
) {
groupedByPrefix.push([]);
}
groupedByPrefix[groupedByPrefix.length - 1].push(classNames[i]);
previousPrefix = prefix;
}
return [
indent([
softline,
join(
line,
groupedByPrefix.map((classNames) => group(join(line, classNames)))
),
]),
softline,
];
}
module.exports = {