vanillajs-browser-helpers
Version:
Collection of convenience code snippets (helpers) that aims to make it a little easier to work with vanilla JS in the browser
84 lines (83 loc) • 2.99 kB
JavaScript
;
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var isString_1 = __importDefault(require("vanillajs-helpers/isString"));
var kebabCase_1 = __importDefault(require("vanillajs-helpers/kebabCase"));
var applyValue = function (elm, property, value, important) {
var val = value != null ? String(value) : '';
if (important) {
var imp = important ? 'important' : undefined;
elm.style.setProperty((0, kebabCase_1.default)(property), val, imp);
}
else {
elm.style[property] = val;
}
// This part here is for when the value is a number,
// but the property can't accept just a numeric value,
// so "px" has to be added
if (!Number.isNaN(Number(val)) && elm.style[property] !== val) {
applyValue(elm, property, value + 'px', important);
}
};
var setValue = function (elm, property, value) {
var important = false;
if ((0, isString_1.default)(value) && value.includes('!important')) {
value = value.split(' ')[0];
important = true;
}
applyValue(elm, property, value, important);
};
/**
* Get a given style property.
* if value is set (not undefined), it will be set before returning
*/
var handleSingleValue = function (elm, property, value) {
if (value !== undefined) {
setValue(elm, property, value);
}
// Get all computed styles as that gives a more correct value
var val = window.getComputedStyle(elm)
.getPropertyValue((0, kebabCase_1.default)(property));
if (val.includes('px')) {
return parseFloat(val);
}
var numeric = Number(val);
return !Number.isNaN(numeric) ? numeric : val;
};
/**
* Traverse the `propertyMap` and set style on element accordingly
*/
var handleMultipleValues = function (elm, properties) {
if (properties) {
Object.entries(properties)
.forEach(function (_a) {
var _b = __read(_a, 2), key = _b[0], value = _b[1];
value && setValue(elm, key, value);
});
}
return window.getComputedStyle(elm);
};
function css(elm, property, value) {
return (0, isString_1.default)(property)
? handleSingleValue(elm, property, value)
: handleMultipleValues(elm, property);
}
exports.default = css;