Sidebar.js 10 KB

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