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
|
"use client";
import { useEffect, useRef, useState } from 'react';
import { io, Socket } from 'socket.io-client';
export const useSocket = () => {
const [isConnected, setIsConnected] = useState(false);
const socketRef = useRef<Socket | null>(null);
useEffect(() => {
// Initialize socket connection only on client
if (typeof window === 'undefined') return;
// Create a socket connection
const socket = io({
path: '/api/socket',
addTrailingSlash: false,
});
// Set up event handlers
socket.on('connect', () => {
console.log('Socket connected:', socket.id);
setIsConnected(true);
});
socket.on('disconnect', () => {
console.log('Socket disconnected');
setIsConnected(false);
});
socket.on('connect_error', (err) => {
console.error('Socket connection error:', err);
setIsConnected(false);
});
// Store socket reference
socketRef.current = socket;
// Clean up on unmount
return () => {
socket.disconnect();
};
}, []);
// Join a location share room
const joinLocationShare = (shareToken: string) => {
if (socketRef.current && shareToken) {
socketRef.current.emit('share:join', shareToken);
}
};
// Leave a location share room
const leaveLocationShare = (shareToken: string) => {
if (socketRef.current && shareToken) {
socketRef.current.emit('share:leave', shareToken);
}
};
// Send a location update
const sendLocationUpdate = (data: {
latitude: number;
longitude: number;
accuracy?: number;
shareToken?: string;
}) => {
if (socketRef.current) {
socketRef.current.emit('location:update', {
...data,
timestamp: new Date().toISOString(),
});
}
};
// Subscribe to location updates for a specific share
const subscribeToLocationUpdates = (
shareToken: string,
callback: (data: any) => void
) => {
if (!socketRef.current) return () => {};
// Join the location share room
joinLocationShare(shareToken);
// Listen for location updates
socketRef.current.on('location:updated', callback);
// Return cleanup function
return () => {
if (socketRef.current) {
socketRef.current.off('location:updated', callback);
leaveLocationShare(shareToken);
}
};
};
return {
socket: socketRef.current,
isConnected,
joinLocationShare,
leaveLocationShare,
sendLocationUpdate,
subscribeToLocationUpdates,
};
};
|