Skip to content

Commit f42bddc

Browse files
committed
search for best number of columns to center horizontally
1 parent 432afd6 commit f42bddc

File tree

1 file changed

+20
-14
lines changed

1 file changed

+20
-14
lines changed

js/views/templates/list.js

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,31 @@
1-
const horizontalGapPercentage = 0.4;
1+
const minHorizontalGapPercentage = 0.3;
22
const verticalGapPercentage = 0.3;
33

4+
const bestHorizontalFit = (windowWidth, objectWidth) => {
5+
let columns = 1;
6+
let percentage =
7+
(windowWidth - columns * objectWidth) / (objectWidth * (1 + columns));
8+
let prevPercentage = percentage;
9+
10+
while (percentage >= minHorizontalGapPercentage) {
11+
prevPercentage = percentage;
12+
columns += 1;
13+
percentage =
14+
(windowWidth - columns * objectWidth) / (objectWidth * (1 + columns));
15+
}
16+
17+
return [columns - 1, prevPercentage];
18+
};
19+
420
export function listView(collection) {
521
const width = window.innerWidth;
622
const length = collection.length;
723

8-
const objWidth = collection[0].width;
9-
const objHorizontalGap = parseInt(horizontalGapPercentage * objWidth);
1024
const objHeight = collection[0].height;
1125
const objVerticalGap = parseInt(verticalGapPercentage * objHeight);
12-
13-
let cols = (width - objHorizontalGap) / (objWidth + objHorizontalGap);
14-
const decimal = cols % 1;
15-
16-
const minDecimal =
17-
(objWidth + 0.5 * objHorizontalGap) / (objWidth + objHorizontalGap);
18-
19-
if (decimal >= minDecimal) {
20-
cols = cols + 1;
21-
}
22-
cols = Math.floor(cols);
26+
const objWidth = collection[0].width;
27+
const [cols, horizontalGapPercentage] = bestHorizontalFit(width, objWidth);
28+
const objHorizontalGap = parseInt(horizontalGapPercentage * objWidth);
2329

2430
const rows = Math.ceil(length / cols);
2531

0 commit comments

Comments
 (0)