-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDSRDataStore.ts
95 lines (80 loc) · 2.57 KB
/
DSRDataStore.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
import { StateOrName, UIRouter } from '@uirouter/core';
import { RecordedDSR } from './interface';
export interface DSRDataStore {
init(router: UIRouter): void;
// Gets the remembered DSR target state for a given state and params
get(state: StateOrName): RecordedDSR[];
// Sets the remembered DSR target state for a given state and params
set(state: StateOrName, recordedDSR: RecordedDSR[] | undefined): void;
}
export class StateObjectDataStore implements DSRDataStore {
private router: UIRouter;
private getState(stateOrName: StateOrName) {
const state = this.router.stateService.get(stateOrName);
return state && state.$$state();
}
public init(router: UIRouter): void {
this.router = router;
}
public get(stateOrName: StateOrName): RecordedDSR[] {
return this.getState(stateOrName).$dsr || [];
}
public set(stateOrName: StateOrName, recordedDsr: RecordedDSR[]): void {
const state = this.getState(stateOrName);
if (recordedDsr) {
state.$dsr = recordedDsr;
} else {
delete state.$dsr;
}
}
}
export class LocalStorageDataStore implements DSRDataStore {
private router: UIRouter;
private key = 'uiRouterDeepStateRedirect';
private _storage: Storage = localStorage;
constructor(storage?: Storage) {
this._storage = storage || localStorage;
}
private getStore() {
const item = this._storage.getItem(this.key);
return JSON.parse(item || '{}');
}
private setStore(contents: any) {
if (contents) {
try {
this._storage.setItem(this.key, JSON.stringify(contents));
} catch (err) {
console.error(
'UI-Router Deep State Redirect: cannot store object in LocalStorage. Is there a circular reference?',
contents
);
console.error(err);
}
} else {
this._storage.removeItem(this.key);
}
}
private getStateName(stateOrName: StateOrName) {
const state = this.router.stateService.get(stateOrName);
return state && state.name;
}
public init(router: UIRouter): void {
this.router = router;
}
public get(stateOrName: StateOrName): RecordedDSR[] {
const stateName = this.getStateName(stateOrName);
const store = this.getStore();
return store[stateName] || [];
}
public set(stateOrName: StateOrName, recordedDsr: RecordedDSR[]): void {
const stateName = this.getStateName(stateOrName);
const store = this.getStore();
store[stateName] = recordedDsr;
this.setStore(store);
}
}
export class SessionStorageDataStore extends LocalStorageDataStore {
constructor() {
super(sessionStorage);
}
}