Sidebar.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import React, { Component } from "react";
  2. import PropTypes from "prop-types";
  3. import { withTranslation, Trans } from "@/components/Common/Translate";
  4. import Link from "next/link";
  5. import Router, { withRouter } from "next/router";
  6. import { Collapse, Badge } from "reactstrap";
  7. import { connect } from "react-redux";
  8. import { bindActionCreators } from "redux";
  9. import * as actions from "../../store/actions/actions";
  10. import SidebarUserBlock from "./SidebarUserBlock";
  11. // import { getUser } from "@/actions/auth";
  12. import Menu from "./Menu.js";
  13. import MenuLLDIKTI from "./MenuLLDIKTI.js";
  14. import MenuPT from "./MenuPT.js";
  15. import MenuBypass from "./MenuBypass";
  16. // localStorage.getItem("user");
  17. // import Menu from './MenuPT.js';
  18. // Helper to check for parrent of an given elements
  19. const parents = (element, selector) => {
  20. if (typeof selector !== "string") {
  21. return null;
  22. }
  23. const parents = [];
  24. let ancestor = element.parentNode;
  25. while (ancestor && ancestor.nodeType === Node.ELEMENT_NODE && ancestor.nodeType !== 3 /*NODE_TEXT*/) {
  26. if (ancestor.matches(selector)) {
  27. parents.push(ancestor);
  28. }
  29. ancestor = ancestor.parentNode;
  30. }
  31. return parents;
  32. };
  33. // Helper to get outerHeight of a dom element
  34. const outerHeight = (elem, includeMargin) => {
  35. const style = getComputedStyle(elem);
  36. const margins = includeMargin ? parseInt(style.marginTop, 10) + parseInt(style.marginBottom, 10) : 0;
  37. return elem.offsetHeight + margins;
  38. };
  39. /**
  40. Component to display headings on sidebar
  41. */
  42. const SidebarItemHeader = ({ item }) => (
  43. <li className="nav-heading">
  44. <span>
  45. <Trans i18nKey={item.translate}>{item.heading}</Trans>
  46. </span>
  47. </li>
  48. );
  49. /**
  50. Normal items for the sidebar
  51. */
  52. const SidebarItem = ({ item, isActive, className, onMouseEnter }) => (
  53. <li className={isActive ? "active" : ""} onMouseEnter={onMouseEnter}>
  54. <Link href={item.path} as={item.as}>
  55. <a title={item.name}>
  56. {item.label && (
  57. <Badge tag="div" className="float-right" color={item.label.color}>
  58. {item.label.value}
  59. </Badge>
  60. )}
  61. {item.icon && <em className={item.icon} />}
  62. <span>
  63. <Trans i18nKey={item.translate}>{item.name}</Trans>
  64. </span>
  65. </a>
  66. </Link>
  67. </li>
  68. );
  69. /**
  70. Build a sub menu with items inside and attach collapse behavior
  71. */
  72. const SidebarSubItem = ({ item, isActive, handler, children, isOpen, onMouseEnter }) => (
  73. <li className={isActive ? "active" : ""}>
  74. <div className="nav-item" onClick={handler} onMouseEnter={onMouseEnter}>
  75. {item.label && (
  76. <Badge tag="div" className="float-right" color={item.label.color}>
  77. {item.label.value}
  78. </Badge>
  79. )}
  80. {item.icon && <em className={item.icon} />}
  81. <span>
  82. <Trans i18nKey={item.translate}>{item.name}</Trans>
  83. </span>
  84. </div>
  85. <Collapse isOpen={isOpen}>
  86. <ul id={item.path} className="sidebar-nav sidebar-subnav">
  87. {children}
  88. </ul>
  89. </Collapse>
  90. </li>
  91. );
  92. /**
  93. Component used to display a header on menu when using collapsed/hover mode
  94. */
  95. const SidebarSubHeader = ({ item }) => <li className="sidebar-subnav-header">{item.name}</li>;
  96. const SidebarBackdrop = ({ closeFloatingNav }) => <div className="sidebar-backdrop" onClick={closeFloatingNav} />;
  97. const FloatingNav = ({ item, target, routeActive, isFixed, closeFloatingNav }) => {
  98. let asideContainer = document.querySelector(".aside-container");
  99. let asideInner = asideContainer.firstElementChild; /*('.aside-inner')*/
  100. let sidebar = asideInner.firstElementChild; /*('.sidebar')*/
  101. let mar = parseInt(getComputedStyle(asideInner)["padding-top"], 0) + parseInt(getComputedStyle(asideContainer)["padding-top"], 0);
  102. let itemTop = target.parentElement.offsetTop + mar - sidebar.scrollTop;
  103. let vwHeight = document.body.clientHeight;
  104. const setPositionStyle = (el) => {
  105. if (!el) return;
  106. el.style.position = isFixed ? "fixed" : "absolute";
  107. el.style.top = itemTop + "px";
  108. el.style.bottom = outerHeight(el, true) + itemTop > vwHeight ? 0 : "auto";
  109. };
  110. return (
  111. <ul id={item.path} ref={setPositionStyle} className="sidebar-nav sidebar-subnav nav-floating" onMouseLeave={closeFloatingNav}>
  112. <SidebarSubHeader item={item} />
  113. {item.submenu.map((subitem, i) => (
  114. <SidebarItem key={i} item={subitem} isActive={routeActive(subitem.path)} />
  115. ))}
  116. </ul>
  117. );
  118. };
  119. /**
  120. The main sidebar component
  121. */
  122. class Sidebar extends Component {
  123. menu = [];
  124. state = {
  125. collapse: {},
  126. showSidebarBackdrop: false,
  127. currentFloatingItem: null,
  128. currentFloatingItemTarget: null,
  129. pathname: this.props.router.pathname,
  130. };
  131. async componentDidMount() {
  132. // const user = await getUser();
  133. const user = this.props.user;
  134. console.log(user)
  135. this.menu = user.user_id === "28DB23AE-2976-47E0-9410-241A11EE1F88" ? MenuBypass : user.role.id === 2022 ? MenuPT : user.role.id === 2021 ? MenuLLDIKTI : Menu;
  136. // prepare the flags to handle menu collapsed states
  137. this.buildCollapseList();
  138. // Listen for routes changes in order to hide the sidebar on mobile
  139. Router.events.on("routeChangeStart", this.handleRouteChange);
  140. Router.events.on("routeChangeComplete", this.handleRouteComplete);
  141. // Attach event listener to automatically close sidebar when click outside
  142. document.addEventListener("click", this.closeSidebarOnExternalClicks);
  143. }
  144. handleRouteComplete = (pathname) => {
  145. this.setState({
  146. pathname,
  147. });
  148. };
  149. handleRouteChange = () => {
  150. this.closeFloatingNav();
  151. this.closeSidebar();
  152. };
  153. componentWillUnmount() {
  154. document.removeEventListener("click", this.closeSidebarOnExternalClicks);
  155. Router.events.off("routeChangeStart", this.handleRouteChange);
  156. Router.events.off("routeChangeComplete", this.handleRouteComplete);
  157. }
  158. closeSidebar = () => {
  159. this.props.actions.toggleSetting("asideToggled");
  160. };
  161. closeSidebarOnExternalClicks = (e) => {
  162. // don't check if sidebar not visible
  163. if (!this.props.settings.asideToggled) return;
  164. if (
  165. !parents(e.target, ".aside-container").length && // if not child of sidebar
  166. !parents(e.target, ".topnavbar-wrapper").length && // if not child of header
  167. !e.target.matches("#user-block-toggle") && // user block toggle anchor
  168. !e.target.parentElement.matches("#user-block-toggle") // user block toggle icon
  169. ) {
  170. this.closeSidebar();
  171. }
  172. };
  173. /** prepare initial state of collapse menus.*/
  174. buildCollapseList = () => {
  175. let collapse = {};
  176. this.menu
  177. .filter(({ heading }) => !heading)
  178. .forEach(({ name, path, submenu }) => {
  179. collapse[name] = this.routeActive(submenu ? submenu.map(({ path }) => path) : path);
  180. });
  181. this.setState({ collapse });
  182. };
  183. routeActive = (paths) => {
  184. const currpath = this.state.pathname;
  185. paths = Array.isArray(paths) ? paths : [paths];
  186. return paths.some((p) => (p === "/" ? currpath === p : currpath.indexOf(p) > -1));
  187. };
  188. toggleItemCollapse = (stateName) => () => {
  189. for (let c in this.state.collapse) {
  190. if (this.state.collapse[c] === true && c !== stateName)
  191. this.setState({
  192. collapse: {
  193. [c]: false,
  194. },
  195. });
  196. }
  197. this.setState({
  198. collapse: {
  199. [stateName]: !this.state.collapse[stateName],
  200. },
  201. });
  202. };
  203. getSubRoutes = (item) => item.submenu.map(({ path }) => path);
  204. /** map menu config to string to determine which element to render */
  205. itemType = (item) => {
  206. if (item.heading) return "heading";
  207. if (!item.submenu) return "menu";
  208. if (item.submenu) return "submenu";
  209. };
  210. shouldUseFloatingNav = () => {
  211. return this.props.settings.isCollapsed || this.props.settings.isCollapsedText || this.props.settings.asideHover;
  212. };
  213. showFloatingNav = (item) => (e) => {
  214. if (this.shouldUseFloatingNav())
  215. this.setState({
  216. currentFloatingItem: item,
  217. currentFloatingItemTarget: e.currentTarget,
  218. showSidebarBackdrop: true,
  219. });
  220. };
  221. closeFloatingNav = () => {
  222. this.setState({
  223. currentFloatingItem: null,
  224. currentFloatingItemTarget: null,
  225. showSidebarBackdrop: false,
  226. });
  227. };
  228. render() {
  229. return (
  230. <>
  231. <aside className="aside-container">
  232. {/* START Sidebar (left) */}
  233. <div className="aside-inner">
  234. <nav className={"sidebar " + (this.props.settings.asideScrollbar ? "show-scrollbar" : "")}>
  235. {/* START sidebar nav */}
  236. <ul className="sidebar-nav">
  237. {/* START user info */}
  238. <li className="has-user-block">
  239. <SidebarUserBlock />
  240. </li>
  241. {/* END user info */}
  242. {/* Iterates over all sidebar items */}
  243. {this.menu.map((item, i) => {
  244. // heading
  245. if (this.itemType(item) === "heading") return <SidebarItemHeader item={item} key={i} />;
  246. else {
  247. if (this.itemType(item) === "menu") return <SidebarItem isActive={this.routeActive(item.path)} item={item} key={i} onMouseEnter={this.closeFloatingNav} />;
  248. if (this.itemType(item) === "submenu")
  249. return [
  250. <SidebarSubItem
  251. item={item}
  252. isOpen={this.state.collapse[item.name]}
  253. handler={this.toggleItemCollapse(item.name)}
  254. isActive={this.routeActive(this.getSubRoutes(item))}
  255. key={i}
  256. onMouseEnter={this.showFloatingNav(item)}
  257. >
  258. <SidebarSubHeader item={item} key={i} />
  259. {item.submenu.map((subitem, i) => (
  260. <SidebarItem key={i} item={subitem} isActive={this.routeActive(subitem.path)} />
  261. ))}
  262. </SidebarSubItem>,
  263. ];
  264. }
  265. return null; // unrecognized item
  266. })}
  267. </ul>
  268. {/* END sidebar nav */}
  269. </nav>
  270. </div>
  271. {/* END Sidebar (left) */}
  272. {this.state.currentFloatingItem && this.state.currentFloatingItem.submenu && (
  273. <FloatingNav item={this.state.currentFloatingItem} target={this.state.currentFloatingItemTarget} routeActive={this.routeActive} isFixed={this.props.settings.isFixed} closeFloatingNav={this.closeFloatingNav} />
  274. )}
  275. </aside>
  276. {this.state.showSidebarBackdrop && <SidebarBackdrop closeFloatingNav={this.closeFloatingNav} />}
  277. </>
  278. );
  279. }
  280. }
  281. Sidebar.propTypes = {
  282. actions: PropTypes.object,
  283. settings: PropTypes.object,
  284. };
  285. const mapStateToProps = (state) => ({ settings: state.settings, user: state.user });
  286. const mapDispatchToProps = (dispatch) => ({
  287. actions: bindActionCreators(actions, dispatch),
  288. });
  289. export default connect(mapStateToProps, mapDispatchToProps)(withRouter(withTranslation(Sidebar)));