-
Notifications
You must be signed in to change notification settings - Fork 1
/
history.ts
286 lines (249 loc) · 9.89 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
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import Manager from './manager';
import {FieldKinds, FieldFilters, FieldSearches} from './types';
import {reaction, toJS, runInAction, decorate, observable} from 'mobx';
import debounce from 'lodash.debounce';
import UrlStore from 'query-params-data';
import pkg from '../package.json';
export type FilterHistoryPlace = {
fieldKinds?: FieldKinds<any>;
fieldFilters?: FieldFilters<any, any>;
};
export type SuggestionHistoryPlace = {
fieldKinds?: FieldKinds<any>;
fieldSearches?: FieldSearches<any>;
};
export type HistoryLocation = {
filters?: Record<string, FilterHistoryPlace>;
suggestions?: Record<string, SuggestionHistoryPlace>;
};
export interface IHistoryOptions<State> {
historySize?: number;
currentLocationStore?: ICurrentLocationStore<State>;
historyPersister?: IHistoryPersister;
rehydrateOnStart?: boolean;
}
export type CurrentLocationStateObserver<State> = (newState: State | undefined) => any;
export interface ICurrentLocationStore<State> {
setState: (
location: State | undefined,
options?: {
replaceLocation: boolean;
}
) => void;
getState: () => State | undefined | void;
subscribeToStateChanges: (
observer: CurrentLocationStateObserver<State>,
options?: {getCurrentState: boolean}
) => void;
}
export interface IHistoryPersister {
setHistory: (location: Array<HistoryLocation | undefined>) => void;
getHistory: () => HistoryLocation[];
}
const LOCAL_STORAGE_KEY = `${pkg.name}/history`;
export const localStorageHistoryPersister = (localStorageSuffix: string): IHistoryPersister => ({
setHistory: (location: Array<HistoryLocation | undefined>) => {
localStorage.setItem(
`${LOCAL_STORAGE_KEY}/${localStorageSuffix}`,
JSON.stringify(location)
);
},
getHistory: () => {
const existingHistory = localStorage.getItem(`${LOCAL_STORAGE_KEY}/${localStorageSuffix}`);
if (existingHistory) {
try {
return JSON.parse(existingHistory);
} catch {
return [];
}
} else {
return [];
}
}
});
class History {
public historySize: number;
public manager: Manager;
public history: Array<HistoryLocation | undefined>;
public currentLocationInHistoryCursor: number;
public currentLocationStore: ICurrentLocationStore<HistoryLocation>;
public historyPersister: IHistoryPersister | undefined;
public hasRehydratedLocation: boolean;
constructor(
manager: Manager,
queryParamKey: string,
options?: IHistoryOptions<HistoryLocation>
) {
// tslint:disable-next-line
runInAction(() => {
this.manager = manager;
this.historySize = (options && options.historySize) || 30;
this.currentLocationStore =
(options && options.currentLocationStore) ||
new UrlStore<HistoryLocation>(queryParamKey);
this.currentLocationInHistoryCursor = 0;
this.history = [];
this.historyPersister = options && options.historyPersister;
this.hasRehydratedLocation = false;
if (options && options.rehydrateOnStart) {
this.rehydrate();
}
});
this.currentLocationStore.subscribeToStateChanges(this._currentStateSubscriber, {
getCurrentState: false
});
const debounceHistoryChange = debounce(this._recordHistoryChange, 300);
reaction(() => {
return Object.keys(this.manager.filters).reduce((acc, filterName) => {
return {
acc,
[filterName]: toJS(
this.manager.filters[filterName]._shouldRunFilteredQueryAndAggs
)
};
}, {});
}, debounceHistoryChange);
Object.keys(this.manager.suggestions).forEach(suggesterName => {
const suggester = this.manager.suggestions[suggesterName];
suggester._subscribeToShouldRunSuggestionSearch(debounceHistoryChange);
});
reaction(
() => {
return {
mostRecentLocation: this._deepCopy(this.history[0] || {}),
historyLength: this.history.length
};
},
() => {
if (this.historyPersister) {
this.historyPersister.setHistory(this.history);
}
},
{fireImmediately: true}
);
}
/**
* Rehydrates state from current state store (URL) or persistent storage (localStorage)
*/
public rehydrate = () => {
// tslint:disable-next-line
runInAction(() => {
if (this.historyPersister) {
const persistedHistory = this.historyPersister.getHistory();
this.history = persistedHistory;
if (persistedHistory.length > 0) {
const existingStateFromUrl = this.currentLocationStore.getState();
if (!existingStateFromUrl) {
const newHistoryLocation = this._deepCopy(
persistedHistory[0] as HistoryLocation
);
// if only suggestions are present then we should
// act as if no location was rehydrated
if (newHistoryLocation.filters) {
this.hasRehydratedLocation = true;
}
this.currentLocationStore.setState(newHistoryLocation);
this._rehydrateFromLocation(newHistoryLocation);
} else {
if (existingStateFromUrl.filters) {
this.hasRehydratedLocation = true;
}
this._rehydrateFromLocation(existingStateFromUrl);
}
} else {
const existingStateFromUrl = this.currentLocationStore.getState();
if (existingStateFromUrl) {
if (existingStateFromUrl.filters) {
this.hasRehydratedLocation = true;
}
this._rehydrateFromLocation(existingStateFromUrl);
}
}
}
});
};
// tslint:disable-next-line
public _recordHistoryChange = () => {
const newHistoryLocation = this.manager.getUserState();
const newLocationString = JSON.stringify(newHistoryLocation);
const existingLocationString = JSON.stringify(
this.history[this.currentLocationInHistoryCursor]
);
if (newLocationString !== existingLocationString) {
this.addToHistory({...newHistoryLocation});
this.currentLocationStore.setState({...newHistoryLocation});
}
};
public _currentStateSubscriber = (newHistoryLocation: HistoryLocation | undefined) => {
if (
newHistoryLocation &&
JSON.stringify(newHistoryLocation) !==
JSON.stringify(this.history[this.currentLocationInHistoryCursor])
) {
this.addToHistory({...newHistoryLocation});
this._rehydrateFromLocation({...newHistoryLocation});
}
};
public _deepCopy = (location: HistoryLocation): HistoryLocation =>
JSON.parse(JSON.stringify(location));
public addToHistory = (location: HistoryLocation | undefined) => {
runInAction(() => {
this.history = [
this._deepCopy(location as HistoryLocation),
...this.history.slice(this.currentLocationInHistoryCursor, this.historySize - 1)
];
this.currentLocationInHistoryCursor = 0;
});
};
public setCurrentState = (location: HistoryLocation): void => {
this.currentLocationStore.setState({...location});
};
public _rehydrateFromLocation = (location: HistoryLocation | undefined = {}) => {
runInAction(() => {
this.manager.setUserState(location);
});
};
public clearHistory = (): void => {
runInAction(() => {
this.history = [];
this.currentLocationInHistoryCursor = 0;
});
};
public back = (): void => {
this._go(-1);
};
public forward = (): void => {
this._go(1);
};
// adapted from https://github.com/erhathaway/router-primitives (MIT licensed)
// tslint:disable-next-line
public _go = (historyChange: number): void => {
if (!historyChange || historyChange === 0) {
throw new Error('No history size change specified');
}
// calculate request history location
const newLocation = this.currentLocationInHistoryCursor - historyChange;
runInAction(() => {
// if within the range of recorded history, set as the new history location
if (newLocation + 1 <= this.history.length && newLocation >= 0) {
this.currentLocationInHistoryCursor = newLocation;
// if too far in the future, set as the most recent history
} else if (newLocation + 1 <= this.history.length) {
this.currentLocationInHistoryCursor = 0;
// if too far in the past, set as the last recorded history
} else if (newLocation >= 0) {
this.currentLocationInHistoryCursor = this.history.length - 1;
}
const newHistoryLocation = this._deepCopy(
this.history[this.currentLocationInHistoryCursor] as HistoryLocation
);
this.currentLocationStore.setState(newHistoryLocation);
this._rehydrateFromLocation(newHistoryLocation);
});
};
}
decorate(History, {
history: observable,
currentLocationInHistoryCursor: observable
});
export default History;