@pacote/pixels
Version:
Converts CSS unit lengths to pixels.
60 lines • 2.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.pixels = pixels;
const get_style_1 = require("@pacote/get-style");
const PIXELS_PER_INCH = 96;
const MILLIMETRES_PER_INCH = 25.4;
const POINTS_PER_INCH = 72;
const PICAS_PER_INCH = 6;
function fontSize(element) {
return element
? (0, get_style_1.getStyle)(element, 'fontSize') || fontSize(element.parentElement)
: (0, get_style_1.getStyle)(window.document.documentElement, 'fontSize');
}
function parse(providedLength) {
var _a;
const length = providedLength || '0';
const value = Number.parseFloat(length);
const match = length.match(/[\d-.]+(\w+)$/);
const unit = (_a = match === null || match === void 0 ? void 0 : match[1]) !== null && _a !== void 0 ? _a : '';
return [value, unit.toLowerCase()];
}
function pixels(length, element) {
var _a, _b;
const view = (_b = (_a = element === null || element === void 0 ? void 0 : element.ownerDocument) === null || _a === void 0 ? void 0 : _a.defaultView) !== null && _b !== void 0 ? _b : window;
const root = view.document.documentElement || view.document.body;
const [value, unit] = parse(length);
switch (unit) {
case 'rem':
return value * pixels(fontSize(window.document.documentElement));
case 'em':
return value * pixels(fontSize(element), element === null || element === void 0 ? void 0 : element.parentElement);
case 'in':
return value * PIXELS_PER_INCH;
case 'q':
return (value * PIXELS_PER_INCH) / MILLIMETRES_PER_INCH / 4;
case 'mm':
return (value * PIXELS_PER_INCH) / MILLIMETRES_PER_INCH;
case 'cm':
return (value * PIXELS_PER_INCH * 10) / MILLIMETRES_PER_INCH;
case 'pt':
return (value * PIXELS_PER_INCH) / POINTS_PER_INCH;
case 'pc':
return (value * PIXELS_PER_INCH) / PICAS_PER_INCH;
case 'vh':
return (value * view.innerHeight || root.clientWidth) / 100;
case 'vw':
return (value * view.innerWidth || root.clientHeight) / 100;
case 'vmin':
return ((value *
Math.min(view.innerWidth || root.clientWidth, view.innerHeight || root.clientHeight)) /
100);
case 'vmax':
return ((value *
Math.max(view.innerWidth || root.clientWidth, view.innerHeight || root.clientHeight)) /
100);
default:
return value;
}
}
//# sourceMappingURL=index.js.map