-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseRealtimeDecisions.ts
More file actions
167 lines (142 loc) · 4.78 KB
/
Copy pathuseRealtimeDecisions.ts
File metadata and controls
167 lines (142 loc) · 4.78 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
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import {
getRealtimeChangesAction,
type RealtimeChange,
type ReviewModeStatus,
} from "@/features/mandates/actions/realtime";
// Re-export types for convenience
export type { RealtimeChange, ReviewModeStatus };
interface UseRealtimeDecisionsOptions {
/** Entity to subscribe to */
entity: string;
/** Called when a change is received from another user */
onRemoteChange?: (change: RealtimeChange) => void;
/** Called when review mode status changes */
onReviewModeChange?: (status: ReviewModeStatus) => void;
/** Whether the hook is enabled (default: true) */
enabled?: boolean;
/** Polling interval in ms (default: 3000 = 3 seconds) */
pollIntervalMs?: number;
}
interface UseRealtimeDecisionsReturn {
/** Whether polling is active */
isConnected: boolean;
/** Last error message, if any */
error: string | null;
/** Current review mode status */
reviewModeStatus: ReviewModeStatus | null;
/** Manually trigger a poll */
refresh: () => void;
}
/**
* Hook for real-time decision/comment sync and review mode status via polling
*
* Polls the server every few seconds for changes and review mode updates.
* Designed to work with Vercel serverless functions.
*
* Changes made by the current user are filtered out via timestamp comparison.
*/
export function useRealtimeDecisions({
entity,
onRemoteChange,
onReviewModeChange,
enabled = true,
pollIntervalMs = 3000,
}: UseRealtimeDecisionsOptions): UseRealtimeDecisionsReturn {
const [isConnected, setIsConnected] = useState(false);
const [error, setError] = useState<string | null>(null);
const [reviewModeStatus, setReviewModeStatus] =
useState<ReviewModeStatus | null>(null);
// Track last poll time to only fetch new changes
const lastPollTimeRef = useRef<string>(new Date().toISOString());
// Track IDs we've already processed to avoid duplicates
const processedIdsRef = useRef<Set<string>>(new Set());
// Polling interval ref
const pollIntervalRef = useRef<NodeJS.Timeout | null>(null);
// Callback refs to avoid stale closures
const onRemoteChangeRef = useRef(onRemoteChange);
const onReviewModeChangeRef = useRef(onReviewModeChange);
// Keep callback refs updated
useEffect(() => {
onRemoteChangeRef.current = onRemoteChange;
}, [onRemoteChange]);
useEffect(() => {
onReviewModeChangeRef.current = onReviewModeChange;
}, [onReviewModeChange]);
const poll = useCallback(async () => {
if (!enabled || !entity) return;
try {
const result = await getRealtimeChangesAction(
entity,
lastPollTimeRef.current,
);
if (!result.success) {
throw new Error(result.error);
}
const data = result.data;
if (!data) {
throw new Error("No data returned");
}
// Update last poll time from server
if (data.serverTime) {
lastPollTimeRef.current = data.serverTime;
}
setIsConnected(true);
setError(null);
// Update review mode status if present
if (data.reviewMode) {
const newStatus: ReviewModeStatus = {
isUnderReview: data.reviewMode.isUnderReview,
reviewSessionId: data.reviewMode.reviewSessionId,
reviewStartedBy: data.reviewMode.reviewStartedBy,
};
setReviewModeStatus(newStatus);
onReviewModeChangeRef.current?.(newStatus);
}
// Process changes
if (data.hasChanges && data.changes?.length > 0) {
for (const change of data.changes) {
// Skip if already processed
if (processedIdsRef.current.has(change.id)) continue;
// Mark as processed
processedIdsRef.current.add(change.id);
// Prune processed set if it grows too large
if (processedIdsRef.current.size > 500) {
const arr = Array.from(processedIdsRef.current);
processedIdsRef.current = new Set(arr.slice(-250));
}
// Notify callback
onRemoteChangeRef.current?.(change);
}
}
} catch (err) {
setError(err instanceof Error ? err.message : "Poll failed");
setIsConnected(false);
}
}, [enabled, entity]);
const refresh = useCallback(() => {
poll();
}, [poll]);
// Start polling on mount
useEffect(() => {
if (!enabled || !entity) return;
// Initial poll
// eslint-disable-next-line react-hooks/set-state-in-effect
poll();
// Set up interval
pollIntervalRef.current = setInterval(poll, pollIntervalMs);
return () => {
if (pollIntervalRef.current) {
clearInterval(pollIntervalRef.current);
pollIntervalRef.current = null;
}
};
}, [enabled, entity, poll, pollIntervalMs]);
return {
isConnected,
error,
reviewModeStatus,
refresh,
};
}