Skip to content

Instantly share code, notes, and snippets.

@vanquyettran
Created July 12, 2018 12:34
Show Gist options
  • Save vanquyettran/c002ed4dc6058b65ade39ef378c9c146 to your computer and use it in GitHub Desktop.
Save vanquyettran/c002ed4dc6058b65ade39ef378c9c146 to your computer and use it in GitHub Desktop.
public updateGrid() {
console.log('updating grid');
const columnCount = 5;
const spaceBetween = 30;
const ulTag = this.grid.nativeElement;
const liTags = ulTag.children;
const liTagLoadedList = [];
if (liTags.length > 0) {
this.updateLoadingState(true);
const setPositions = () => {
const columnHeights = [];
for (let i = 0; i < columnCount; i++) {
columnHeights[i] = 0;
}
[].forEach.call(liTags, (liTag) => {
const columnIndex = columnHeights.indexOf(Math.min(...columnHeights));
liTag.style.left = `calc(${columnIndex * 100}% / ${columnCount} - ${
columnIndex * spaceBetween * (columnCount - 1) / columnCount}px + ${columnIndex * spaceBetween}px)`;
liTag.style.top = columnHeights[columnIndex] + 'px';
liTag.classList.remove('invisible');
columnHeights[columnIndex] += spaceBetween + liTag.offsetHeight;
this.updateLoadingState(false);
});
ulTag.style.height = Math.max(...columnHeights) + 'px';
};
[].forEach.call(liTags, (liTag, liIndex) => {
// console.log(liTag);
liTag.style.width = `calc(100% / ${columnCount} - ${spaceBetween * (columnCount - 1) / columnCount}px)`;
liTagLoadedList[liIndex] = false;
const tryDelay = 50; // 20ms
const loadingHeightsMaxLength = 4; // increase this value will increase loading time, but decrease height error
const loadingHeights = [];
let listenLoading = true;
setInterval(() => {
loadingHeights.push(liTag.offsetHeight);
if (loadingHeights.length === loadingHeightsMaxLength) {
loadingHeights.shift();
// check if last heights is same (no change when time change) ==> item loaded
if (listenLoading) {
// clearInterval(interval);
if (loadingHeights.every(height => height === loadingHeights[0])) {
listenLoading = false;
liTagLoadedList[liIndex] = true;
if (liTagLoadedList.every(loaded => loaded)) {
setPositions();
}
}
} else {
if (loadingHeights.some(height => height !== loadingHeights[0])) {
listenLoading = true;
}
}
}
}, tryDelay);
});
} else {
this.updateLoadingState(false);
ulTag.style.height = '0px';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment