-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter-vanilla.js
1 lines (1 loc) · 2.77 KB
/
router-vanilla.js
1
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.routerVanilla=e():t.routerVanilla=e()}(self,(function(){return(()=>{"use strict";var t={d:(e,o)=>{for(var s in o)t.o(o,s)&&!t.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:o[s]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{Router:()=>o,View:()=>s});const o=class{defaults={options:{loadScript:()=>{},topOfPage:{top:0,left:0,behavior:"smooth"}}};constructor(t,e,o,s,a){this.root=t,this.nav=e,this.display=o,this.routes=s,this.root.appendChild(this.nav),this.root.appendChild(this.display),window.addEventListener("popstate",this.populateRoute),this.loadScript=a&&a.loadScript?a.loadScript:this.defaults.options.loadScript,this.topOfPage=a&&a.topOfPage?a.topOfPage:this.defaults.options.topOfPage,this.addRoutesToNav(),this.populateRoute()}addRoutesToNav=(t="NavLink",e="Sub")=>{this.routes.forEach((o=>{const s=e=>{const o=document.createElement("a");return o.innerText=e.title,o.classList.add(t),o.href=e.path,o.addEventListener("click",(t=>{t.preventDefault(),this.navigate(t.target.href)})),o},a=document.createElement("div");if(a.appendChild(s(o)),this.nav.appendChild(a),o.subRoutes&&o.subRoutes.some((t=>t.display))){const t=document.createElement("div");t.classList.add("SubMenu"),a.addEventListener("mouseenter",(e=>t.classList.add("hovered"))),a.addEventListener("mouseleave",(e=>t.classList.remove("hovered"))),o.subRoutes.filter((t=>t.display)).forEach((o=>{const a=s(o);a.classList.add(e),t.appendChild(a)})),a.appendChild(t)}}))};regExPath=t=>new RegExp("^"+t.replace(/\//g,"\\/").replace(/:\w+/g,"(.+)")+"$");populateRoute=t=>{const e=new((this.routes.map((t=>({...t,isMatch:location.pathname.match(this.regExPath(t.path))}))).find((t=>t.isMatch))||{...this.routes[0],isMatch:!0}).view);this.handleActiveLink(),this.display.innerHTML=e.renderHtml(),window.scrollTo(this.topOfPage),document.querySelectorAll("a.internal").forEach((t=>{t.addEventListener("click",(t=>{t.preventDefault(),this.navigate(t.target.href)}))})),this.loadScript()};navigate=t=>{history.pushState(null,null,t),this.populateRoute()};handleActiveLink=t=>{this.nav.childNodes.forEach((t=>{const e=[...this.routes,...this.routes.filter((t=>t.subRoutes)).map((t=>t.subRoutes)).flat()].find((t=>t.path===location.pathname));e&&Array.from(t.childNodes).some((t=>t.innerText===e.title))?t.classList.add("active"):t.classList.remove("active")}))}},s=class{constructor(t){this.baseTitle=t}setTitle(t){document.title=`${this.baseTitle}${t?` - ${t}`:""}`}renderHTML(){return""}};return e})()}));