summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/new_sidebar.js
blob: 2d1ed9e40761575eeb8fa2bae12978dc939f17a2 (plain)
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import Cookies from 'js-cookie';
import _ from 'underscore';
import bp from './breakpoints';

export default class NewNavSidebar {
  constructor() {
    this.initDomElements();
    this.render();
  }

  initDomElements() {
    this.$page = $('.page-with-sidebar');
    this.$sidebar = $('.nav-sidebar');
    this.$overlay = $('.mobile-overlay');
    this.$openSidebar = $('.toggle-mobile-nav');
    this.$closeSidebar = $('.close-nav-button');
    this.$sidebarToggle = $('.js-toggle-sidebar');
  }

  bindEvents() {
    this.$openSidebar.on('click', () => this.toggleSidebarNav(true));
    this.$closeSidebar.on('click', () => this.toggleSidebarNav(false));
    this.$overlay.on('click', () => this.toggleSidebarNav(false));
    this.$sidebarToggle.on('click', () => {
      const value = !this.$sidebar.hasClass('sidebar-icons-only');
      this.toggleCollapsedSidebar(value);
    });

    $(window).on('resize', () => _.debounce(this.render(), 100));
  }

  static setCollapsedCookie(value) {
    if (bp.getBreakpointSize() !== 'lg') {
      return;
    }
    Cookies.set('sidebar_collapsed', value, { expires: 365 * 10 });
  }

  toggleSidebarNav(show) {
    this.$sidebar.toggleClass('nav-sidebar-expanded', show);
    this.$overlay.toggleClass('mobile-nav-open', show);
    this.$sidebar.removeClass('sidebar-icons-only');
  }

  toggleCollapsedSidebar(collapsed) {
    const breakpoint = bp.getBreakpointSize();

    if (this.$sidebar.length) {
      this.$sidebar.toggleClass('sidebar-icons-only', collapsed);
      this.$page.toggleClass('page-with-new-sidebar', !collapsed);
      this.$page.toggleClass('page-with-icon-sidebar', breakpoint === 'sm' ? true : collapsed);
    }
    NewNavSidebar.setCollapsedCookie(collapsed);
  }

  render() {
    const breakpoint = bp.getBreakpointSize();

    if (breakpoint === 'sm' || breakpoint === 'md') {
      this.toggleCollapsedSidebar(true);
    } else if (breakpoint === 'lg') {
      const collapse = Cookies.get('sidebar_collapsed') === 'true';
      this.toggleCollapsedSidebar(collapse);
    }
  }
}