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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
|
/**
* A callback passed to subscriptions, called when the event
* that the subscription is listening to is called.
*/
export type EventListener<
TState,
TPayload extends unknown = undefined,
> = (
state: TState,
payload?: TPayload,
) => void | Promise<void>;
type Subscription<
TState,
TPayload extends unknown = undefined,
> = {
callback: EventListener<TState, TPayload>;
once: boolean;
};
/**
* An instance of the ShapeX object.
*/
export type ShapeXInstance<TState> = {
/**
* Subscribe to an event.
*
* @param topic
* @param callback
*/
subscribe: <TPayload extends unknown = undefined>(
topic: string,
callback: EventListener<TState, TPayload>,
) => number;
/**
* Subscribe to an event once.
*
* @param topic
* @param callback
*/
subscribeOnce: <TPayload extends unknown = undefined>(
topic: string,
callback: EventListener<TState, TPayload>,
) => number;
/**
* Unsubscribe from an event.
*
* @param topic
*/
unsubscribe: (topic: string) => void;
/**
* Get the number of subscriptions for an event.
*/
subscriptionCount: (to: string) => number;
/**
* Get the subscriptions for an event.
*/
subscriptions: () => string[];
/**
* Dispatch an event.
*
* @param to
* @param payload
*/
dispatch: <TPayload extends unknown>(to: string, payload?: TPayload) => void;
/**
* Get the current state.
*/
state: () => TState;
/**
* Update state.
*
* @param updatedState
*/
setState: (updatedState: TState) => void;
};
/**
* A function that creates an EventX object.
*
* @param {TState extends object} initialState The initial application state.
* @returns {ShapeXInstance} The ShapeX object.
*/
export function ShapeX<TState extends object>(initialState: TState): ShapeXInstance<TState> {
let _state = initialState;
let _subscriptionId = 0;
const _subscriptions: Map<string, Array<Subscription<TState, unknown>>> = new Map();
/**
* Subscribe to an event.
*
* @param topic
* @param {EventListener} callback
* @returns
*/
const subscribe = <
TPayload extends unknown = undefined,
>(
topic: string,
callback: EventListener<TState, TPayload>,
): number => {
// there are no listeners, set as empty array
if (!_subscriptions.has(topic)) {
_subscriptions.set(topic, []);
}
// add a listener
_subscriptions.get(topic)?.push({
callback: callback as unknown as EventListener<TState, unknown>,
once: false,
});
return ++_subscriptionId;
};
/**
* Subscribe to an event, once.
*
* @param {string} topic
* @param {EventListener} callback
* @returns
*/
const subscribeOnce = <TPayload extends unknown = undefined>(
topic: string,
callback: EventListener<TState, TPayload>,
): number => {
// there are no listeners, set as empty array
if (!_subscriptions.has(topic)) {
_subscriptions.set(topic, []);
}
// add a listener
_subscriptions.get(topic)?.push({
callback: callback as unknown as EventListener<TState, unknown>,
once: true,
});
return ++_subscriptionId;
};
/**
* Removes all listeners for a topic.
*
* @param topic
*/
const unsubscribe = (topic: string): void => {
if (_subscriptions.has(topic)) {
_subscriptions.delete(topic);
}
};
/**
* Composes a list of changes between two states.
*
* @param {TState extends object} oldState
* @param {TState extends object} newState
* @returns {string[]} The list of changes as array of paths.
*/
const changedState = <TState extends object>(
oldState: TState,
newState: TState,
): string[] => {
const paths = <R extends object>(
state: R,
path: string,
): { path: string; value: unknown }[] => {
const _paths = [] as { path: string; value: unknown }[];
for (const key in state) {
const currentPath = `${path}.${key}`;
_paths.push({
path: currentPath,
value: state[key],
});
if (typeof state[key] === "object" && state[key] !== null) {
_paths.push(...paths(state[key], currentPath));
}
}
return _paths;
};
const differ = <S extends object>(oldState: S, newState: S): string[] => {
const oldPaths = paths(oldState, "$");
const oldPathKeys = oldPaths.map((x) => x.path);
const newPaths = paths(newState, "$");
const newPathKeys = newPaths.map((x) => x.path);
// all new paths
const added = newPathKeys.filter((path) => !oldPathKeys.includes(path));
// all removed paths
const removed = oldPathKeys.filter((path) => !newPathKeys.includes(path));
// paths that remained
const same = oldPathKeys.filter((path) => newPathKeys.includes(path));
// paths that changed
const changed = same.filter((path) => {
const oldValue = oldPaths.find((x) => x.path === path)?.value;
const newValue = newPaths.find((x) => x.path === path)?.value;
return oldValue !== newValue;
});
return [...new Set([...added, ...removed, ...changed])];
};
return differ(oldState, newState);
};
/**
* Dispatches an event with the given name and arguments.
*
* @param {string} to The name of the event to dispatch.
* @param payload
* @returns {void}
*/
const dispatch = <TPayload extends unknown = undefined>(
to: string,
payload?: TPayload,
): void => {
if (!_subscriptions.has(to)) return;
const scopedSubscriptions = _subscriptions.get(to) ?? [];
const remainingSubscriptions = [] as Array<Subscription<TState, unknown>>;
for (const subscription of scopedSubscriptions) {
const callback = subscription.callback as unknown as EventListener<TState, TPayload>;
if (payload) {
callback(_state, payload);
} else {
callback(_state);
}
if (!subscription.once) {
remainingSubscriptions.push(subscription);
}
}
_subscriptions.set(to, remainingSubscriptions);
};
/**
* Returns the number of subscriptions for the given event name.
*
* @param {string} eventName The name of the event to check.
* @returns {number} The number of subscriptions for the given event name.
*/
const subscriptionCount = (eventName: string | null): number => {
if (eventName) {
return _subscriptions.get(eventName)?.length ?? 0;
}
return Array.from(_subscriptions.keys()).length;
};
/**
* Returns the names of all subscriptions.
*
* @returns {string[]} An array of subscription names.
*/
const subscriptions = (): string[] => {
return Array.from(_subscriptions.keys());
};
/**
* Returns the current state.
*
* @returns {} The current state.
*/
const state = (): TState => {
return _state;
};
/**
* Updates state.
*
* @param updatedState updated state
*/
const setState = (updatedState: TState): void => {
const changes = changedState(_state, updatedState);
_state = updatedState;
for (let i = 0; i < changes.length; i++) {
dispatch(changes[i]);
}
}
return {
subscribe,
subscribeOnce,
unsubscribe,
subscriptionCount,
subscriptions,
dispatch,
state,
setState,
};
}
|