Files
nearle_console/src/components/updateNetworkStatus.js
2026-05-13 17:48:36 +05:30

97 lines
2.4 KiB
JavaScript

import { useEffect, useState, useRef } from 'react';
import { useTheme } from '@mui/material/styles';
import WifiOffIcon from '@mui/icons-material/WifiOff';
import WifiIcon from '@mui/icons-material/Wifi';
const NOTIFICATION_STYLE = {
position: 'fixed',
top: '10px', // Keep top spacing
left: '50%', // Center horizontally
transform: 'translateX(-50%)', // Offset to truly center
padding: '12px 40px',
borderRadius: '8px',
color: 'white',
fontWeight: '500',
fontSize: '14px',
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
zIndex: 9999,
maxWidth: '90%',
minWidth: 'auto',
textAlign: 'center'
};
const InternetStatus = () => {
const theme = useTheme();
const [isOnline, setIsOnline] = useState(navigator.onLine);
const [showBackOnline, setShowBackOnline] = useState(false);
const wasOffline = useRef(!navigator.onLine);
useEffect(() => {
const handleNetworkChange = () => {
const online = navigator.onLine;
setIsOnline(online);
if (online && wasOffline.current) {
console.log('✅ Back online');
setShowBackOnline(true);
wasOffline.current = false;
// window.location.reload();
setTimeout(() => {
setShowBackOnline(false);
}, 2000);
}
if (!online) {
console.log('❌ No internet connection');
wasOffline.current = true;
setShowBackOnline(false);
}
};
window.addEventListener('online', handleNetworkChange);
window.addEventListener('offline', handleNetworkChange);
return () => {
window.removeEventListener('online', handleNetworkChange);
window.removeEventListener('offline', handleNetworkChange);
};
}, []);
return (
<>
{!isOnline && (
<div
style={{
...NOTIFICATION_STYLE,
backgroundColor: theme.palette.error.main,
display: 'flex',
alignItems: 'center',
gap: '10px'
}}
>
<WifiOffIcon style={{ color: '#fff' }} />
No Internet Connection
</div>
)}
{showBackOnline && (
<div
style={{
...NOTIFICATION_STYLE,
backgroundColor: theme.palette.success.main,
display: 'flex',
alignItems: 'center',
gap: '10px'
}}
>
<WifiIcon style={{ color: '#fff' }} />
Back Online
</div>
)}
</>
);
};
export default InternetStatus;