Skip to content

Commit 8e0ee69

Browse files
fix(ui): gallery grid calculation (#6889)
## Summary There was an issue w/ the calculation causing an infinite loop but the fixed algorithm from #6887 wasn't correct bc it doesn't take into account the grid gap correctly. This then breaks arrow key navigation. - Restore the previous calculation - Bail out if the gallery elements don't have any width, which causes the infinite loop - this part was missed when copying the logic from GalleryImageGrid ## Related Issues / Discussions n/a ## QA Instructions shouldn't freeze ## Merge Plan n/a ## Checklist - [x] _The PR has a short but descriptive title, suitable for a changelog_ - [ ] _Tests added / updated (if applicable)_ - [ ] _Documentation added / updated (if applicable)_
2 parents f47cf39 + 401577b commit 8e0ee69

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

invokeai/frontend/web/src/features/gallery/hooks/useGalleryNavigation.ts

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ const getImagesPerRow = (): number => {
3535
if (!imageEl || !gridEl) {
3636
return 0;
3737
}
38-
3938
const container = gridEl.parentElement;
4039
if (!container) {
4140
return 0;
@@ -44,16 +43,27 @@ const getImagesPerRow = (): number => {
4443
const imageRect = imageEl.getBoundingClientRect();
4544
const containerRect = container.getBoundingClientRect();
4645

46+
// We need to account for the gap between images
4747
const gridElStyle = window.getComputedStyle(gridEl);
4848
const gap = parseFloat(gridElStyle.gap);
4949

50-
// Validate input values
51-
if (imageRect.width <= 0 || gap < 0) {
50+
if (!imageRect.width || !imageRect.height || !containerRect.width || !containerRect.height) {
51+
// Gallery is too small to fit images or not rendered yet
5252
return 0;
5353
}
5454

55-
// Calculate maximum number of images per row
56-
const imagesPerRow = Math.floor((containerRect.width + 1) / (imageRect.width + gap));
55+
let imagesPerRow = 0;
56+
let spaceUsed = 0;
57+
58+
// Floating point precision can cause imagesPerRow to be 1 too small. Adding 1px to the container size fixes
59+
// this, without the possibility of accidentally adding an extra column.
60+
while (spaceUsed + imageRect.width <= containerRect.width + 1) {
61+
imagesPerRow++; // Increment the number of images
62+
spaceUsed += imageRect.width; // Add image size to the used space
63+
if (spaceUsed + gap <= containerRect.width) {
64+
spaceUsed += gap; // Add gap size to the used space after each image except after the last image
65+
}
66+
}
5767

5868
return imagesPerRow;
5969
};

0 commit comments

Comments
 (0)