UNPKG

@ray-js/router

Version:

Ray Core

112 lines (107 loc) 2.14 kB
import "core-js/modules/es.regexp.exec.js"; import "core-js/modules/es.string.replace.js"; import { url } from '@ray-js/library'; import { history } from './history'; export class Router { /** * 页面路由调度器 */ /** * 当前环境地址栏 */ constructor(options) { this.scheduler = options.scheduler; // window.router = this } normalizeRoute(params) { const { to } = params; // FIXME: 绝对路径是否需要支持? if (to.startsWith('//') || to.startsWith('http')) { return Promise.resolve({ to }); } // TODO: Web 应用下重复进入一个路由 if (this.$href) { const { pathname, search, hash } = url.parse(this.$href); if (url.format({ pathname, search, hash }) === to) { console.warn('duplicate route to:', to); } } return Promise.resolve({ to }); } /** * 跳转到指定路由 * @param to - routes.config.ts 中配置的路由地址 * @param options * @param options.subpackage - 分包名 * * @example * router.push('/cat', { subpackage: 'packageA' }); */ push(to) { this.normalizeRoute({ to }).then(_ref => { let { to } = _ref; history.push(to); }); } /** * 替换当前路由 * @param to - routes.config.ts 中配置的路由地址 * @param options * @param options.subpackage - 分包名 * * @example * router.replace('/cat', { subpackage: 'packageA' }); */ replace(to) { this.normalizeRoute({ to }).then(_ref2 => { let { to } = _ref2; history.replace(to); }); } go(delta) { // 在应用堆栈内进行跳转 history.go(delta); } back() { history.goBack(); } reload(to) { if (to) { this.normalizeRoute({ to }).then(_ref3 => { let { to } = _ref3; window.location.href = to; }); } else { window.location.reload(); } } get href() { return window.location.href; } }