All files / atoms/Dropdown usePositionBinding.js

0% Statements 0/15
0% Branches 0/6
0% Functions 0/3
0% Lines 0/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37                                                                         
import { useState } from 'react';
import useInterval from 'react-useinterval';
import difference from 'lodash/difference';
import values from 'lodash/values';
 
import { DROPDOWN_PALCEMENT_BL } from './constants';
 
function getDropDownCss(bindTo, placement) {
  if (!bindTo.current) return null;
  const rect = bindTo.current.getBoundingClientRect();
  const top = rect.height + rect.top + 2;
  switch (placement) {
    case DROPDOWN_PALCEMENT_BL:
      return {
        left: rect.left,
        top,
      };
    default:
      return {
        right: window.innerWidth - (rect.left + rect.width),
        top,
      };
  }
}
 
export default (bindTo, placement) => {
  const defaultState = getDropDownCss(bindTo, placement);
  const [state, replaceState] = useState(defaultState);
  function observeChanges() {
    const nextState = getDropDownCss(bindTo, placement);
    const diff = difference(values(nextState), values(state));
    if (diff.length) replaceState(nextState);
  }
  useInterval(observeChanges, 32);
  return state;
};