-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate-manager.js
More file actions
651 lines (539 loc) · 21 KB
/
Copy pathstate-manager.js
File metadata and controls
651 lines (539 loc) · 21 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
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
// core/state-manager.js - VERSIONE OTTIMIZZATA (v3.1.0)
console.log("Teams Caption Extractor - State Manager OPTIMIZED Loading...");
(function() {
// Stato centralizzato dell'applicazione
const initialState = {
isActive: false,
isMinimized: false,
isExpanded: false,
captions: [],
lastSpeaker: null,
captionNodesBeingTracked: new Map(),
panelWidth: 280,
minimizedWidth: 48,
expandedWidth: 380,
panelMode: 'dock',
dockMode: false,
dockRatio: 0.3,
screenshots: [],
personalNotes: [],
customerInfo: '',
projectInfo: '',
customMeetingTitle: '',
fileFormat: 'html',
screenshotSectionCollapsed: false,
includeChatMessages: true,
};
// Crea una copia iniziale dello stato
TeamsCaption.state = JSON.parse(JSON.stringify(initialState));
TeamsCaption.state.captionNodesBeingTracked = new Map(); // Ripristina Map che non può essere JSON.stringified
// TRACCIAMENTO OTTIMIZZATO DEGLI AGGIORNAMENTI
let stateUpdateInProgress = false;
let pendingStateUpdates = {};
let updateTimeout = null;
// FUNZIONI PRIVATE PER GESTIONE STATO
/**
* Valida un aggiornamento di stato
*/
function validateStateUpdate(partialState) {
const validKeys = Object.keys(initialState);
const invalidKeys = Object.keys(partialState).filter(key => !validKeys.includes(key));
if (invalidKeys.length > 0) {
console.warn('⚠️ Invalid state keys detected:', invalidKeys);
// Rimuove chiavi non valide
invalidKeys.forEach(key => delete partialState[key]);
}
return partialState;
}
/**
* Metodo sicuro per aggiornare lo stato - VERSIONE OTTIMIZZATA
*/
function updateState(partialState) {
try {
// Valida l'aggiornamento
const validatedState = validateStateUpdate(partialState);
if (Object.keys(validatedState).length === 0) {
console.warn('⚠️ No valid state updates to apply');
return;
}
// BATCH UPDATES: Accumula aggiornamenti per evitare troppi re-render
Object.assign(pendingStateUpdates, validatedState);
// Cancella timeout precedente se esiste
if (updateTimeout) {
clearTimeout(updateTimeout);
}
// Imposta nuovo timeout per applicare aggiornamenti in batch
updateTimeout = setTimeout(() => {
if (stateUpdateInProgress) {
console.log('⏸️ State update already in progress, deferring');
return;
}
stateUpdateInProgress = true;
// Applica tutti gli aggiornamenti pendenti
const updatesToApply = { ...pendingStateUpdates };
pendingStateUpdates = {};
// Aggiorna solo le proprietà fornite
Object.assign(TeamsCaption.state, updatesToApply);
// Notifica del cambiamento di stato SOLO se necessario
const hasSignificantChanges = Object.keys(updatesToApply).some(key =>
['captions', 'personalNotes', 'screenshots', 'isActive', 'isMinimized'].includes(key)
);
if (hasSignificantChanges) {
TeamsCaption.EventBus.publish('STATE_CHANGED', TeamsCaption.state);
}
console.log('🔄 State updated (batched):', Object.keys(updatesToApply));
stateUpdateInProgress = false;
updateTimeout = null;
}, 100); // 100ms di debounce
} catch (error) {
console.error('❌ Error updating state:', error);
stateUpdateInProgress = false;
}
}
/**
* Reset sicuro dello stato
*/
function resetState() {
try {
const newState = JSON.parse(JSON.stringify(initialState));
newState.captionNodesBeingTracked = new Map();
// Resetta anche i pending updates
pendingStateUpdates = {};
if (updateTimeout) {
clearTimeout(updateTimeout);
updateTimeout = null;
}
Object.assign(TeamsCaption.state, newState);
TeamsCaption.EventBus.publish('STATE_CHANGED', TeamsCaption.state);
console.log('🔄 State reset to initial values');
} catch (error) {
console.error('❌ Error resetting state:', error);
}
}
// FUNZIONI PUBBLICHE API
/**
* Aggiunge una didascalia con controllo duplicati OTTIMIZZATO
*/
function addCaption(caption) {
try {
if (!caption || !caption.text || !caption.speaker) {
console.warn('⚠️ Invalid caption data provided');
return null;
}
// Controllo duplicati ottimizzato
const existingCaptions = TeamsCaption.state.captions;
const isDuplicate = existingCaptions.some(c =>
c.speaker === caption.speaker &&
c.text === caption.text &&
Math.abs(new Date(c.timestamp) - new Date(caption.timestamp)) < 5000 // 5 secondi di tolleranza
);
if (isDuplicate) {
console.log('⚪ Duplicate caption detected, skipping');
return null;
}
// Genera ID se mancante
if (!caption.id) {
caption.id = `caption-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
}
// Assicura che abbia i campi necessari
const fullCaption = {
id: caption.id,
speaker: caption.speaker,
text: caption.text,
timestamp: caption.timestamp || new Date().toISOString(),
isHighlight: caption.isHighlight || false,
isTodo: caption.isTodo || false,
isChat: caption.isChat || false
};
// AGGIORNAMENTO CON UI REFRESH
const captions = [...TeamsCaption.state.captions, fullCaption];
// PERFORMANCE FIX: Limit UI captions array to prevent memory bloat
// Full backup is handled by session-backup.js (saves to chrome.storage every 2 min + after each caption)
const MAX_CAPTIONS = 300;
if (captions.length > MAX_CAPTIONS) {
const removed = captions.length - MAX_CAPTIONS;
TeamsCaption.state.captions = captions.slice(-MAX_CAPTIONS);
console.log(`[Performance] Trimmed ${removed} old UI captions, keeping ${MAX_CAPTIONS}`);
} else {
TeamsCaption.state.captions = captions;
}
TeamsCaption.state.lastSpeaker = fullCaption.speaker;
// Triggera aggiornamento UI immediato per le caption
TeamsCaption.EventBus.publish('NEW_CAPTION_ADDED', fullCaption);
// CRITICAL FIX: Triggera anche STATE_CHANGED per aggiornare il pannello
setTimeout(() => {
TeamsCaption.EventBus.publish('STATE_CHANGED', TeamsCaption.state);
}, 50);
console.log(`➕ Caption added: ${fullCaption.speaker} - ${fullCaption.text.substring(0, 30)}...`);
return fullCaption;
} catch (error) {
console.error('❌ Error adding caption:', error);
return null;
}
}
/**
* Aggiorna una didascalia esistente - OTTIMIZZATO
*/
function updateCaption(captionId, updates) {
try {
const captionIndex = TeamsCaption.state.captions.findIndex(c => c.id === captionId);
if (captionIndex === -1) {
console.warn(`⚠️ Caption with ID ${captionId} not found`);
return false;
}
// Aggiorna in-place per performance
Object.assign(TeamsCaption.state.captions[captionIndex], updates);
// Notifica specifica per aggiornamento caption
TeamsCaption.EventBus.publish('CAPTION_UPDATED', {
id: captionId,
updates,
caption: TeamsCaption.state.captions[captionIndex]
});
console.log(`🔄 Caption updated: ${captionId}`);
return true;
} catch (error) {
console.error('❌ Error updating caption:', error);
return false;
}
}
/**
* Toggle highlight OTTIMIZZATO - AGGIORNAMENTO IMMEDIATO
*/
function toggleHighlight(captionId) {
try {
const caption = TeamsCaption.state.captions.find(c => c.id === captionId);
if (!caption) {
console.error(`❌ Caption with ID ${captionId} not found for highlight toggle`);
return null;
}
// Aggiorna immediatamente lo stato
const newState = !caption.isHighlight;
caption.isHighlight = newState;
console.log(`⭐ Highlight toggled for ${captionId}: ${!newState} -> ${newState}`);
// Non triggerare state change completo - l'UI si aggiorna da sola
return caption;
} catch (error) {
console.error('❌ Error toggling highlight:', error);
return null;
}
}
/**
* Toggle todo OTTIMIZZATO - AGGIORNAMENTO IMMEDIATO
*/
function toggleTodo(captionId) {
try {
const caption = TeamsCaption.state.captions.find(c => c.id === captionId);
if (!caption) {
console.error(`❌ Caption with ID ${captionId} not found for todo toggle`);
return null;
}
// Aggiorna immediatamente lo stato
const newState = !caption.isTodo;
caption.isTodo = newState;
console.log(`✅ Todo toggled for ${captionId}: ${!newState} -> ${newState}`);
// Non triggerare state change completo - l'UI si aggiorna da sola
return caption;
} catch (error) {
console.error('❌ Error toggling todo:', error);
return null;
}
}
/**
* Aggiunge uno screenshot
*/
function addScreenshot(screenshot) {
try {
if (!screenshot || !screenshot.dataUrl) {
console.warn('⚠️ Invalid screenshot data provided');
return false;
}
const fullScreenshot = {
id: `screenshot-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
dataUrl: screenshot.dataUrl,
timestamp: screenshot.timestamp || new Date().toISOString(),
context: screenshot.context || ''
};
const screenshots = [...TeamsCaption.state.screenshots, fullScreenshot];
updateState({ screenshots });
console.log('📷 Screenshot added');
return true;
} catch (error) {
console.error('❌ Error adding screenshot:', error);
return false;
}
}
/**
* Aggiunge una nota personale - OTTIMIZZATO
*/
function addNote(note) {
try {
if (!note || !note.text) {
console.warn('⚠️ Invalid note data provided');
return false;
}
const fullNote = {
id: note.id || `note-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
text: note.text,
timestamp: note.timestamp || new Date().toISOString(),
referencedCaption: note.referencedCaption || null
};
// Aggiorna direttamente senza triggering state change generale
if (!TeamsCaption.state.personalNotes) {
TeamsCaption.state.personalNotes = [];
}
TeamsCaption.state.personalNotes.push(fullNote);
console.log('📝 Note added');
return true;
} catch (error) {
console.error('❌ Error adding note:', error);
return false;
}
}
/**
* Elimina una nota personale - OTTIMIZZATO
*/
function deleteNote(noteId) {
try {
if (!TeamsCaption.state.personalNotes) {
return false;
}
const initialLength = TeamsCaption.state.personalNotes.length;
TeamsCaption.state.personalNotes = TeamsCaption.state.personalNotes.filter(n => n.id !== noteId);
const wasDeleted = TeamsCaption.state.personalNotes.length < initialLength;
if (wasDeleted) {
console.log(`📝 Note deleted: ${noteId}`);
}
return wasDeleted;
} catch (error) {
console.error('❌ Error deleting note:', error);
return false;
}
}
/**
* Pulisce le didascalie - OTTIMIZZATO
*/
function clearCaptions() {
try {
TeamsCaption.state.captions = [];
TeamsCaption.state.lastSpeaker = null;
TeamsCaption.state.captionNodesBeingTracked = new Map();
// Notifica specifica per clear
TeamsCaption.EventBus.publish('CAPTIONS_CLEARED');
console.log('🗑️ Captions cleared');
return true;
} catch (error) {
console.error('❌ Error clearing captions:', error);
return false;
}
}
// API per lo state manager
const StateManager = {
// Getters
getState() {
return JSON.parse(JSON.stringify(TeamsCaption.state));
},
getCaption(captionId) {
return TeamsCaption.state.captions.find(c => c.id === captionId) || null;
},
getCaptions() {
return [...TeamsCaption.state.captions];
},
getHighlights() {
return TeamsCaption.state.captions.filter(c => c.isHighlight);
},
getTodos() {
return TeamsCaption.state.captions.filter(c => c.isTodo);
},
// State management
updateState,
resetState,
// Caption management
addCaption,
updateCaption,
toggleHighlight,
toggleTodo,
clearCaptions,
// Other content
addScreenshot,
addNote,
deleteNote,
// UI state
setCustomerInfo(customer) {
const nextValue = customer || '';
if (TeamsCaption.state.customerInfo === nextValue) return;
TeamsCaption.state.customerInfo = nextValue;
TeamsCaption.EventBus.publish('CUSTOMER_PROJECT_UPDATED', {
customer: TeamsCaption.state.customerInfo,
project: TeamsCaption.state.projectInfo || ''
});
},
setProjectInfo(project) {
const nextValue = project || '';
if (TeamsCaption.state.projectInfo === nextValue) return;
TeamsCaption.state.projectInfo = nextValue;
TeamsCaption.EventBus.publish('CUSTOMER_PROJECT_UPDATED', {
customer: TeamsCaption.state.customerInfo || '',
project: TeamsCaption.state.projectInfo
});
},
setMeetingTitle(title) {
TeamsCaption.state.customMeetingTitle = title || '';
},
setFileFormat(format) {
if (['html', 'txt'].includes(format)) {
TeamsCaption.state.fileFormat = format;
}
},
toggleMinimized() {
const newState = !TeamsCaption.state.isMinimized;
TeamsCaption.state.isMinimized = newState;
TeamsCaption.state.isExpanded = false; // Reset expanded quando si minimizza
// Questo richiede un re-render del pannello
TeamsCaption.EventBus.publish('STATE_CHANGED', TeamsCaption.state);
},
toggleExpanded() {
if (!TeamsCaption.state.isMinimized) {
const newState = !TeamsCaption.state.isExpanded;
TeamsCaption.state.isExpanded = newState;
// Questo richiede un re-render del pannello
TeamsCaption.EventBus.publish('STATE_CHANGED', TeamsCaption.state);
}
},
// Statistiche
getStats() {
return {
captions: TeamsCaption.state.captions.length,
highlights: TeamsCaption.state.captions.filter(c => c.isHighlight).length,
todos: TeamsCaption.state.captions.filter(c => c.isTodo).length,
notes: TeamsCaption.state.personalNotes?.length || 0,
screenshots: TeamsCaption.state.screenshots?.length || 0,
chatMessages: TeamsCaption.state.captions.filter(c => c.isChat).length
};
}
};
// Esponi l'API pubblicamente
TeamsCaption.StateManager = StateManager;
// GESTIONE EVENTI OTTIMIZZATA
let eventListenersSetup = false;
function setupEventListeners() {
if (eventListenersSetup) return;
eventListenersSetup = true;
console.log("🎯 Setting up State Manager event listeners");
// Eventi di attivazione
TeamsCaption.EventBus.subscribe('ACTIVATE', () => {
TeamsCaption.state.isActive = true;
});
TeamsCaption.EventBus.subscribe('DEACTIVATE', () => {
TeamsCaption.state.isActive = false;
});
// Eventi UI
TeamsCaption.EventBus.subscribe('TOGGLE_MINIMIZE', () => {
StateManager.toggleMinimized();
});
TeamsCaption.EventBus.subscribe('TOGGLE_EXPANDED', () => {
StateManager.toggleExpanded();
});
// Eventi contenuto - OTTIMIZZATI per non causare refresh completi
TeamsCaption.EventBus.subscribe('CAPTION_DETECTED', (caption) => {
StateManager.addCaption(caption);
});
TeamsCaption.EventBus.subscribe('TOGGLE_HIGHLIGHT', (captionId) => {
StateManager.toggleHighlight(captionId);
});
TeamsCaption.EventBus.subscribe('TOGGLE_TODO', (captionId) => {
StateManager.toggleTodo(captionId);
});
TeamsCaption.EventBus.subscribe('SCREENSHOT_TAKEN', (screenshot) => {
StateManager.addScreenshot(screenshot);
});
TeamsCaption.EventBus.subscribe('NOTE_ADDED', (note) => {
if (TeamsCaption.NotesModule) return;
StateManager.addNote(note);
});
TeamsCaption.EventBus.subscribe('NOTE_DELETED', (noteId) => {
if (TeamsCaption.NotesModule) return;
StateManager.deleteNote(noteId);
});
TeamsCaption.EventBus.subscribe('CLEAR_CAPTIONS', () => {
StateManager.clearCaptions();
});
// Eventi configurazione
TeamsCaption.EventBus.subscribe('UPDATE_CUSTOMER_PROJECT', (data) => {
if (data.customer !== undefined) StateManager.setCustomerInfo(data.customer);
if (data.project !== undefined) StateManager.setProjectInfo(data.project);
});
TeamsCaption.EventBus.subscribe('UPDATE_MEETING_TITLE', (title) => {
StateManager.setMeetingTitle(title);
});
TeamsCaption.EventBus.subscribe('UPDATE_SETTINGS', (settings) => {
if (settings.fileFormat) {
StateManager.setFileFormat(settings.fileFormat);
}
if (settings.panelMode && ['dock', 'fullscreen'].includes(settings.panelMode)) {
TeamsCaption.state.panelMode = settings.panelMode;
}
if (typeof settings.dockMode === 'boolean') {
TeamsCaption.state.dockMode = settings.dockMode;
}
if (typeof settings.dockRatio === 'number' && Number.isFinite(settings.dockRatio)) {
const clamped = Math.min(0.5, Math.max(0.2, settings.dockRatio));
TeamsCaption.state.dockRatio = clamped;
}
if (settings.panelMode !== undefined || settings.dockMode !== undefined || settings.dockRatio !== undefined) {
TeamsCaption.EventBus.publish('STATE_CHANGED', TeamsCaption.state);
}
});
TeamsCaption.EventBus.subscribe('SET_PANEL_MODE', (mode) => {
if (!mode || !['dock', 'fullscreen'].includes(mode)) return;
TeamsCaption.state.panelMode = mode;
TeamsCaption.EventBus.publish('STATE_CHANGED', TeamsCaption.state);
});
TeamsCaption.EventBus.subscribe('TOGGLE_PANEL_MODE', () => {
const next = TeamsCaption.state.panelMode === 'fullscreen' ? 'dock' : 'fullscreen';
TeamsCaption.state.panelMode = next;
TeamsCaption.EventBus.publish('STATE_CHANGED', TeamsCaption.state);
});
}
// Debug API per console
window.StateDebug = {
state: () => TeamsCaption.state,
stats: () => StateManager.getStats(),
highlights: () => StateManager.getHighlights(),
todos: () => StateManager.getTodos(),
reset: () => StateManager.resetState(),
clear: () => StateManager.clearCaptions()
};
// Inizializzazione
TeamsCaption.EventBus.subscribe('CORE_INITIALIZED', () => {
console.log("✅ State Manager OPTIMIZED Initialized (v3.1.0)");
setupEventListeners();
// Carica preferenze salvate
chrome.storage.local.get(['defaultCustomer', 'defaultProject', 'fileFormat', 'dockMode', 'dockRatio', 'panelMode'], (result) => {
if (result.defaultCustomer) StateManager.setCustomerInfo(result.defaultCustomer);
if (result.defaultProject) StateManager.setProjectInfo(result.defaultProject);
if (result.fileFormat) StateManager.setFileFormat(result.fileFormat);
if (result.panelMode && ['dock', 'fullscreen'].includes(result.panelMode)) {
TeamsCaption.state.panelMode = result.panelMode;
}
if (typeof result.dockMode === 'boolean') {
TeamsCaption.state.dockMode = result.dockMode;
}
if (typeof result.dockRatio === 'number' && Number.isFinite(result.dockRatio)) {
TeamsCaption.state.dockRatio = Math.min(0.5, Math.max(0.2, result.dockRatio));
}
// Carica il titolo del meeting se salvato
chrome.runtime.sendMessage({
action: 'getItem',
key: 'meetingTitle'
}, (response) => {
if (response && response.success && response.value) {
StateManager.setMeetingTitle(response.value);
}
});
});
// Log statistiche iniziali
setTimeout(() => {
console.log("📊 Initial state stats:", StateManager.getStats());
}, 2000);
});
})();