mettle-router
Version:
The official router for mettle.js
7 lines (6 loc) • 2.22 kB
JavaScript
/*!
* Mettle-router v0.6.0
* (c) 2021-2025 maomincoding
* Released under the MIT License.
*/
const t="0.6.0",n={path:"",isMounted:!1,_template:null};function o(t,o){return"function"==typeof o&&window.addEventListener("hashchange",(()=>{n.path=h(),n.isMounted=!1;const r=e(n.path,t);o(r)}),!1),function(){if(n.path)return e(n.path,t);if(location.hash){const o=h();return n.isMounted,e(o,t)}return"/index.html"===location.pathname?e("/",t):e(location.pathname,t)}()}function e(t,o){for(let e=0;e<o.length;e++){const r=o[e];if(r.path===t){if(n.isMounted)return n._template;const t=r.template;return n.isMounted=!0,n._template=t,n._template}}}function r(t){var o;"string"==typeof t||"object"===(o=t,Object.prototype.toString.call(o).match(/\[object (.+?)\]/)[1].toLowerCase())?"string"==typeof t?(window.location.href=`${p()}#${t}`,n.path=t):t.path&&"string"==typeof t.path?(t.query?window.location.href=`${p()}#${t.path}?${function(t){const n=[];for(let o in t)n.push(`${o}=${s(t[o])}`);return n.join("&")}(t.query)}`:window.location.href=`${p()}#${t.path}`,n.path=t.path):console.error("[mettle-router error]: the first parameter of function linkTo should have a param called path with string when it is an ordinary object"):console.error("[mettle-router error]: the first parameter of function linkTo should be a string or a object")}function i(t){window.history.go(t)}function a(){window.history.go(-1)}function c(){window.history.go(1)}function l(){const t=decodeURIComponent(location.href.split("?")[1]).replace(/\+/g," ");if(!t)return{};const n={};return t.split("&").forEach((t=>{const o=t.indexOf("=");if(-1!==o){const e=t.substring(0,o),r=t.substring(o+1,t.length);n[e]=r}})),n}function s(t){return t=(t=(t=(t=(t=(t=(t=(t=(t+="").replace(/%/g,"%25")).replace(/\+/g,"%2B")).replace(/ /g,"%20")).replace(/\//g,"%2F")).replace(/\?/g,"%3F")).replace(/&/g,"%26")).replace(/\=/g,"%3D")).replace(/#/g,"%23")}function h(){return-1!==location.hash.indexOf("?")?location.hash.split("#")[1].split("?")[0]:location.hash.split("#")[1]}function p(){const t=window.location.href,n=t.indexOf("#");return`${n>=0?t.slice(0,n):t}`}export{a as back,c as forward,i as go,o as initRouter,r as linkTo,t as routerVersion,l as toParse};