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';| Property | Description |
|---|---|
connectionState | Current connection status |
sendMutations | Send element mutations to the server |
sendCursor | Broadcast cursor position to other participants |
disconnect | Manually 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
- On mount, opens a WebSocket to
config.wsUrl - Sends a
joinmessage withboardId,authToken, and optionallastSequence - Receives
joinedmessage confirming the connection - Receives either
sync:fullorsync:deltafor initial state
Reconnection
- Max 5 reconnect attempts
- Exponential backoff with jitter:
min(1000 * 2^attempt + random(0-1000), 30000)ms - On reconnect, sends
lastSequencefor delta sync - After max attempts, sets
connectionStateto'disconnected'and stores an error in theBoardStore
Message Handling
| Server Message | Action |
|---|---|
joined | Set connected, update sequence |
sync:delta | Update sequence |
sync:full | Update sequence |
mutation:ack | Update sequence |
mutation:broadcast | Apply remote mutations to the store's scene |
cursor:broadcast | Update cursor position in the store |
participant:joined | (no-op, handled by presence) |
participant:left | Remove cursor from store |
rate-limited | Log warning with retry delay |
error | Log error; if SESSION_MISMATCH, store non-recoverable error |