All files / src/stores commentSync.ts

100% Statements 52/52
94.11% Branches 16/17
100% Functions 7/7
100% Lines 52/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                      7x 7x 7x 7x           7x 7x 6x   6x 6x 6x 1x 1x 1x 6x 7x   1x 1x 7x           7x   7x     7x 1x 1x 1x   1x 1x 7x           7x 10x 10x 1x 1x 10x         7x 8x 8x 8x 8x 1x 1x 8x 8x           7x 13x 5x 5x 5x 13x 13x 13x 7x   1x  
// Types
import { CommentChangePayload, CommentChangeAction } from '@/types/meal';
 
/**
 * Cross-device and cross-tab synchronization for comment changes.
 * Uses BroadcastChannel API for same-device tabs and relies on WebSocket
 * for cross-device synchronization.
 */
 
type CommentSyncListener = (change: CommentChangePayload) => void;
 
class CommentSyncStore {
  private listeners: Set<CommentSyncListener> = new Set();
  private broadcastChannel: BroadcastChannel | null = null;
  private isInitialized = false;
 
  /**
   * Initialize cross-tab broadcast channel.
   * Must be called once per app instance.
   */
  init() {
    if (this.isInitialized) return;
    if (typeof window === 'undefined') return;
 
    try {
      this.broadcastChannel = new BroadcastChannel('comment-sync');
      this.broadcastChannel.onmessage = (event) => {
        const change = event.data as CommentChangePayload;
        this.notifyListeners(change);
      };
      this.isInitialized = true;
    } catch {
      // BroadcastChannel not available in this environment (e.g., private browsing)
      console.debug('BroadcastChannel not available for comment sync');
    }
  }
 
  /**
   * Broadcast a comment change to all tabs on this device and remote listeners.
   * Should be called after a comment API operation (create/update/delete).
   */
  broadcast(change: CommentChangePayload) {
    // Notify local listeners first (same-tab subscribers)
    this.notifyListeners(change);
 
    // Broadcast to other tabs on this device
    if (this.broadcastChannel) {
      try {
        this.broadcastChannel.postMessage(change);
      } catch {
        // Silently fail if broadcast channel is unavailable
      }
    }
  }
 
  /**
   * Subscribe to comment changes from any source (local, other tabs, remote devices).
   * Returns an unsubscribe function.
   */
  subscribe(listener: CommentSyncListener): () => void {
    this.listeners.add(listener);
    return () => {
      this.listeners.delete(listener);
    };
  }
 
  /**
   * Notify all local listeners of a comment change.
   */
  private notifyListeners(change: CommentChangePayload) {
    this.listeners.forEach((listener) => {
      try {
        listener(change);
      } catch (err) {
        console.error('Error in comment sync listener:', err);
      }
    });
  }
 
  /**
   * Clean up resources (close broadcast channel).
   * Called on component unmount or app cleanup.
   */
  destroy() {
    if (this.broadcastChannel) {
      this.broadcastChannel.close();
      this.broadcastChannel = null;
    }
    this.listeners.clear();
    this.isInitialized = false;
  }
}
 
export const commentSyncStore = new CommentSyncStore();