import { Store } from 'web/index'; import { BaseLog } from 'base-log'; const log = new BaseLog('Visit'); export class Visit { store = new Store() storeName visits = [] readyHandle isReady constructor (name?) { // type=0 表示初始加载+链接跳转加载,type=1 表示页面刷新,type=2表示前进后退加载 const visitNeedClear = !performance || performance.navigation.type == 0; log.info('visitNeedClear',visitNeedClear); this.storeName = name ? 'visits.' + name : 'visits'; this.store.get(this.storeName).then((visits) => { this.visits = visits || []; if(visitNeedClear) return this.clear(); return Promise.resolve(this.visits); }).then(() => { if(this.readyHandle) this.readyHandle(); this.isReady = true; }); } ready = (readyHandle) => { this.readyHandle = readyHandle; } add = (visit) => { this.visits.push(visit); return this.sync(); } remove = (step) => { if(step >= 0) return; step = step || -1; var len = this.visits.length; var end = len + step; this.visits = this.visits.slice(0, end); return this.sync(); } // 获取索引,如果有多个相同值,则取最后一个索引 findIndex = (visit) => { var index = -1; for (var i = 0, n = this.visits.length; i < n; i++) { var key = this.visits[i]; if(visit == key) index = i; } return index; } getAll = () => { return this.visits; } clear = () => { this.visits = []; return this.sync(); } count = () => { return this.visits.length; } // 同步本地存储 sync = () => { return this.store.set(this.storeName, this.visits); } }