My App
BoardKitFrontend

useCollaboration

WebSocket connection for realtime collaboration

useCollaboration manages the WebSocket connection for realtime collaboration, including mutation sending, cursor sharing, and automatic reconnection.

Signature

function useCollaboration(boardId: string): UseCollaborationResult;

Return Type

interface UseCollaborationResult {
    connectionState: ConnectionState;
    sendMutations: (mutations: ElementMutation[]) => void;
    sendCursor: (position: { x: number; y: number }, pageId: string) => void;
    disconnect: () => void;
}

type ConnectionState = 'connecting' | 'connected' | 'reconnecting' | 'disconnected';
PropertyDescription
connectionStateCurrent connection status
sendMutationsSend element mutations to the server
sendCursorBroadcast cursor position to other participants
disconnectManually close the WebSocket connection

Usage

import { useCollaboration } from '@hfu.digital/boardkit-react';

function CollaborationStatus({ boardId }: { boardId: string }) {
    const { connectionState, disconnect } = useCollaboration(boardId);

    return (
        <div>
            <span>Status: {connectionState}</span>
            <button onClick={disconnect}>Disconnect</button>
        </div>
    );
}

Connection Lifecycle

  1. On mount, opens a WebSocket to config.wsUrl
  2. Sends a join message with boardId, authToken, and optional lastSequence
  3. Receives joined message confirming the connection
  4. Receives either sync:full or sync:delta for initial state

Reconnection

  • Max 5 reconnect attempts
  • Exponential backoff with jitter: min(1000 * 2^attempt + random(0-1000), 30000)ms
  • On reconnect, sends lastSequence for delta sync
  • After max attempts, sets connectionState to 'disconnected' and stores an error in the BoardStore

Message Handling

Server MessageAction
joinedSet connected, update sequence
sync:deltaUpdate sequence
sync:fullUpdate sequence
mutation:ackUpdate sequence
mutation:broadcastApply remote mutations to the store's scene
cursor:broadcastUpdate cursor position in the store
participant:joined(no-op, handled by presence)
participant:leftRemove cursor from store
rate-limitedLog warning with retry delay
errorLog error; if SESSION_MISMATCH, store non-recoverable error

On this page