-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
state_sync.ts
207 lines (195 loc) · 5.78 KB
/
state_sync.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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { EMPTY, Subscription } from 'rxjs';
import { tap } from 'rxjs';
import defaultComparator from 'fast-deep-equal';
import { IStateSyncConfig } from './types';
import { IStateStorage } from './state_sync_state_storage';
import { distinctUntilChangedWithInitialValue } from '../../common';
import { BaseState } from '../../common/state_containers';
import { applyDiff } from '../state_management/utils/diff_object';
/**
* @public
*/
export type StopSyncStateFnType = () => void;
/**
* @public
*/
export type StartSyncStateFnType = () => void;
/**
* @public
*/
export interface ISyncStateRef<StateStorage extends IStateStorage = IStateStorage> {
/**
* stop state syncing
*/
stop: StopSyncStateFnType;
/**
* start state syncing
*/
start: StartSyncStateFnType;
}
/**
* Utility for syncing application state wrapped in state container
* with some kind of storage (e.g. URL)
*
* Go {@link https://github.com/elastic/kibana/tree/main/src/plugins/kibana_utils/docs/state_sync | here} for a complete guide and examples.
*
* @example
*
* the simplest use case
* ```ts
* const stateStorage = createKbnUrlStateStorage();
* syncState({
* storageKey: '_s',
* stateContainer,
* stateStorage
* });
* ```
*
* @example
* conditionally configuring sync strategy
* ```ts
* const stateStorage = createKbnUrlStateStorage({useHash: config.get('state:stateContainerInSessionStorage')})
* syncState({
* storageKey: '_s',
* stateContainer,
* stateStorage
* });
* ```
*
* @example
* implementing custom sync strategy
* ```ts
* const localStorageStateStorage = {
* set: (storageKey, state) => localStorage.setItem(storageKey, JSON.stringify(state)),
* get: (storageKey) => localStorage.getItem(storageKey) ? JSON.parse(localStorage.getItem(storageKey)) : null
* };
* syncState({
* storageKey: '_s',
* stateContainer,
* stateStorage: localStorageStateStorage
* });
* ```
*
* @example
* transforming state before serialising
* Useful for:
* * Migration / backward compatibility
* * Syncing part of state
* * Providing default values
* ```ts
* const stateToStorage = (s) => ({ tab: s.tab });
* syncState({
* storageKey: '_s',
* stateContainer: {
* get: () => stateToStorage(stateContainer.get()),
* set: stateContainer.set(({ tab }) => ({ ...stateContainer.get(), tab }),
* state$: stateContainer.state$.pipe(map(stateToStorage))
* },
* stateStorage
* });
* ```
*
* @param - syncing config {@link IStateSyncConfig}
* @returns - {@link ISyncStateRef}
* @public
*/
export function syncState<
State extends BaseState,
StateStorage extends IStateStorage = IStateStorage
>({
storageKey,
stateStorage,
stateContainer,
}: IStateSyncConfig<State, IStateStorage>): ISyncStateRef {
const subscriptions: Subscription[] = [];
const updateState = () => {
const newState = stateStorage.get<State>(storageKey);
const oldState = stateContainer.get();
if (newState) {
// apply only real differences to new state
const mergedState = { ...oldState } as State;
// merges into 'mergedState' all differences from newState,
// but leaves references if they are deeply the same
const diff = applyDiff(mergedState, newState);
if (diff.keys.length > 0) {
stateContainer.set(mergedState);
}
} else if (oldState !== newState) {
// empty new state case
stateContainer.set(newState);
}
};
const updateStorage = () => {
const newStorageState = stateContainer.get();
const oldStorageState = stateStorage.get<State>(storageKey);
if (!defaultComparator(newStorageState, oldStorageState)) {
stateStorage.set(storageKey, newStorageState);
}
};
const onStateChange$ = stateContainer.state$.pipe(
distinctUntilChangedWithInitialValue(stateContainer.get(), defaultComparator),
tap(() => updateStorage())
);
const onStorageChange$ = stateStorage.change$
? stateStorage.change$(storageKey).pipe(
distinctUntilChangedWithInitialValue(stateStorage.get(storageKey), defaultComparator),
tap(() => {
updateState();
})
)
: EMPTY;
return {
stop: () => {
// if stateStorage has any cancellation logic, then run it
if (stateStorage.cancel) {
stateStorage.cancel();
}
subscriptions.forEach((s) => s.unsubscribe());
subscriptions.splice(0, subscriptions.length);
},
start: () => {
if (subscriptions.length > 0) {
throw new Error("syncState: can't start syncing state, when syncing is in progress");
}
subscriptions.push(onStateChange$.subscribe(), onStorageChange$.subscribe());
},
};
}
/**
* @example
* sync multiple different sync configs
* ```ts
* syncStates([
* {
* storageKey: '_s1',
* stateStorage: stateStorage1,
* stateContainer: stateContainer1,
* },
* {
* storageKey: '_s2',
* stateStorage: stateStorage2,
* stateContainer: stateContainer2,
* },
* ]);
* ```
* @param stateSyncConfigs - Array of {@link IStateSyncConfig} to sync
*/
export function syncStates(stateSyncConfigs: Array<IStateSyncConfig<any>>): ISyncStateRef {
const syncRefs = stateSyncConfigs.map((config) => syncState(config));
return {
stop: () => {
syncRefs.forEach((s) => s.stop());
},
start: () => {
syncRefs.forEach((s) => s.start());
},
};
}