scancss
Version:
A robust CSS stylesheet statistics collector and analyzer
74 lines (57 loc) • 2.27 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.handleUnits = handleUnits;
var _postcssValuesParser = require('postcss-values-parser');
var _postcssValuesParser2 = _interopRequireDefault(_postcssValuesParser);
var _cssUnits = require('../../constants/cssUnits');
var _cssUnitsThatAllowZeroWithoutUnit = require('../../constants/cssUnitsThatAllowZeroWithoutUnit');
var _countUsage = require('../../calculators/countUsage');
var _isSafeAst = require('../../predicates/isSafeAst');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function walkNodes(nodes, decl, report, options) {
nodes.forEach(node => {
if (node.type === 'number' && node.unit !== '') {
const unit = node.unit.toLowerCase();
const valueWithUnit = node.value + unit;
report.units.total++;
(0, _countUsage.countUsage)(unit, report.units.usage);
if (_cssUnits.cssUnits.includes(unit)) {
/** Count negative margins */
if (decl.prop.startsWith('margin') && node.value.startsWith('-') && options.properties) {
report.properties.negativeMargins++;
}
/** Count excessive units, i.e. `0px` */
if (parseFloat(node.value) === 0 && _cssUnitsThatAllowZeroWithoutUnit.cssUnitsThatAllowZeroWithoutUnit.includes(unit)) {
report.units.excessive.total++;
(0, _countUsage.countUsage)(valueWithUnit, report.units.excessive.usage);
}
} else {
report.units.unknown.total++;
(0, _countUsage.countUsage)(unit, report.units.unknown.usage);
}
}
/* istanbul ignore else */
if (node.type === 'func' && Array.isArray(node.nodes)) {
walkNodes(node.nodes, decl, report, options);
}
});
}
function handleUnits(decl, report, options) {
const currentUnitsTotal = report.units.total;
try {
const ast = (0, _postcssValuesParser2.default)(decl.value).parse();
/* istanbul ignore else */
if ((0, _isSafeAst.isSafeAst)(ast)) {
walkNodes(ast.nodes[0].nodes, decl, report, options);
}
} catch (err) {
/* istanbul ignore next */
/* eslint-disable-next-line no-console */
console.log(`'postcss-values-parser' module error\n${err}`);
}
if (currentUnitsTotal === report.units.total && options.properties) {
report.properties.unitless++;
}
}