This repository has been archived by the owner on Apr 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
VuexMultiHistory.ts
229 lines (189 loc) · 6.41 KB
/
VuexMultiHistory.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import Vue from 'vue';
import { MutationPayload, Plugin, Store } from 'vuex';
import {
DefaultKey,
DeserializeFunction,
FilterFunction,
HistorySnapshot,
InvalidOptionsError,
InvalidTypeError,
InvalidValueError,
ResolveFunction,
SerializeFunction,
} from './';
import { VuexHistory } from './VuexHistory';
// tslint:disable-next-line
const DEFAULT_FILTER: FilterFunction = function(mutation: MutationPayload) {
return true;
};
// tslint:disable-next-line
const DEFAULT_RESOLVE: ResolveFunction = function(mutation: MutationPayload) {
return [this.options.histories.keys[0]];
};
// tslint:disable-next-line
const DEFAULT_SERIALIZE: SerializeFunction = function(historyKey: string, state: any) {
return state;
};
// tslint:disable-next-line
const DEFAULT_DESERIALIZE: DeserializeFunction = function(historyKey: string, stateData: any, state: any) {
return stateData;
};
export const DEFAULT_KEY: DefaultKey = 'default';
type HistoryMap = Record<string, VuexHistory>;
interface Data {
historyMap: HistoryMap;
}
export interface HistoriesOptions {
keys: string[];
resolve: ResolveFunction;
}
export interface TransformOptions {
serialize: SerializeFunction;
deserialize: DeserializeFunction;
}
export interface VuexMultiHistoryOptions {
debug?: boolean;
size?: number;
filter?: FilterFunction;
histories?: HistoriesOptions;
transform?: TransformOptions;
}
const generateDefaultOptions: () => Required<VuexMultiHistoryOptions> = () => {
return {
debug: false,
size: 50,
filter: DEFAULT_FILTER,
histories: {
keys: [DEFAULT_KEY],
resolve: DEFAULT_RESOLVE,
},
transform: {
serialize: DEFAULT_SERIALIZE,
deserialize: DEFAULT_DESERIALIZE,
},
};
};
export class VuexMultiHistory<STATE = any> {
readonly plugin: Plugin<any>;
readonly data: Data;
readonly options: Required<VuexMultiHistoryOptions>;
store!: Store<STATE>;
private hasInstalled: boolean = false;
constructor(options?: Partial<VuexMultiHistoryOptions>) {
this.options = Object.assign(generateDefaultOptions(), options);
this.validateOptions();
const dataObj: Data = {
historyMap: {},
};
for (const key of this.options.histories.keys) {
dataObj.historyMap[key] = new VuexHistory(this, key);
}
this.data = Vue.observable<Data>(dataObj);
this.plugin = (store: Store<any>) => {
this.store = store;
this.validateOptions();
for (const key in this.data.historyMap) {
if (this.data.historyMap.hasOwnProperty(key)) {
this.data.historyMap[key].init();
}
}
store.subscribe((mutation, state) => {
if (this.options.filter && !this.options.filter.call(this, mutation)) {
return;
}
const resolvedHistoryKeys = this.options.histories.resolve.call(this, mutation);
const localHistoryKeys = Object.keys(this.data.historyMap);
for (const resolvedHistoryKey of resolvedHistoryKeys) {
if (!this.data.historyMap[resolvedHistoryKey]) {
const keysString = localHistoryKeys.join(', ');
throw new Error(`'${resolvedHistoryKey}' is not a valid key! Valid keys are: [${keysString}]}`);
}
const history = this.getHistory(resolvedHistoryKey);
const snapshot: HistorySnapshot = {
mutation: mutation.type,
stateData: this.serialize(resolvedHistoryKey, state),
};
history.addSnapshot(snapshot);
}
});
store.addHistory = this.addHistory.bind(this);
store.hasHistory = this.hasHistory.bind(this);
store.history = this.getHistory.bind(this);
store.listHistoryKeys = this.listHistoryKeys.bind(this);
store.removeHistory = this.removeHistory.bind(this);
this.hasInstalled = true;
};
}
addHistory(historyKey: string): VuexHistory | undefined {
if (this.data.historyMap[historyKey]) {
return;
}
const history = new VuexHistory(this, historyKey);
if (this.hasInstalled) {
history.init();
}
Vue.set(this.data.historyMap, historyKey, history);
return history;
}
hasHistory(historyKey: string): boolean {
return !!this.data.historyMap[historyKey];
}
getHistory(historyKey?: string): VuexHistory {
const key = historyKey || this.options.histories.keys[0];
if (!this.data.historyMap[key]) {
throw new Error(`Cannot retrieve history for key '${key}'`);
}
return this.data.historyMap[key];
}
listHistoryKeys(): string[] {
return Object.keys(this.data.historyMap);
}
removeHistory(historyKey: string): VuexHistory | undefined {
if (!this.data.historyMap[historyKey]) {
return;
}
const history = this.data.historyMap[historyKey];
Vue.delete(this.data.historyMap, historyKey);
return history;
}
serialize(historyKey: string, state: STATE): any {
return this.removeObservers(this.options.transform.serialize.call(this, historyKey, state));
}
deserialize(historyKey: string, stateData: any): any {
return this.removeObservers(this.options.transform.deserialize.call(this, historyKey, stateData, this.store.state));
}
private validateOptions() {
const errors: Error[] = [];
const size = this.options.size;
if (typeof size !== 'number') {
errors.push(new InvalidTypeError('size', 'number'));
} else if (size <= 0) {
errors.push(new InvalidValueError('size', 'has to be greater than zero'));
}
const filter = this.options.filter;
if (typeof filter !== 'function') {
errors.push(new InvalidTypeError('filter', 'function'));
}
const { resolve, keys } = this.options.histories;
if (typeof resolve !== 'function') {
errors.push(new InvalidTypeError('resolve', 'function'));
}
if (typeof keys !== 'object' || !Array.isArray(keys)) {
errors.push(new InvalidTypeError('keys', 'array'));
}
const { serialize, deserialize } = this.options.transform;
if (typeof serialize !== 'function') {
errors.push(new InvalidTypeError('serialize', 'function'));
}
if (typeof deserialize !== 'function') {
errors.push(new InvalidTypeError('deserialize', 'function'));
}
if (errors.length > 0) {
const introLine = `The following errors occurred when validating the options of 'VuexMultiHistory':`;
throw new InvalidOptionsError(introLine, ...errors);
}
}
private removeObservers<T = any>(obj: T): T {
return JSON.parse(JSON.stringify(obj)) as T;
}
}