teamsync / src /lib /client /socket.ts
shahzaib24681012's picture
Batch 1-3: fixes, advanced features, visual consistency
4498c94
Raw History Blame Contribute Delete
2.38 kB
'use client';
import { io, Socket } from 'socket.io-client';
let socket: Socket | null = null;
export function getSocket(): Socket {
if (!socket) {
socket = io({ path: '/socket.io', autoConnect: true, reconnection: true });
// if the access token expired while idle, the reconnect handshake is rejected —
// refresh the session and try again so realtime never silently dies
let refreshingAuth = false;
socket.on('connect_error', async (err) => {
if (refreshingAuth || !/unauthorized/i.test(err.message)) return;
refreshingAuth = true;
try {
const res = await fetch('/api/auth/refresh', { method: 'POST' });
if (res.ok) socket?.connect();
} catch { /* next reconnect attempt will retry */ }
finally {
setTimeout(() => { refreshingAuth = false; }, 3000);
}
});
// away/active presence based on tab visibility + idle
let idleTimer: ReturnType<typeof setTimeout> | null = null;
const setAway = () => socket?.emit('presence:set', 'away');
const setActive = () => {
socket?.emit('presence:set', 'online');
if (idleTimer) clearTimeout(idleTimer);
idleTimer = setTimeout(setAway, 10 * 60 * 1000); // 10 min idle → away
};
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => (document.hidden ? setAway() : setActive()));
['mousemove', 'keydown', 'click'].forEach((ev) =>
document.addEventListener(ev, throttle(setActive, 30_000), { passive: true }),
);
setActive();
}
}
return socket;
}
export function disconnectSocket() {
socket?.disconnect();
socket = null;
}
function throttle<T extends (...args: never[]) => void>(fn: T, ms: number): T {
let last = 0;
return ((...args: never[]) => {
const now = Date.now();
if (now - last > ms) {
last = now;
fn(...args);
}
}) as T;
}
/** Browser push notification (Chrome Notification API) when tab is unfocused. */
export function maybeDesktopNotify(title: string, body: string) {
if (typeof window === 'undefined' || !('Notification' in window)) return;
if (!document.hidden) return;
if (Notification.permission === 'granted') {
new Notification(title, { body, icon: '/favicon.ico' });
} else if (Notification.permission === 'default') {
Notification.requestPermission();
}
}