Files
test-repo/src/language-html/syntax-attribute.js
T
James Longandfisker Cheung 6bf6b20aed Reverts #7865, keeping class names on the same line (#11827)
* Reverts #7865, keeping class names on the same line

* Add changelog

* Fix lint

* Fix

Co-authored-by: fisker Cheung <lionkay@gmail.com>
2021-11-18 16:10:41 +09:00

70 lines
1.7 KiB
JavaScript

"use strict";
const parseSrcset = require("parse-srcset");
const {
builders: { ifBreak, join, line },
} = require("../document/index.js");
function printImgSrcset(value) {
const srcset = parseSrcset(value, {
logger: {
error(message) {
throw new Error(message);
},
},
});
const hasW = srcset.some(({ w }) => w);
const hasH = srcset.some(({ h }) => h);
const hasX = srcset.some(({ d }) => d);
if (hasW + hasH + hasX > 1) {
throw new Error("Mixed descriptor in srcset is not supported");
}
const key = hasW ? "w" : hasH ? "h" : "d";
const unit = hasW ? "w" : hasH ? "h" : "x";
const getMax = (values) => Math.max(...values);
const urls = srcset.map((src) => src.url);
const maxUrlLength = getMax(urls.map((url) => url.length));
const descriptors = srcset
.map((src) => src[key])
.map((descriptor) => (descriptor ? descriptor.toString() : ""));
const descriptorLeftLengths = descriptors.map((descriptor) => {
const index = descriptor.indexOf(".");
return index === -1 ? descriptor.length : index;
});
const maxDescriptorLeftLength = getMax(descriptorLeftLengths);
return join(
[",", line],
urls.map((url, index) => {
const parts = [url];
const descriptor = descriptors[index];
if (descriptor) {
const urlPadding = maxUrlLength - url.length + 1;
const descriptorPadding =
maxDescriptorLeftLength - descriptorLeftLengths[index];
const alignment = " ".repeat(urlPadding + descriptorPadding);
parts.push(ifBreak(alignment, " "), descriptor + unit);
}
return parts;
})
);
}
function printClassNames(value) {
return value.trim().split(/\s+/).join(" ");
}
module.exports = {
printImgSrcset,
printClassNames,
};