-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathcreateAwarenessStore.ts
More file actions
768 lines (660 loc) · 23 KB
/
createAwarenessStore.ts
File metadata and controls
768 lines (660 loc) · 23 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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
/**
* # AwarenessStore
*
* This store implements the same pattern as WorkflowStore and AdaptorStore:
* useSyncExternalStore + Immer for optimal performance and referential stability.
*
* ## Core Principles:
* - Awareness as reactive data source (similar to Y.Doc)
* - Immer for referentially stable state updates
* - Command Query Separation (CQS) for predictable state mutations
* - Maximum referential stability to minimize React re-renders
* - Clean separation between collaborative awareness data and local UI state
*
* ## Update Patterns:
*
* ### Pattern 1: Awareness → Observer → Immer → Notify (Collaborative Data)
* **When to use**: All collaborative awareness data (users, cursors, selections)
* **Flow**: Awareness change → observer fires → validate → Immer update → React notification
* **Benefits**: Real-time collaboration, automatic conflict resolution, referential stability
*
* ```typescript
* // Example: Awareness state changes trigger observer
* awareness.on('change', () => {
* const users = extractUsersFromAwareness(awareness);
* state = produce(state, (draft) => {
* draft.users = users; // Referentially stable update
* draft.lastUpdated = Date.now();
* });
* notify();
* });
* ```
*
* ### Pattern 2: Direct Immer → Notify + Awareness Update (Local Commands)
* **When to use**: Local user actions that need to update awareness
* **Flow**: Command → update awareness → immediate local state update → notify
* **Benefits**: Immediate UI feedback, maintains consistency
*
* ```typescript
* // Example: Update local cursor position
* const updateLocalCursor = (cursor: { x: number; y: number } | null) => {
* if (awareness) {
* awareness.setLocalStateField('cursor', cursor);
* }
*
* state = produce(state, (draft) => {
* if (draft.localUser) {
* // Update local state immediately for responsiveness
* const localUserIndex = draft.users.findIndex(u => u.user.id === draft.localUser?.id);
* if (localUserIndex !== -1 && cursor) {
* draft.users[localUserIndex].cursor = cursor;
* }
* }
* });
* notify();
* };
* ```
*
* ### Pattern 3: Direct Immer → Notify (Local UI State)
* **When to use**: Local state that doesn't affect awareness
* **Flow**: Direct Immer update → React notification
* **Benefits**: Simple, immediate response
*
* ## Architecture Benefits:
* - Removes awareness dependency from SessionProvider context
* - Provides memoized selectors for referential stability
* - Separates awareness management from session lifecycle
* - Enables fine-grained subscriptions to specific awareness data
*/
/**
* ## Redux DevTools Integration
*
* This store integrates with Redux DevTools for debugging in
* development and test environments.
*
* **Features:**
* - Real-time state inspection
* - Action history with timestamps
* - Time-travel debugging (jump to previous states)
* - State export/import for reproducing bugs
*
* **Usage:**
* 1. Install Redux DevTools browser extension
* 2. Open DevTools and select the "AwarenessStore" instance
* 3. Perform actions in the app and watch them appear in DevTools
*
* **Note:** DevTools is automatically disabled in production builds.
*
* **Excluded from DevTools:**
* rawAwareness (too large/circular)
*/
import { produce } from 'immer';
import type { Awareness } from 'y-protocols/awareness';
import _logger from '#/utils/logger';
import type {
ActivityState,
AwarenessState,
AwarenessStore,
AwarenessUser,
LocalUserData,
SetStateHandler,
} from '../types/awareness';
import { getVisibilityProps } from '../utils/visibility';
import { createWithSelector } from './common';
import { wrapStoreWithDevTools } from './devtools';
const logger = _logger.ns('AwarenessStore').seal();
/**
* Creates an awareness store instance with useSyncExternalStore + Immer pattern
*/
export const createAwarenessStore = (): AwarenessStore => {
// Single Immer-managed state object (referentially stable)
let state: AwarenessState = produce(
{
users: [],
localUser: null,
isInitialized: false,
cursorsMap: new Map(),
rawAwareness: null,
isConnected: false,
lastUpdated: null,
userCache: new Map(),
} as AwarenessState,
// No initial transformations needed
draft => draft
);
const listeners = new Set<() => void>();
let awarenessInstance: Awareness | null = null;
let lastSeenTimer: NodeJS.Timeout | null = null;
let cacheCleanupTimer: NodeJS.Timeout | null = null;
// Cache configuration
const CACHE_TTL = 60 * 1000; // 1 minute in milliseconds
// Redux DevTools integration
const devtools = wrapStoreWithDevTools({
name: 'AwarenessStore',
excludeKeys: ['rawAwareness', 'userCache'], // Exclude Y.js Awareness object and Map cache
maxAge: 200, // Higher limit since awareness changes are frequent
});
const notify = (actionName: string = 'stateChange') => {
devtools.notifyWithAction(actionName, () => state);
listeners.forEach(listener => {
listener();
});
};
// =============================================================================
// CORE STORE INTERFACE
// =============================================================================
const subscribe = (listener: () => void) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
const getSnapshot = (): AwarenessState => state;
// withSelector utility - creates memoized selectors for referential stability
const withSelector = createWithSelector(getSnapshot);
// =============================================================================
// PATTERN 1: Awareness → Observer → Immer → Notify (Collaborative Data)
// =============================================================================
/**
* Helper: Compare cursor positions for referential stability
* Handles both null and undefined (Y.js awareness uses null when clearing)
*/
const arePositionsEqual = (
a: { x: number; y: number } | undefined | null,
b: { x: number; y: number } | undefined | null
): boolean => {
// Use == null to catch both null and undefined
if (a == null && b == null) return true;
if (a == null || b == null) return false;
return a.x === b.x && a.y === b.y;
};
/**
* Helper: Compare selections (RelativePosition) for referential stability
* Handles both null and undefined (Y.js awareness uses null when clearing)
*/
const areSelectionsEqual = (
a: AwarenessUser['selection'] | undefined | null,
b: AwarenessUser['selection'] | undefined | null
): boolean => {
// Use == null to catch both null and undefined
if (a == null && b == null) return true;
if (a == null || b == null) return false;
// RelativePosition objects from Yjs need proper comparison
// Using JSON.stringify for deep equality check
return (
JSON.stringify(a.anchor) === JSON.stringify(b.anchor) &&
JSON.stringify(a.head) === JSON.stringify(b.head)
);
};
/**
* Handle awareness state changes - core collaborative data update pattern
*/
const handleAwarenessChange = () => {
if (!awarenessInstance) {
logger.warn('handleAwarenessChange called without awareness instance');
return;
}
// Capture awareness instance for closure
const awareness = awarenessInstance;
state = produce(state, draft => {
const awarenessStates = awareness.getStates();
const now = Date.now();
// Track which clientIds we've seen in this update
const seenClientIds = new Set<number>();
// Update or add users using Immer's Map support
awarenessStates.forEach((awarenessState, clientId) => {
seenClientIds.add(clientId);
// Validate user data exists
if (!awarenessState['user']) {
return;
}
try {
// Get existing user from Map (if any)
const existingUser = draft.cursorsMap.get(clientId);
// Extract new data
const userData = awarenessState['user'] as AwarenessUser['user'];
const cursor = awarenessState['cursor'] as AwarenessUser['cursor'];
const selection = awarenessState[
'selection'
] as AwarenessUser['selection'];
const lastSeen = awarenessState['lastSeen'] as number | undefined;
const lastState = awarenessState['lastState'] as
| ActivityState
| undefined;
// Check if user data actually changed
if (existingUser) {
let hasChanged = false;
// Compare user fields
if (
existingUser.user.id !== userData.id ||
existingUser.user.name !== userData.name ||
existingUser.user.email !== userData.email ||
existingUser.user.color !== userData.color
) {
hasChanged = true;
}
// Compare cursor
if (!arePositionsEqual(existingUser.cursor, cursor)) {
hasChanged = true;
}
// Compare selection
if (!areSelectionsEqual(existingUser.selection, selection)) {
hasChanged = true;
}
// Compare lastSeen
if (existingUser.lastSeen !== lastSeen) {
hasChanged = true;
}
// compare lastState
if (existingUser.lastState !== lastState) {
hasChanged = true;
}
// Only update if something changed
// If not changed, Immer preserves the existing reference
if (hasChanged) {
draft.cursorsMap.set(clientId, {
clientId,
user: userData,
cursor,
selection,
lastSeen,
lastState,
});
}
} else {
// New user - add to map
draft.cursorsMap.set(clientId, {
clientId,
user: userData,
cursor,
selection,
lastSeen,
lastState,
});
}
// Update cache for this active user
draft.userCache.set(userData.id, {
user: draft.cursorsMap.get(clientId)!,
cachedAt: now,
});
} catch (error) {
logger.warn('Invalid user data for client', clientId, error);
}
});
// Remove users that are no longer in awareness from cursorsMap
const entriesToDelete: number[] = [];
draft.cursorsMap.forEach((_, clientId) => {
if (!seenClientIds.has(clientId)) {
entriesToDelete.push(clientId);
}
});
entriesToDelete.forEach(clientId => {
draft.cursorsMap.delete(clientId);
});
// Rebuild users array from cursorsMap
const liveUsers = Array.from(draft.cursorsMap.values());
// Merge with cached users (inactive collaborators within cache TTL)
const liveUserIds = new Set(liveUsers.map(u => u.user.id));
const cachedUsers: AwarenessUser[] = [];
draft.userCache.forEach((cachedUser, userId) => {
if (!liveUserIds.has(userId)) {
// Only add if cache is still valid
if (now - cachedUser.cachedAt <= CACHE_TTL) {
cachedUsers.push(cachedUser.user);
} else {
// Clean up expired cache entry
draft.userCache.delete(userId);
}
}
});
// Combine live and cached users, then sort by name for consistent ordering
draft.users = [...liveUsers, ...cachedUsers].sort((a, b) =>
a.user.name.localeCompare(b.user.name)
);
draft.lastUpdated = Date.now();
});
notify('awarenessChange');
};
const visibilityProps = getVisibilityProps();
const activityStateChangeHandler = (setState: SetStateHandler) => {
const isHidden = document[visibilityProps?.hidden as keyof Document];
if (isHidden) {
setState('away');
} else {
setState('active');
}
};
const initActivityStateChange = (setState: SetStateHandler) => {
if (visibilityProps) {
const handler = activityStateChangeHandler.bind(undefined, setState);
// initial call
handler();
document.addEventListener(visibilityProps.visibilityChange, handler);
// return cleanup function
return () => {
document.removeEventListener(visibilityProps.visibilityChange, handler);
};
}
};
// =============================================================================
// PATTERN 2: Direct Immer → Notify + Awareness Update (Local Commands)
// =============================================================================
/**
* Set up periodic cache cleanup
*/
const setupCacheCleanup = () => {
if (cacheCleanupTimer) {
clearInterval(cacheCleanupTimer);
}
// Clean up expired cache entries every 30 seconds
cacheCleanupTimer = setInterval(() => {
const now = Date.now();
const newCache = new Map(state.userCache);
let hasChanges = false;
newCache.forEach((cachedUser, userId) => {
if (now - cachedUser.cachedAt > CACHE_TTL) {
newCache.delete(userId);
hasChanges = true;
}
});
if (hasChanges) {
state = produce(state, draft => {
draft.userCache = newCache;
});
notify('cacheCleanup');
}
}, 30000); // Check every 30 seconds
};
/**
* Initialize awareness instance and set up observers
*/
const initializeAwareness = (
awareness: Awareness,
userData: LocalUserData
) => {
logger.debug('Initializing awareness', { userData });
awarenessInstance = awareness;
// Set up awareness with user data
awareness.setLocalStateField('user', userData);
awareness.setLocalStateField('lastSeen', Date.now());
// Set up awareness observer for Pattern 1 updates
awareness.on('change', handleAwarenessChange);
// Set up cache cleanup
setupCacheCleanup();
// Update local state
state = produce(state, draft => {
draft.localUser = userData;
draft.rawAwareness = awareness;
draft.isInitialized = true;
draft.isConnected = true;
draft.lastUpdated = Date.now();
});
// Initial sync of users
handleAwarenessChange();
devtools.connect();
notify('initializeAwareness');
};
/**
* Clean up awareness instance
*/
const destroyAwareness = () => {
logger.debug('Destroying awareness');
if (awarenessInstance) {
awarenessInstance.off('change', handleAwarenessChange);
awarenessInstance = null;
}
if (lastSeenTimer) {
clearInterval(lastSeenTimer);
lastSeenTimer = null;
}
if (cacheCleanupTimer) {
clearInterval(cacheCleanupTimer);
cacheCleanupTimer = null;
}
devtools.disconnect();
state = produce(state, draft => {
draft.users = [];
draft.cursorsMap.clear();
draft.localUser = null;
draft.rawAwareness = null;
draft.isInitialized = false;
draft.isConnected = false;
draft.lastUpdated = Date.now();
draft.userCache = new Map();
});
notify('destroyAwareness');
};
/**
* Update local user data in awareness
*/
const updateLocalUserData = (userData: Partial<LocalUserData>) => {
if (!awarenessInstance || !state.localUser) {
logger.warn('Cannot update user data - awareness not initialized');
return;
}
const updatedUserData = { ...state.localUser, ...userData };
// Update awareness first
awarenessInstance.setLocalStateField('user', updatedUserData);
// Update local state for immediate UI response
state = produce(state, draft => {
draft.localUser = updatedUserData;
});
notify('updateLocalUserData');
// Note: awareness observer will also fire and update the users array
};
/**
* Update local cursor position
*/
const updateLocalCursor = (cursor: { x: number; y: number } | null) => {
if (!awarenessInstance) {
logger.warn('Cannot update cursor - awareness not initialized');
return;
}
// Update awareness
awarenessInstance.setLocalStateField('cursor', cursor);
// Immediate local state update for responsiveness
state = produce(state, draft => {
if (draft.localUser) {
const localUserIndex = draft.users.findIndex(
u => u.user.id === draft.localUser?.id
);
if (localUserIndex !== -1 && draft.users[localUserIndex]) {
if (cursor) {
draft.users[localUserIndex].cursor = cursor;
} else {
delete draft.users[localUserIndex].cursor;
}
}
}
});
notify('updateLocalCursor');
};
/**
* Update local text selection
*/
const updateLocalSelection = (
selection: AwarenessUser['selection'] | null
) => {
if (!awarenessInstance) {
logger.warn('Cannot update selection - awareness not initialized');
return;
}
// Update awareness
awarenessInstance.setLocalStateField('selection', selection);
// Immediate local state update for responsiveness
state = produce(state, draft => {
if (draft.localUser) {
const localUserIndex = draft.users.findIndex(
u => u.user.id === draft.localUser?.id
);
if (localUserIndex !== -1 && draft.users[localUserIndex]) {
if (selection) {
draft.users[localUserIndex].selection = selection;
} else {
delete draft.users[localUserIndex].selection;
}
}
}
});
notify('updateLocalSelection');
};
/**
* Update last seen timestamp
* @param forceTimestamp - Optional timestamp to use instead of Date.now()
*/
const updateLastSeen = (forceTimestamp?: number) => {
if (!awarenessInstance) {
return;
}
const timestamp = forceTimestamp ?? Date.now();
awarenessInstance.setLocalStateField('lastSeen', timestamp);
// Note: We don't update local state here as awareness observer will handle it
};
/**
* Set up automatic last seen updates
*/
const setupLastSeenTimer = () => {
let frozenTimestamp: number | null = null;
const startTimer = () => {
if (lastSeenTimer) {
clearInterval(lastSeenTimer);
}
lastSeenTimer = setInterval(() => {
// If page is hidden, use frozen timestamp, otherwise use current time
if (frozenTimestamp) frozenTimestamp++; // This is to make sure that state is updated and data gets transmitted
updateLastSeen(frozenTimestamp ?? undefined);
}, 10000); // Update every 10 seconds
};
const getVisibilityProps = () => {
if (typeof document.hidden !== 'undefined') {
return { hidden: 'hidden', visibilityChange: 'visibilitychange' };
}
if (
// @ts-expect-error webkitHidden not defined
typeof (document as unknown as Document).webkitHidden !== 'undefined'
) {
return {
hidden: 'webkitHidden',
visibilityChange: 'webkitvisibilitychange',
};
}
// @ts-expect-error mozHidden not defined
if (typeof (document as unknown as Document).mozHidden !== 'undefined') {
return { hidden: 'mozHidden', visibilityChange: 'mozvisibilitychange' };
}
// @ts-expect-error msHidden not defined
if (typeof (document as unknown as Document).msHidden !== 'undefined') {
return { hidden: 'msHidden', visibilityChange: 'msvisibilitychange' };
}
return null;
};
const visibilityProps = getVisibilityProps();
const handleVisibilityChange = () => {
if (!visibilityProps) return;
const isHidden = (document as unknown as Document)[
visibilityProps.hidden as keyof Document
];
if (isHidden) {
// Page is hidden, freeze the current timestamp
frozenTimestamp = Date.now();
} else {
// Page is visible, unfreeze and update immediately
frozenTimestamp = null;
updateLastSeen();
}
};
// Set up visibility change listener if supported
if (visibilityProps) {
document.addEventListener(
visibilityProps.visibilityChange,
handleVisibilityChange
);
// Check initial visibility state
const isHidden = (document as unknown as Document)[
visibilityProps.hidden as keyof Document
];
if (isHidden) {
// Start with frozen timestamp if already hidden
frozenTimestamp = Date.now();
}
}
// Always start the timer (whether visible or hidden)
startTimer();
// cleanup
return () => {
if (lastSeenTimer) {
clearInterval(lastSeenTimer);
lastSeenTimer = null;
}
if (visibilityProps) {
document.removeEventListener(
visibilityProps.visibilityChange,
handleVisibilityChange
);
}
};
};
// =============================================================================
// PATTERN 3: Direct Immer → Notify (Local UI State)
// =============================================================================
/**
* Set connection state
*/
const setConnected = (isConnected: boolean) => {
state = produce(state, draft => {
draft.isConnected = isConnected;
});
notify('setConnected');
};
// =============================================================================
// QUERY HELPERS (CQS Pattern)
// =============================================================================
const getAllUsers = (): AwarenessUser[] => state.users;
const getRemoteUsers = (): AwarenessUser[] => {
if (!state.localUser) return state.users;
return state.users.filter(user => user.user.id !== state.localUser?.id);
};
const getLocalUser = (): LocalUserData | null => state.localUser;
const getUserById = (userId: string): AwarenessUser | null => {
return state.users.find(user => user.user.id === userId) || null;
};
const getUserByClientId = (clientId: number): AwarenessUser | null => {
return state.users.find(user => user.clientId === clientId) || null;
};
const isAwarenessReady = (): boolean => {
return state.isInitialized && state.rawAwareness !== null;
};
const getConnectionState = (): boolean => state.isConnected;
const getRawAwareness = (): Awareness | null => state.rawAwareness;
// =============================================================================
// PUBLIC INTERFACE
// =============================================================================
return {
// Core store interface
subscribe,
getSnapshot,
withSelector,
// Commands (CQS pattern)
initializeAwareness,
destroyAwareness,
updateLocalUserData,
updateLocalCursor,
updateLocalSelection,
updateLastSeen,
setConnected,
// Queries (CQS pattern)
getAllUsers,
getRemoteUsers,
getLocalUser,
getUserById,
getUserByClientId,
isAwarenessReady,
getConnectionState,
getRawAwareness,
// Internal methods (for SessionProvider integration)
_internal: {
handleAwarenessChange,
setupLastSeenTimer,
initActivityStateChange,
},
};
};
export type AwarenessStoreInstance = ReturnType<typeof createAwarenessStore>;