element/packages/table/src/util.js

78 lines
1.9 KiB
JavaScript

let scrollBarWidth;
export const getScrollBarWidth = () => {
if (scrollBarWidth !== undefined) return scrollBarWidth;
const outer = document.createElement('div');
outer.style.visibility = 'hidden';
outer.style.width = '100px';
outer.style.position = 'absolute';
outer.style.top = '-9999px';
document.body.appendChild(outer);
const widthNoScroll = outer.offsetWidth;
outer.style.overflow = 'scroll';
const inner = document.createElement('div');
inner.style.width = '100%';
outer.appendChild(inner);
const widthWithScroll = inner.offsetWidth;
outer.parentNode.removeChild(outer);
return widthNoScroll - widthWithScroll;
};
export const getCell = function(event) {
let cell = event.target;
while (cell && cell.tagName.toUpperCase() !== 'HTML') {
if (cell.tagName.toUpperCase() === 'TD') {
return cell;
}
cell = cell.parentNode;
}
return null;
};
export const getValueByPath = function(object, prop) {
prop = prop || '';
const paths = prop.split('.');
let current = object;
let result = null;
for (let i = 0, j = paths.length; i < j; i++) {
const path = paths[i];
if (!current) break;
if (i === j - 1) {
result = current[path];
break;
}
current = current[path];
}
return result;
};
const isObject = function(obj) {
return obj !== null && typeof obj === 'object';
};
export const orderBy = function(array, sortKey, reverse) {
if (!sortKey) {
return array;
}
const order = (reverse && reverse < 0) ? -1 : 1;
// sort on a copy to avoid mutating original array
return array.slice().sort(function(a, b) {
if (sortKey !== '$key') {
if (isObject(a) && '$value' in a) a = a.$value;
if (isObject(b) && '$value' in b) b = b.$value;
}
a = isObject(a) ? getValueByPath(a, sortKey) : a;
b = isObject(b) ? getValueByPath(b, sortKey) : b;
return a === b ? 0 : a > b ? order : -order;
});
};