fly_out_nav.js 2.1 KB
Newer Older
1
import Cookies from 'js-cookie';
2
import bp from './breakpoints';
3

4 5 6 7 8 9 10 11 12 13
export const canShowActiveSubItems = (el) => {
  const isHiddenByMedia = bp.getBreakpointSize() === 'sm' || bp.getBreakpointSize() === 'md';

  if (el.classList.contains('active') && !isHiddenByMedia) {
    return Cookies.get('sidebar_collapsed') === 'true';
  }

  return true;
};
export const canShowSubItems = () => bp.getBreakpointSize() === 'sm' || bp.getBreakpointSize() === 'md' || bp.getBreakpointSize() === 'lg';
14

15 16 17 18
export const calculateTop = (boundingRect, outerHeight) => {
  const windowHeight = window.innerHeight;
  const bottomOverflow = windowHeight - (boundingRect.top + outerHeight);

19 20
  return bottomOverflow < 0 ? (boundingRect.top - outerHeight) + boundingRect.height :
    boundingRect.top;
21 22
};

P
Phil Hughes 已提交
23
export const showSubLevelItems = (el) => {
P
Phil Hughes 已提交
24
  const subItems = el.querySelector('.sidebar-sub-level-items');
P
Phil Hughes 已提交
25

26
  if (!subItems || !canShowSubItems() || !canShowActiveSubItems(el)) return;
P
Phil Hughes 已提交
27

P
Phil Hughes 已提交
28
  subItems.style.display = 'block';
29
  el.classList.add('is-showing-fly-out');
P
Phil Hughes 已提交
30
  el.classList.add('is-over');
P
Phil Hughes 已提交
31 32

  const boundingRect = el.getBoundingClientRect();
P
Phil Hughes 已提交
33
  const top = calculateTop(boundingRect, subItems.offsetHeight);
P
Phil Hughes 已提交
34 35
  const isAbove = top < boundingRect.top;

36
  subItems.classList.add('fly-out-list');
P
Phil Hughes 已提交
37
  subItems.style.transform = `translate3d(0, ${Math.floor(top)}px, 0)`;
P
Phil Hughes 已提交
38 39

  if (isAbove) {
P
Phil Hughes 已提交
40
    subItems.classList.add('is-above');
P
Phil Hughes 已提交
41 42 43 44
  }
};

export const hideSubLevelItems = (el) => {
P
Phil Hughes 已提交
45
  const subItems = el.querySelector('.sidebar-sub-level-items');
P
Phil Hughes 已提交
46

47
  if (!subItems || !canShowSubItems() || !canShowActiveSubItems(el)) return;
P
Phil Hughes 已提交
48

49
  el.classList.remove('is-showing-fly-out');
P
Phil Hughes 已提交
50
  el.classList.remove('is-over');
51 52
  subItems.style.display = '';
  subItems.style.transform = '';
P
Phil Hughes 已提交
53
  subItems.classList.remove('is-above');
P
Phil Hughes 已提交
54 55
};

56
export default () => {
57
  const items = [...document.querySelectorAll('.sidebar-top-level-items > li')]
P
Phil Hughes 已提交
58
    .filter(el => el.querySelector('.sidebar-sub-level-items'));
P
Phil Hughes 已提交
59 60 61 62 63

  items.forEach((el) => {
    el.addEventListener('mouseenter', e => showSubLevelItems(e.currentTarget));
    el.addEventListener('mouseleave', e => hideSubLevelItems(e.currentTarget));
  });
64
};