Sidebar.js 10 KB

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