Skip to content

Commit

Permalink
feat: Add elementFillsContainer utility function
Browse files Browse the repository at this point in the history
  • Loading branch information
guidobouman committed Apr 25, 2018
1 parent 874efc1 commit 3f15f3a
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/utilities.js
Expand Up @@ -45,3 +45,15 @@ export function getElementsInContainerViewport(container, elementList) {
);
});
}

export function elementFillsContainer(container, element) {
const containerRect = getContainerRect(container);
const elementRect = element.getBoundingClientRect();

return (
elementRect.top <= containerRect.top &&
elementRect.bottom >= containerRect.bottom &&
elementRect.left <= containerRect.left &&
elementRect.right >= containerRect.right
);
}
31 changes: 31 additions & 0 deletions src/utilities.test.js
Expand Up @@ -2,6 +2,7 @@ import {
getScrollingElement,
getTargetScrollTop,
getElementsInContainerViewport,
elementFillsContainer,
} from './utilities';

describe('getScrolllingElement', () => {
Expand Down Expand Up @@ -118,3 +119,33 @@ describe('getElementsInContainerViewport', () => {
expect(test2).toHaveLength(1);
});
});


describe('elementFillsContainer', () => {
const SCREEN_WIDTH = 800;
function getElement(top, bottom, left = 0, right = SCREEN_WIDTH) {
const target = document.createElement('div');
target.getBoundingClientRect = () => ({
top, bottom, left, right,
});

return target;
}

test('checks element in body viewport', () => {
window.innerWidth = SCREEN_WIDTH;
window.innerHeight = 600;
expect(elementFillsContainer(document.body, getElement(-100, 700))).toBe(true);
expect(elementFillsContainer(document.body, getElement(0, 600))).toBe(true);
expect(elementFillsContainer(document.body, getElement(1, 601))).toBe(false);
expect(elementFillsContainer(document.body, getElement(-1, 599))).toBe(false);
});

test('checks element in non-body viewport', () => {
const container = getElement(200, 500);
expect(elementFillsContainer(container, getElement(100, 600))).toBe(true);
expect(elementFillsContainer(container, getElement(200, 500))).toBe(true);
expect(elementFillsContainer(container, getElement(201, 501))).toBe(false);
expect(elementFillsContainer(container, getElement(99, 499))).toBe(false);
});
});

0 comments on commit 3f15f3a

Please sign in to comment.