-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhistory.ts
105 lines (90 loc) · 2.39 KB
/
history.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { Module } from 'vuex'
import { Route } from 'vue-router'
import invariant from 'tiny-invariant'
import { RootState } from '../global'
import { RECORD_MAX_VAL } from '../../constants'
export interface HistoryState {
recordHead: RecordItem | null
}
export class RecordItem {
name?: string
fullPath: string
constructor(route: Route, public next: RecordItem | null = null) {
this.fullPath = route.fullPath
if (route.meta && route.meta.title) {
this.name = route.meta.title
}
}
}
const history: Module<HistoryState, RootState> = {
namespaced: true,
state: {
recordHead: null
},
getters: {
isInList({ recordHead }) {
return (route: Route) => {
let current = recordHead
while (current) {
if (current.fullPath === route.fullPath) return true
current = current.next
}
return false
}
}
},
mutations: {
append(state, route: Route) {
if (!state.recordHead) {
state.recordHead = new RecordItem(route)
return
}
let current: RecordItem | null = state.recordHead
let size = 1
invariant(
RECORD_MAX_VAL > 1,
'[module/history]: RECORD_MAX_VAL should be greater then 1'
)
while (current.next) {
++size
current = current.next
}
// drop the head when exceed
if (size === RECORD_MAX_VAL) {
state.recordHead = state.recordHead.next
}
// a new tail element of linked list
current.next = new RecordItem(route)
},
prepend(state, route: Route) {
if (!state.recordHead) {
state.recordHead = new RecordItem(route)
return
}
let current: RecordItem | null = state.recordHead
let size = 1
invariant(
RECORD_MAX_VAL > 1,
'[module/history]: RECORD_MAX_VAL should be greater then 1'
)
state.recordHead = new RecordItem(route, state.recordHead)
while (current.next) {
++size
if (size === RECORD_MAX_VAL) {
// drop the tail element
current.next = null
break
}
current = current.next
}
}
},
actions: {
append({ commit, getters }, to: Route) {
if (!to.meta || !to.meta.title || getters.isInList(to)) return
// only add it when it doesn't exist in the linked-list
commit('append', to)
}
}
}
export default history