UNPKG

web-portals

Version:

web-portals

98 lines (87 loc) 2.63 kB
'use strict' import { Application } from '../Application' import { TransformProptey } from './proptey' class TransformHistory extends TransformProptey { public history: number = 0 public historyIndex: number = history.length public historyDirection: number = 0 private backoutCount: number = 0 constructor (app: Application) { super(app) this.bindHistoryState() } private bindHistoryState () { addEventListener('popstate', this.popstate.bind(this)) } public popstate (event: PopStateEvent) { const state = event.state const { historyIndex } = state if (historyIndex < this.historyIndex) { this.historyDirection = -1 } else { this.historyDirection = 1 } this.historyIndex = historyIndex this.back(event) } public pushState (id = '', title = '', search = location.search, param = '') { id = encodeURIComponent(id) history.pushState({ id, title, time: Date.now(), search, historyIndex: history.length + 1 }, title, location.pathname + search + '#' + id + '/' + param) this.historyIndex = history.length this.historyDirection = 1 } public replaceState (id = '', title = '', search = location.search, param = '') { id = encodeURIComponent(id) history.replaceState({ id, title, time: Date.now(), search, historyIndex: history.length }, title, location.pathname + search + '#' + id + '/' + param) this.historyIndex = history.length this.historyDirection = 1 } public async back (event: PopStateEvent) { const options = this.options const route = event.state || this.app.route const id = decodeURIComponent(route.id) || options.index || 'frameworks' const search = route.search const module = await this.app.get(id) if (!module) return /** * 如果设置了单向锁,且回退时模块层级为 0 时 * 阻止返回,并发送事件 */ if (this.checkSingleLock()) { this.backoutCount++ this.pushState(id, module.config.title, search) this.app.trigger('exit', { backoutCount: this.backoutCount }) return } else { this.backoutCount = 0 } if (options.singleFlow && module.config.level !== 0 && module.config.level >= this.module.config.level) { return history.back() } this.app.transform.to(id, search, -1) this.app.trigger('back', { id, module }) } public checkSingleLock (): boolean { return this.options.singleLock && this.module.config.level === 0 ? true : false } } export { TransformHistory }