-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystem.ts
More file actions
269 lines (244 loc) Β· 6.63 KB
/
system.ts
File metadata and controls
269 lines (244 loc) Β· 6.63 KB
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
/**
* System Configuration - Event Bus Communication
*
* This example shows how resources communicate through an event bus,
* demonstrating loose coupling and coordination outside of React.
*/
import { defineResource, StartedResource } from "braided";
import { createSystemHooks, createSystemManager } from "braided-react";
/**
* Event Bus Resource
*
* Central event emitter that allows resources to communicate.
* Resources can emit events and subscribe to events from other resources.
*/
export const eventBusResource = defineResource({
start: () => {
console.log("π‘ Event bus starting...");
type EventHandler = (...args: any[]) => void;
const listeners = new Map<string, Set<EventHandler>>();
return {
emit(event: string, ...args: any[]) {
console.log(`π‘ Event emitted: ${event}`, args);
const handlers = listeners.get(event);
if (handlers) {
handlers.forEach((handler) => handler(...args));
}
},
on(event: string, handler: EventHandler) {
if (!listeners.has(event)) {
listeners.set(event, new Set());
}
listeners.get(event)!.add(handler);
console.log(`π‘ Listener added for: ${event}`);
return () => {
listeners.get(event)?.delete(handler);
console.log(`π‘ Listener removed for: ${event}`);
};
},
getListenerCount(event: string) {
return listeners.get(event)?.size || 0;
},
cleanup() {
listeners.clear();
},
};
},
halt: (bus) => {
console.log("π‘ Event bus halting");
bus.cleanup();
},
});
/**
* Timer Resource
*
* Emits tick events every second.
* Demonstrates a resource that produces events.
*/
export const timerResource = defineResource({
dependencies: ["eventBus"],
start: ({
eventBus,
}: {
eventBus: StartedResource<typeof eventBusResource>;
}) => {
console.log("β° Timer starting...");
let ticks = 0;
let running = false;
let intervalId: number | null = null;
return {
start() {
if (running) return;
running = true;
intervalId = window.setInterval(() => {
ticks++;
eventBus.emit("timer:tick", ticks);
}, 1000);
eventBus.emit("timer:started");
console.log("β° Timer started");
},
stop() {
if (!running) return;
running = false;
if (intervalId !== null) {
clearInterval(intervalId);
intervalId = null;
eventBus.emit("timer:stopped");
}
console.log("β° Timer stopped");
},
reset() {
ticks = 0;
eventBus.emit("timer:reset");
console.log("β° Timer reset");
},
getTicks: () => ticks,
isRunning: () => running,
};
},
halt: (timer) => {
timer.stop();
console.log("β° Timer halting");
},
});
/**
* Counter Resource
*
* Listens to timer ticks and increments a counter.
* Demonstrates a resource that consumes events.
*/
export const counterResource = defineResource({
dependencies: ["eventBus"],
start: ({
eventBus,
}: {
eventBus: StartedResource<typeof eventBusResource>;
}) => {
console.log("π’ Counter starting...");
let count = 0;
const listeners = new Set<() => void>();
const notify = () => {
listeners.forEach((listener) => listener());
};
// Listen to timer ticks
const unsubTick = eventBus.on("timer:tick", (ticks: number) => {
count++;
notify();
console.log(`π’ Counter incremented on tick ${ticks}: ${count}`);
});
// Listen to timer reset
const unsubReset = eventBus.on("timer:reset", () => {
count = 0;
notify();
console.log("π’ Counter reset");
});
return {
subscribe(listener: () => void) {
listeners.add(listener);
return () => listeners.delete(listener);
},
getSnapshot: () => count,
getCount: () => count,
increment() {
count++;
notify();
eventBus.emit("counter:changed", count);
},
reset() {
count = 0;
notify();
eventBus.emit("counter:changed", count);
},
cleanup: () => {
unsubTick();
unsubReset();
},
};
},
halt: (counter) => {
counter.cleanup();
console.log(`π’ Counter halting (final count: ${counter.getCount()})`);
},
});
/**
* Logger Resource
*
* Listens to all events and logs them.
* Demonstrates a resource that observes the entire system.
*/
export const loggerResource = defineResource({
dependencies: ["eventBus"],
start: ({
eventBus,
}: {
eventBus: StartedResource<typeof eventBusResource>;
}) => {
console.log("π Logger starting...");
let logs: string[] = [];
const listeners = new Set<() => void>();
const notify = () => {
listeners.forEach((listener) => listener());
};
const addLog = (message: string) => {
const timestamp = new Date().toLocaleTimeString();
const entry = `[${timestamp}] ${message}`;
logs = [...logs, entry];
notify();
};
// Listen to all events
const unsubTick = eventBus.on("timer:tick", (ticks: number) => {
addLog(`Timer tick: ${ticks}`);
});
const unsubReset = eventBus.on("timer:reset", () => {
addLog("Timer reset");
});
const unsubCounter = eventBus.on("counter:changed", (count: number) => {
addLog(`Counter changed: ${count}`);
});
const unsubStopped = eventBus.on("timer:stopped", () => {
addLog("Timer stopped");
});
const unsubStarted = eventBus.on("timer:started", () => {
addLog("Timer started");
});
return {
subscribe(listener: () => void) {
listeners.add(listener);
return () => listeners.delete(listener);
},
getSnapshot: () => logs,
getLogs: () => [...logs],
clear() {
logs = [];
notify();
console.log("π Logs cleared");
},
cleanup: () => {
unsubTick();
unsubReset();
unsubCounter();
unsubStopped();
unsubStarted();
},
};
},
halt: (logger) => {
logger.cleanup();
console.log(`π Logger halting (${logger.getLogs().length} logs recorded)`);
},
});
/**
* System Configuration
*
* All resources communicate through the event bus.
* No resource directly depends on another (except eventBus).
*/
export const systemConfig = {
eventBus: eventBusResource,
timer: timerResource,
counter: counterResource,
logger: loggerResource,
};
export const manager = createSystemManager(systemConfig);
export const { useSystem, useResource, SystemProvider } =
createSystemHooks(manager);