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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
|
/**
* StateManager - Centralized state management with Proxy-based reactivity
*
* Usage:
* state.time.speed = 2.0 // automatically emits events
* state.on('time.speed', (value) => console.log('Speed changed:', value))
* state.on('time.*', (change) => console.log('Time domain changed:', change))
*
* State Domains:
* - userPrefs: showGrid, showMetrics, theme, etc.
* - uiConfig: active panels, layout, dimensions
* - time: current time, speed, paused state, real elapsed time
* - rendering: graphs, renderer info
* - health: framerate, service connections, db access
* - dataInput: sources, structure, metadata
* - inputActions: keyboard/mouse/gamepad action mappings
*/
// Simple EventEmitter implementation
class EventEmitter {
constructor() {
this.events = new Map();
}
on(event, callback) {
if (!this.events.has(event)) {
this.events.set(event, []);
}
this.events.get(event).push(callback);
// Return unsubscribe function
return () => this.off(event, callback);
}
off(event, callback) {
if (!this.events.has(event)) return;
const callbacks = this.events.get(event);
const index = callbacks.indexOf(callback);
if (index > -1) {
callbacks.splice(index, 1);
}
}
emit(event, data) {
if (!this.events.has(event)) return;
this.events.get(event).forEach(callback => {
try {
callback(data);
} catch (e) {
console.error(`[State] Error in event handler for '${event}':`, e);
}
});
}
once(event, callback) {
const wrapper = (data) => {
callback(data);
this.off(event, wrapper);
};
this.on(event, wrapper);
}
clear() {
this.events.clear();
}
}
export class StateManager extends EventEmitter {
constructor() {
super();
// Internal state storage (not proxied)
this._state = {
userPrefs: {
showGrid: true,
showMetrics: true,
theme: 'dark',
rollingWindow: 60,
historyCapacity: 10000,
metricsUpdateInterval: 10,
},
uiConfig: {
activePanels: ['graph1', 'graph2'],
layout: 'horizontal-split',
canvasWidth: 0,
canvasHeight: 0,
},
time: {
current: 0, // Current plot time
realElapsed: 0, // Real time elapsed since start
speed: 1.0, // Time speed multiplier (0.1 to 5.0)
isPaused: false, // Pause state
startTimestamp: Date.now(), // Real timestamp when started
verticalScale: 1.0, // Vertical zoom for time history
},
rendering: {
rendererType: 'unknown', // 'webgpu' | 'webgl' | 'canvas'
frameCounter: 0,
// Note: graph instances are NOT stored here to avoid proxy wrapping
},
health: {
fps: 0,
updateMs: 0,
renderMs: 0,
vertexCount: 0,
lineCount: 0,
serviceConnections: {}, // e.g., { websocket: 'connected', mqtt: 'disconnected' }
},
dataInput: {
sources: [], // Array of data source configs
activeSource: null, // Currently active source
dataStructure: null, // Schema of incoming data
metadata: {}, // Additional metadata
},
inputActions: {
keyboardMap: new Map(), // Map of KeyboardEvent.code => action name
mouseMap: new Map(), // Map of mouse button => action name
actionHandlers: new Map(), // Map of action name => handler function
},
};
// Track which domains should be persisted
this._persistedDomains = new Set(['userPrefs']);
// Load persisted state
this._loadPersistedState();
// Create proxied state - this is what users interact with
this.state = this._createProxy(this._state, []);
}
/**
* Create a reactive Proxy that emits events on property changes
* @param {Object} target - The object to proxy
* @param {Array} path - Current property path (e.g., ['time', 'speed'])
* @private
*/
_createProxy(target, path) {
// Don't proxy non-objects or special objects like Map/Set
if (typeof target !== 'object' || target === null) {
return target;
}
// Don't proxy Maps and Sets - they need special handling
if (target instanceof Map || target instanceof Set) {
return target;
}
const self = this;
return new Proxy(target, {
get(obj, prop) {
const value = obj[prop];
// Return primitives and functions as-is
if (typeof value !== 'object' || value === null) {
return value;
}
// Return nested objects as proxies
return self._createProxy(value, [...path, prop]);
},
set(obj, prop, value) {
const oldValue = obj[prop];
// Only emit if value actually changed
if (oldValue === value) {
return true;
}
obj[prop] = value;
// Build event path
const fullPath = [...path, prop];
const pathString = fullPath.join('.');
const domain = fullPath[0];
// Emit specific property change: "time.speed"
self.emit(pathString, {
path: fullPath,
value: value,
oldValue: oldValue,
});
// Emit domain wildcard: "time.*"
if (domain) {
self.emit(`${domain}.*`, {
path: fullPath,
property: prop,
value: value,
oldValue: oldValue,
});
}
// Emit global wildcard: "*"
self.emit('*', {
path: fullPath,
value: value,
oldValue: oldValue,
});
// Auto-persist certain domains
if (self._persistedDomains.has(domain)) {
self._persistDomain(domain);
}
return true;
}
});
}
// =========================================================================
// Persistence
// =========================================================================
_persistDomain(domain) {
try {
const data = this._state[domain];
// Convert Maps to objects for JSON serialization
const serializable = this._makeSerializable(data);
localStorage.setItem(`timeplot-${domain}`, JSON.stringify(serializable));
} catch (e) {
console.warn(`[State] Failed to persist ${domain}:`, e);
}
}
_loadPersistedState() {
this._persistedDomains.forEach(domain => {
try {
const saved = localStorage.getItem(`timeplot-${domain}`);
if (saved) {
const data = JSON.parse(saved);
// Deep merge to preserve defaults for new properties
this._state[domain] = this._deepMerge(this._state[domain], data);
}
} catch (e) {
console.warn(`[State] Failed to load ${domain}:`, e);
}
});
}
_makeSerializable(obj) {
if (obj instanceof Map) {
return Object.fromEntries(obj);
}
if (obj instanceof Set) {
return Array.from(obj);
}
if (typeof obj === 'object' && obj !== null) {
const result = {};
for (const [key, value] of Object.entries(obj)) {
result[key] = this._makeSerializable(value);
}
return result;
}
return obj;
}
_deepMerge(target, source) {
const result = { ...target };
for (const key in source) {
if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key])) {
result[key] = this._deepMerge(target[key] || {}, source[key]);
} else {
result[key] = source[key];
}
}
return result;
}
// =========================================================================
// Convenience Methods
// =========================================================================
/**
* Toggle a boolean preference
*/
togglePref(key) {
const current = this.state.userPrefs[key];
if (typeof current === 'boolean') {
this.state.userPrefs[key] = !current;
}
}
/**
* Pause/resume time
*/
togglePause() {
this.state.time.isPaused = !this.state.time.isPaused;
}
/**
* Set time speed (clamped 0.1 to 5.0)
*/
setTimeSpeed(speed) {
this.state.time.speed = Math.max(0.1, Math.min(5.0, speed));
}
/**
* Increment time (respects pause and speed)
*/
incrementTime(delta) {
if (this.state.time.isPaused) return;
this.state.time.current += delta * this.state.time.speed;
}
/**
* Update real elapsed time
*/
updateRealElapsed() {
const elapsed = (Date.now() - this.state.time.startTimestamp) / 1000;
this.state.time.realElapsed = elapsed;
}
// =========================================================================
// Input Actions System
// =========================================================================
/**
* Register an input action handler
* @param {string} actionName - Name of the action (e.g., 'toggleGrid', 'pause')
* @param {Function} handler - Handler function to call
*/
registerAction(actionName, handler) {
this.state.inputActions.actionHandlers.set(actionName, handler);
}
/**
* Map a keyboard key to an action
* @param {string} code - KeyboardEvent.code (e.g., 'KeyG', 'Space')
* @param {string} actionName - Action to trigger
*/
mapKey(code, actionName) {
this.state.inputActions.keyboardMap.set(code, actionName);
}
/**
* Map a mouse button to an action
* @param {number} button - Mouse button number (0=left, 1=middle, 2=right)
* @param {string} actionName - Action to trigger
*/
mapMouseButton(button, actionName) {
this.state.inputActions.mouseMap.set(button, actionName);
}
/**
* Execute an action by name
*/
executeAction(actionName, event) {
const handler = this.state.inputActions.actionHandlers.get(actionName);
if (handler) {
handler(event);
} else {
console.warn(`[State] No handler registered for action: ${actionName}`);
}
}
/**
* Handle keyboard event through action system
*/
handleKeyboardEvent(event) {
const actionName = this.state.inputActions.keyboardMap.get(event.code);
if (actionName) {
this.executeAction(actionName, event);
return true;
}
return false;
}
/**
* Handle mouse button event through action system
*/
handleMouseButtonEvent(event) {
const actionName = this.state.inputActions.mouseMap.get(event.button);
if (actionName) {
this.executeAction(actionName, event);
return true;
}
return false;
}
// =========================================================================
// Data Sources
// =========================================================================
addDataSource(source) {
this.state.dataInput.sources.push(source);
}
removeDataSource(sourceId) {
const sources = this.state.dataInput.sources;
const index = sources.findIndex(s => s.id === sourceId);
if (index > -1) {
sources.splice(index, 1);
}
}
setActiveDataSource(sourceId) {
this.state.dataInput.activeSource = sourceId;
}
// =========================================================================
// Debugging
// =========================================================================
dump() {
console.log('[State] Current state:', JSON.parse(JSON.stringify(this._state)));
}
debugEvents() {
console.log('[State] Registered events:', Array.from(this.events.keys()));
}
}
|