@platform/css
Version:
Helpers for working with inline CSS.
90 lines (89 loc) • 2.55 kB
JavaScript
import { valueUtil } from '../common';
const isBlank = (value) => {
if (value === undefined || value === null) {
return true;
}
if (typeof value === 'string' && valueUtil.isBlank(value)) {
return true;
}
if (Array.isArray(value) && valueUtil.compact(value).length === 0) {
return true;
}
return false;
};
export const toEdges = (input, options = {}) => {
if (isBlank(input)) {
const { defaultValue } = options;
if (defaultValue && !isBlank(defaultValue)) {
input = defaultValue;
}
else {
return {};
}
}
input = input || 0;
if (!Array.isArray(input)) {
input = input.toString().split(' ');
}
const edges = input
.map(item => (typeof item === 'string' && item.endsWith('px') ? item.replace(/px$/, '') : item))
.map(item => valueUtil.toNumber(item));
let top;
let right;
let bottom;
let left;
const getEdge = (index) => {
const edge = edges[index];
if (edge === null || edge === 'null' || edge === '') {
return undefined;
}
return edge;
};
switch (edges.length) {
case 1:
top = getEdge(0);
bottom = getEdge(0);
left = getEdge(0);
right = getEdge(0);
break;
case 2:
top = getEdge(0);
bottom = getEdge(0);
left = getEdge(1);
right = getEdge(1);
break;
case 3:
top = getEdge(0);
left = getEdge(1);
right = getEdge(1);
bottom = getEdge(2);
break;
default:
top = getEdge(0);
right = getEdge(1);
bottom = getEdge(2);
left = getEdge(3);
}
if (top === undefined && right === undefined && bottom === undefined && left === undefined) {
return {};
}
return {
top,
right,
bottom,
left,
};
};
export function prefixEdges(prefix, edges) {
return Object.keys(edges).reduce((acc, key) => {
const value = edges[key];
key = `${prefix}${key[0].toUpperCase()}${key.substr(1)}`;
return Object.assign(Object.assign({}, acc), { [key]: value });
}, {});
}
export const toMargins = (input, options = {}) => {
return prefixEdges('margin', toEdges(input, options));
};
export const toPadding = (input, options = {}) => {
return prefixEdges('padding', toEdges(input, options));
};