277 lines
7.5 KiB
TypeScript
277 lines
7.5 KiB
TypeScript
import { useEffect, useRef, useCallback } from 'react';
|
|
import { useAuthStore } from '@/store/auth';
|
|
import { useListsStore } from '@/store/lists';
|
|
import { useItemsStore } from '@/store/items';
|
|
import type { ListItem, Item } from '@shop/types';
|
|
|
|
/**
|
|
* WebSocket hook for real-time shopping list synchronization
|
|
* Connects to backend and listens for changes from other family members
|
|
*/
|
|
export function useWebSocket() {
|
|
const wsRef = useRef<WebSocket | null>(null);
|
|
const reconnectTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
const pingIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
|
|
|
const { user } = useAuthStore();
|
|
const { lists, updateList, updateListItem, removeListItem, addListItem } = useListsStore();
|
|
const { items } = useItemsStore();
|
|
|
|
// Get active household from current user
|
|
const householdId = user?.householdId;
|
|
|
|
/**
|
|
* Connect to WebSocket server
|
|
*/
|
|
const connect = useCallback(() => {
|
|
if (!user || !householdId) {
|
|
console.warn('[WebSocket] Cannot connect: missing user or household');
|
|
return;
|
|
}
|
|
|
|
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
|
|
console.log('[WebSocket] Already connected');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const baseURL = process.env.EXPO_PUBLIC_API_URL || 'http://localhost:3001';
|
|
// Convert http to ws, https to wss
|
|
const wsURL = baseURL.replace(/^http/, 'ws').replace(/^https/, 'wss');
|
|
|
|
const url = `${wsURL}/api/ws?userId=${user.id}&householdId=${householdId}`;
|
|
|
|
console.log(`[WebSocket] Connecting to ${url}`);
|
|
wsRef.current = new WebSocket(url);
|
|
|
|
wsRef.current.onopen = () => {
|
|
console.log('[WebSocket] Connected');
|
|
// Clear any pending reconnect
|
|
if (reconnectTimeoutRef.current) {
|
|
clearTimeout(reconnectTimeoutRef.current);
|
|
}
|
|
|
|
// Start ping to keep connection alive
|
|
startPingInterval();
|
|
};
|
|
|
|
wsRef.current.onmessage = (event) => {
|
|
try {
|
|
const message = JSON.parse(event.data);
|
|
handleWebSocketMessage(message);
|
|
} catch (err) {
|
|
console.error('[WebSocket] Failed to parse message:', err);
|
|
}
|
|
};
|
|
|
|
wsRef.current.onerror = (error) => {
|
|
console.error('[WebSocket] Connection error:', error);
|
|
};
|
|
|
|
wsRef.current.onclose = () => {
|
|
console.log('[WebSocket] Disconnected');
|
|
stopPingInterval();
|
|
// Attempt to reconnect after 5 seconds
|
|
scheduleReconnect();
|
|
};
|
|
} catch (err) {
|
|
console.error('[WebSocket] Connection failed:', err);
|
|
scheduleReconnect();
|
|
}
|
|
}, [user, householdId]);
|
|
|
|
/**
|
|
* Handle incoming WebSocket messages
|
|
*/
|
|
const handleWebSocketMessage = useCallback(
|
|
(message: any) => {
|
|
const { type, listId, itemId, item, checked, userId, excludedItemIds } = message;
|
|
|
|
// Ignore messages from self (already updated locally)
|
|
if (userId === user?.id) {
|
|
return;
|
|
}
|
|
|
|
console.log(`[WebSocket] Received: ${type} from ${userId}`);
|
|
|
|
const list = lists.find((l) => l.id === listId);
|
|
if (!list) return;
|
|
|
|
switch (type) {
|
|
case 'connected':
|
|
console.log('[WebSocket] Server confirmed connection');
|
|
break;
|
|
|
|
case 'item_checked':
|
|
// Update item checked status in list
|
|
const updatedList = {
|
|
...list,
|
|
items: list.items.map((li) => (li.id === itemId ? { ...li, checked } : li)),
|
|
};
|
|
updateList(updatedList);
|
|
console.log(`[WebSocket] Item ${itemId} checked status updated to ${checked}`);
|
|
break;
|
|
|
|
case 'item_added':
|
|
// Add new item to list (from another family member)
|
|
if (item) {
|
|
addListItem(listId, item);
|
|
console.log(`[WebSocket] Item added: ${item.itemId}`);
|
|
}
|
|
break;
|
|
|
|
case 'item_removed':
|
|
// Remove item from list
|
|
removeListItem(listId, itemId);
|
|
console.log(`[WebSocket] Item ${itemId} removed`);
|
|
break;
|
|
|
|
case 'list_reset':
|
|
// Reset preset list (clear items except excluded)
|
|
const resetList = {
|
|
...list,
|
|
items: list.items.filter((li) => excludedItemIds?.includes(li.id)),
|
|
};
|
|
updateList(resetList);
|
|
console.log(`[WebSocket] List ${listId} reset`);
|
|
break;
|
|
|
|
case 'list_created':
|
|
// New list created by another family member
|
|
// This would be handled by fetching from API instead
|
|
console.log('[WebSocket] New list created by another user');
|
|
break;
|
|
|
|
case 'pong':
|
|
// Response to ping, connection is alive
|
|
break;
|
|
|
|
default:
|
|
console.warn(`[WebSocket] Unknown message type: ${type}`);
|
|
}
|
|
},
|
|
[lists, user?.id, updateList, updateListItem, removeListItem, addListItem]
|
|
);
|
|
|
|
/**
|
|
* Schedule reconnection attempt
|
|
*/
|
|
const scheduleReconnect = useCallback(() => {
|
|
if (reconnectTimeoutRef.current) {
|
|
clearTimeout(reconnectTimeoutRef.current);
|
|
}
|
|
|
|
reconnectTimeoutRef.current = setTimeout(() => {
|
|
console.log('[WebSocket] Attempting to reconnect...');
|
|
connect();
|
|
}, 5000);
|
|
}, [connect]);
|
|
|
|
/**
|
|
* Send message to server
|
|
*/
|
|
const send = useCallback((message: any) => {
|
|
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
|
|
wsRef.current.send(JSON.stringify(message));
|
|
console.log(`[WebSocket] Sent: ${message.type}`);
|
|
} else {
|
|
console.warn('[WebSocket] Not connected, message not sent');
|
|
}
|
|
}, []);
|
|
|
|
/**
|
|
* Start ping interval to keep connection alive
|
|
*/
|
|
const startPingInterval = useCallback(() => {
|
|
if (pingIntervalRef.current) {
|
|
clearInterval(pingIntervalRef.current);
|
|
}
|
|
|
|
pingIntervalRef.current = setInterval(() => {
|
|
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
|
|
send({ type: 'ping' });
|
|
}
|
|
}, 30000); // Ping every 30 seconds
|
|
}, [send]);
|
|
|
|
/**
|
|
* Stop ping interval
|
|
*/
|
|
const stopPingInterval = useCallback(() => {
|
|
if (pingIntervalRef.current) {
|
|
clearInterval(pingIntervalRef.current);
|
|
pingIntervalRef.current = null;
|
|
}
|
|
}, []);
|
|
|
|
/**
|
|
* Disconnect WebSocket
|
|
*/
|
|
const disconnect = useCallback(() => {
|
|
stopPingInterval();
|
|
if (wsRef.current) {
|
|
wsRef.current.close();
|
|
wsRef.current = null;
|
|
}
|
|
}, [stopPingInterval]);
|
|
|
|
/**
|
|
* Connect on mount, disconnect on unmount
|
|
*/
|
|
useEffect(() => {
|
|
connect();
|
|
|
|
return () => {
|
|
disconnect();
|
|
};
|
|
}, [connect, disconnect]);
|
|
|
|
return {
|
|
isConnected: wsRef.current?.readyState === WebSocket.OPEN,
|
|
send,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Convenience functions to send common messages
|
|
*/
|
|
export function useWebSocketActions() {
|
|
const { send } = useWebSocket();
|
|
|
|
return {
|
|
notifyItemChecked: (listId: string, itemId: string, checked: boolean) => {
|
|
send({
|
|
type: 'item_checked',
|
|
data: { listId, itemId, checked },
|
|
});
|
|
},
|
|
|
|
notifyItemAdded: (listId: string, item: ListItem) => {
|
|
send({
|
|
type: 'item_added',
|
|
data: { listId, item },
|
|
});
|
|
},
|
|
|
|
notifyItemRemoved: (listId: string, itemId: string) => {
|
|
send({
|
|
type: 'item_removed',
|
|
data: { listId, itemId },
|
|
});
|
|
},
|
|
|
|
notifyListReset: (listId: string, excludedItemIds: string[]) => {
|
|
send({
|
|
type: 'list_reset',
|
|
data: { listId, excludedItemIds },
|
|
});
|
|
},
|
|
|
|
notifyListCreated: (list: any) => {
|
|
send({
|
|
type: 'list_created',
|
|
data: { list },
|
|
});
|
|
},
|
|
};
|
|
}
|