-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
store.ts
289 lines (271 loc) · 8.75 KB
/
store.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
287
288
289
/**
* Internal dependencies
*/
import { proxifyState, proxifyStore, deepMerge } from './proxies';
/**
* External dependencies
*/
import { getNamespace } from './namespaces';
import { isPlainObject } from './utils';
export const stores = new Map();
const rawStores = new Map();
const storeLocks = new Map();
const storeConfigs = new Map();
const serverStates = new Map();
/**
* Get the defined config for the store with the passed namespace.
*
* @param namespace Store's namespace from which to retrieve the config.
* @return Defined config for the given namespace.
*/
export const getConfig = ( namespace?: string ) =>
storeConfigs.get( namespace || getNamespace() ) || {};
/**
* Get the part of the state defined and updated from the server.
*
* The object returned is read-only, and includes the state defined in PHP with
* `wp_interactivity_state()`. When using `actions.navigate()`, this object is
* updated to reflect the changes in its properites, without affecting the state
* returned by `store()`. Directives can subscribe to those changes to update
* the state if needed.
*
* @example
* ```js
* const { state } = store('myStore', {
* callbacks: {
* updateServerState() {
* const serverState = getServerState();
* // Override some property with the new value that came from the server.
* state.overridableProp = serverState.overridableProp;
* },
* },
* });
* ```
*
* @param namespace Store's namespace from which to retrieve the server state.
* @return The server state for the given namespace.
*/
export const getServerState = ( namespace?: string ) => {
const ns = namespace || getNamespace();
if ( ! serverStates.has( ns ) ) {
serverStates.set( ns, proxifyState( ns, {}, { readOnly: true } ) );
}
return serverStates.get( ns );
};
interface StoreOptions {
/**
* Property to block/unblock private store namespaces.
*
* If the passed value is `true`, it blocks the given namespace, making it
* accessible only trough the returned variables of the `store()` call. In
* the case a lock string is passed, it also blocks the namespace, but can
* be unblocked for other `store()` calls using the same lock string.
*
* @example
* ```
* // The store can only be accessed where the `state` const can.
* const { state } = store( 'myblock/private', { ... }, { lock: true } );
* ```
*
* @example
* ```
* // Other modules knowing `SECRET_LOCK_STRING` can access the namespace.
* const { state } = store(
* 'myblock/private',
* { ... },
* { lock: 'SECRET_LOCK_STRING' }
* );
* ```
*/
lock?: boolean | string;
}
type Prettify< T > = { [ K in keyof T ]: T[ K ] } & {};
type DeepPartial< T > = T extends object
? { [ P in keyof T ]?: DeepPartial< T[ P ] > }
: T;
type DeepPartialState< T extends { state: object } > = Omit< T, 'state' > & {
state?: DeepPartial< T[ 'state' ] >;
};
type ConvertGeneratorToPromise< T > = T extends (
...args: infer A
) => Generator< any, infer R, any >
? ( ...args: A ) => Promise< R >
: never;
type ConvertGeneratorsToPromises< T > = {
[ K in keyof T ]: T[ K ] extends ( ...args: any[] ) => any
? ConvertGeneratorToPromise< T[ K ] > extends never
? T[ K ]
: ConvertGeneratorToPromise< T[ K ] >
: T[ K ] extends object
? Prettify< ConvertGeneratorsToPromises< T[ K ] > >
: T[ K ];
};
type ConvertPromiseToGenerator< T > = T extends (
...args: infer A
) => Promise< infer R >
? ( ...args: A ) => Generator< any, R, any >
: never;
type ConvertPromisesToGenerators< T > = {
[ K in keyof T ]: T[ K ] extends ( ...args: any[] ) => any
? ConvertPromiseToGenerator< T[ K ] > extends never
? T[ K ]
: ConvertPromiseToGenerator< T[ K ] >
: T[ K ] extends object
? Prettify< ConvertPromisesToGenerators< T[ K ] > >
: T[ K ];
};
export const universalUnlock =
'I acknowledge that using a private store means my plugin will inevitably break on the next store release.';
/**
* Extends the Interactivity API global store adding the passed properties to
* the given namespace. It also returns stable references to the namespace
* content.
*
* These props typically consist of `state`, which is the reactive part of the
* store ― which means that any directive referencing a state property will be
* re-rendered anytime it changes ― and function properties like `actions` and
* `callbacks`, mostly used for event handlers. These props can then be
* referenced by any directive to make the HTML interactive.
*
* @example
* ```js
* const { state } = store( 'counter', {
* state: {
* value: 0,
* get double() { return state.value * 2; },
* },
* actions: {
* increment() {
* state.value += 1;
* },
* },
* } );
* ```
*
* The code from the example above allows blocks to subscribe and interact with
* the store by using directives in the HTML, e.g.:
*
* ```html
* <div data-wp-interactive="counter">
* <button
* data-wp-text="state.double"
* data-wp-on--click="actions.increment"
* >
* 0
* </button>
* </div>
* ```
* @param namespace The store namespace to interact with.
* @param storePart Properties to add to the store namespace.
* @param options Options for the given namespace.
*
* @return A reference to the namespace content.
*/
// Overload for when the types are inferred.
export function store< T extends object >(
namespace: string,
storePart: T,
options?: StoreOptions
): Prettify< ConvertGeneratorsToPromises< T > >;
// Overload for when types are passed via generics and they contain state.
export function store< T extends { state: object } >(
namespace: string,
storePart: ConvertPromisesToGenerators< DeepPartialState< T > >,
options?: StoreOptions
): Prettify< ConvertGeneratorsToPromises< T > >;
// Overload for when types are passed via generics and they don't contain state.
export function store< T extends object >(
namespace: string,
storePart: ConvertPromisesToGenerators< T >,
options?: StoreOptions
): Prettify< ConvertGeneratorsToPromises< T > >;
// Overload for when types are divided into multiple parts.
export function store< T extends object >(
namespace: string,
storePart: ConvertPromisesToGenerators< DeepPartial< T > >,
options?: StoreOptions
): Prettify< ConvertGeneratorsToPromises< T > >;
export function store(
namespace: string,
{ state = {}, ...block }: any = {},
{ lock = false }: StoreOptions = {}
) {
if ( ! stores.has( namespace ) ) {
// Lock the store if the passed lock is different from the universal
// unlock. Once the lock is set (either false, true, or a given string),
// it cannot change.
if ( lock !== universalUnlock ) {
storeLocks.set( namespace, lock );
}
const rawStore = {
state: proxifyState(
namespace,
isPlainObject( state ) ? state : {}
),
...block,
};
const proxifiedStore = proxifyStore( namespace, rawStore );
rawStores.set( namespace, rawStore );
stores.set( namespace, proxifiedStore );
} else {
// Lock the store if it wasn't locked yet and the passed lock is
// different from the universal unlock. If no lock is given, the store
// will be public and won't accept any lock from now on.
if ( lock !== universalUnlock && ! storeLocks.has( namespace ) ) {
storeLocks.set( namespace, lock );
} else {
const storeLock = storeLocks.get( namespace );
const isLockValid =
lock === universalUnlock ||
( lock !== true && lock === storeLock );
if ( ! isLockValid ) {
if ( ! storeLock ) {
throw Error( 'Cannot lock a public store' );
} else {
throw Error(
'Cannot unlock a private store with an invalid lock code'
);
}
}
}
const target = rawStores.get( namespace );
deepMerge( target, block );
deepMerge( target.state, state );
}
return stores.get( namespace );
}
export const parseServerData = ( dom = document ) => {
const jsonDataScriptTag =
// Preferred Script Module data passing form
dom.getElementById(
'wp-script-module-data-@wordpress/interactivity'
) ??
// Legacy form
dom.getElementById( 'wp-interactivity-data' );
if ( jsonDataScriptTag?.textContent ) {
try {
return JSON.parse( jsonDataScriptTag.textContent );
} catch {}
}
return {};
};
export const populateServerData = ( data?: {
state?: Record< string, unknown >;
config?: Record< string, unknown >;
} ) => {
if ( isPlainObject( data?.state ) ) {
Object.entries( data!.state ).forEach( ( [ namespace, state ] ) => {
const st = store< any >( namespace, {}, { lock: universalUnlock } );
deepMerge( st.state, state, false );
deepMerge( getServerState( namespace ), state );
} );
}
if ( isPlainObject( data?.config ) ) {
Object.entries( data!.config ).forEach( ( [ namespace, config ] ) => {
storeConfigs.set( namespace, config );
} );
}
};
// Parse and populate the initial state and config.
const data = parseServerData();
populateServerData( data );