Commit e2a616fd authored by Sarvin Taba's avatar Sarvin Taba

socketio done

parents
Pipeline #135 canceled with stages
REACT_APP_BACKEND_URL=http://localhost:4500/api
REACT_APP_SOCKET_URL=http://localhost:4500
\ No newline at end of file
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
This diff is collapsed.
{
"name": "backpack-gui",
"version": "0.1.0",
"private": true,
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^1.2.36",
"@fortawesome/free-regular-svg-icons": "^5.15.4",
"@fortawesome/free-solid-svg-icons": "^5.15.4",
"@fortawesome/react-fontawesome": "^0.1.16",
"@testing-library/jest-dom": "^5.15.0",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"axios": "^0.24.0",
"bootstrap": "^5.1.3",
"react": "^17.0.2",
"react-bootstrap": "^2.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.0.1",
"react-scripts": "4.0.3",
"socket.io-client": "^4.3.2",
"web-vitals": "^0.2.4",
"workbox-background-sync": "^5.1.4",
"workbox-broadcast-update": "^5.1.4",
"workbox-cacheable-response": "^5.1.4",
"workbox-core": "^5.1.4",
"workbox-expiration": "^5.1.4",
"workbox-google-analytics": "^5.1.4",
"workbox-navigation-preload": "^5.1.4",
"workbox-precaching": "^5.1.4",
"workbox-range-requests": "^5.1.4",
"workbox-routing": "^5.1.4",
"workbox-strategies": "^5.1.4",
"workbox-streams": "^5.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using create-react-app" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
.App {
text-align: center;
height: 100vh;
display:flex;
flex-direction:column;
}
.btn-block {
display: block;
width: 100%;
}
.fill-height{
flex:1;
overflow-y: scroll;
}
.text-left{
text-align: left !important;
}
import React from "react";
import "./App.css";
import Cameras from "./components/Cameras";
import ImuGps from "./components/ImuGps";
import { Card } from "react-bootstrap";
import Axios from "axios";
import { useContext , useEffect , useState} from "react";
import DebugMessages from "./components/DebugMessages";
import GeneralStatus from "./components/GeneralStatus";
import socketClient from "socket.io-client"
const socket = socketClient("http://127.0.0.1:4500",{ transports: ["websocket"] });
function App() {
// const [CameraData, setCameraData] = useState({});
// const [newCameraData , setNewCameraData] = useState({});
useEffect(() => {
socket.on("connectionStart", (res) => {
console.log(res);
})
socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
// Axios({
// method: "GET",
// withCredentials: true,
// url:
// process.env.REACT_APP_BACKEND_URL +
// "/cameraInfo"
// }).then(async (res) => {
// console.log("********************")
// setCameraData(res)
// });
}, []);
return (
<div className="App pt-3">
<h4>Backpack GUI</h4>
<div className=" m-2 py-1 border border-dark rounded">
<Cameras socket={socket} />
<ImuGps socket={socket} />
</div>
<div className=" m-2 py-1 border border-dark rounded">
<GeneralStatus socket={socket} />
</div>
<div className=" m-2 px-2 border border-dark rounded fill-height text-left">
<DebugMessages socket={socket} />
</div>
</div>
);
}
export default App;
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
import React from "react";
import Camera from "./UIElements/Camera";
import Axios from "axios";
import { useEffect, useState } from "react";
const Cameras = ({socket}) => {
const [cameraData, setCameraData] = useState([]);
const [newCameraData, setNewCameraData] = useState([]);
socket.on("cameraData", (res) => {
console.log(res);
setCameraData(res);
})
// useEffect(() => {
// Axios({
// method: "GET",
// withCredentials: true,
// url: process.env.REACT_APP_BACKEND_URL + "/cameraInfo",
// }).then(async (res) => {
// console.log("********************");
// setCameraData(res.data);
// console.log(res.data);
// });
// }, [newCameraData]);
return (
<React.Fragment>
<div className="row m-1 py-1">
{(cameraData || []).map((cam) => (
<div className="col-3 px-1" key={`divCamera_${cam.name}`}>
<Camera
bat={cam.bat}
sd={cam.sd}
name={cam.name}
connection={cam.connection}
recording={cam.recording}
key={`cameraCom_${cam.name}`}
></Camera>
</div>
))}
</div>
</React.Fragment>
);
};
export default Cameras;
import { useState } from "react";
const DebugMessages =({socket})=>
{
const [debugMessages, setDebugMessages] = useState([]);
socket.on("debugMessages", (res) => {
console.log(res);
setDebugMessages(res);
})
return(
<ul className="list-group">
{(debugMessages || []).map((msg) => (
<li className={"list-group-item " + msg.type } key={`liMessages_${msg.msg_id}`}>{msg.message}</li>
) )}
</ul>
)
}
export default DebugMessages;
\ No newline at end of file
import React , {useState} from "react"
const GeneralStatus =() =>{
const [newDatasetBtn , setNewDatasetBtn ] =useState(true)
const [captueText , setCaptureText ] =useState("Start Capture")
const onNewDataSet =() => {
setNewDatasetBtn(false)
}
const onStartCaptue =() => {
if (captueText === "Start Capture")
setCaptureText("End Capture")
else {
setNewDatasetBtn(true)
setCaptureText("Start Capture")
}
}
return(
<React.Fragment>
<div className=" row m-1 ">
<div className="col-6 px-1 my-1">
<button disabled={!newDatasetBtn} className="btn btn-primary btn-block" onClick={onNewDataSet}>New Dataset</button>
</div>
<div className="col-6 px-1 my-1">DataSetName</div>
<div className="col-6 px-1 my-1">
<button className="btn btn-primary btn-block" disabled={newDatasetBtn} >Start GPS</button>
</div>
<div className="col-6 px-1 my-1">
<button className="btn btn-primary btn-block" disabled={newDatasetBtn} >Start IMU</button>
</div>
<div className="col-12 px-1 my-1">
<button className="btn btn-primary btn-block" disabled={newDatasetBtn} onClick={onStartCaptue}>{captueText}</button>
</div>
</div>
</React.Fragment>
)
}
export default GeneralStatus
\ No newline at end of file
import Axios from "axios";
import { useEffect, useState } from "react";
import Gps from "./UIElements/Gps";
import Imu from "./UIElements/Imu";
const ImuGps = ({socket}) => {
return (
<div className=" row m-1 ">
<div className="col-6 px-1">
<Imu socket={socket}/>
</div>
<div className="col-6 px-1">
<Gps socket={socket}/>
</div>
</div>
);
};
export default ImuGps;
.float-left {
float: left !important;
}
.larger{
font-size: larger;
}
.text-right{
text-align: right;
}
.flash {
animation-name: flash;
animation-duration: 0.5s;
animation-timing-function: linear;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-play-state: running;
}
@keyframes flash {
from {color: green;}
to {color: white;}
}
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faBatteryFull,
faBatteryQuarter,
faLink,
faSdCard,
faUnlink,
} from "@fortawesome/free-solid-svg-icons";
import "./Camera.css";
const Camera = (props) => {
return (
<div className={"border border-dark p-1 rounded " + ( props.connected === 0 ? "" : "border-thick") }>
<div className={props.bat < 20 ? " text-danger" : ""}>
<div className="col-3 float-left text-right">
<FontAwesomeIcon
icon={props.bat < 20 ? faBatteryQuarter : faBatteryFull}
className="menu-icon "
/>
</div>
<span className={props.bat < 20 ? " p-1 text-danger small" : "p-1 small"}>
{props.bat}%
</span>
</div>
<div className={props.connection ? "text-success" :" text-danger"}>
<div className="col-3 float-left text-right">
<FontAwesomeIcon icon={props.connection ? faLink : faUnlink} className="menu-icon" />
</div>
<span className={ props.recording ? "flash small" :" small"}>{props.name}</span>
</div>
<div className={props.sd < 60 ? "m-2 text-danger" : "m-2 "}>
<div className="col-3 float-left text-right">
<FontAwesomeIcon icon={faSdCard} className="menu-icon" />
</div>
<span className="p-1 small">
{Math.floor(props.sd / 60)}:{Math.floor(props.sd % 60)}
</span>
</div>
</div>
);
};
export default Camera;
import Axios from "axios";
import { useEffect, useState } from "react";
const Gps = ({socket}) => {
const lockDic =[{key : 1 , value : "value1"}, {key: 2 , value: "value2"}];
const [gpsData, setGpsData] = useState({});
const [newGpsData, setNewGpsData] = useState({});
socket.on("gpsData", (res) => {
console.log(res);
setGpsData(res);
})
// useEffect(() => {
// Axios({
// method: "GET",
// withCredentials: true,
// url: process.env.REACT_APP_BACKEND_URL + "/gpsInfo",
// }).then(async (res) => {
// console.log("********************");
// setGpsData(res.data);
// console.log(res.data);
// // console.log(lockDic.find((x)=> x.key === gpsData.lock ).value)
// });
// }, [newGpsData]);
return (
<div className={"border p-1 rounded pb-3 border-thicker " + (gpsData.connection ? "border-success " : "border-dark") }>
<h6>GPS</h6>
<div>
<div className="col-6 float-left text-right bold">Status :</div>
<span>{gpsData.lock}</span>
</div>
<div>
<div className="col-6 float-left text-right bold">Accuracy :</div>
<span>{gpsData.accuracy} m</span>
</div>
<div>
<div className="col-6 float-left text-right bold">Base :</div>
<span>{gpsData.base} km</span>
</div>
</div>
);
};
export default Gps;
import Axios from "axios";
import { useEffect, useState } from "react";
const Imu = ({socket}) => {
const [imuData, setImuData] = useState({});
const [newImuData, setNewImuData] = useState({});
socket.on("ImuData", (res) => {
console.log(res);
setImuData(res);
})
// useEffect(() => {
// Axios({
// method: "GET",
// withCredentials: true,
// url: process.env.REACT_APP_BACKEND_URL + "/imuInfo",
// }).then(async (res) => {
// console.log("********************");
// setImuData(res.data);
// console.log(res.data);
// });
// }, [newImuData]);
return (
<div className={"border p-1 rounded pb-3 border-thicker " + (imuData.connection ? "border-success " : "border-dark") }>
<h6>IMU</h6>
<div>
<div className="col-4 float-left text-right bold">X :</div>
<span>{imuData.x}</span>
</div>
<div>
<div className="col-4 float-left text-right bold">Y :</div>
<span>{imuData.y}</span>
</div>
<div>
<div className="col-4 float-left text-right bold">Z :</div>
<span>{imuData.z}</span>
</div>
</div>
);
};
export default Imu;
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
.bold{
font-weight: bold;
}
.border{ overflow: auto !important;}
.border-thick {
border-width: 2px !important;
}
.border-thicker {
border-width: 3px !important;
}
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.min.css';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://cra.link/PWA
serviceWorkerRegistration.unregister();
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
<g fill="#61DAFB">
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
<circle cx="420.9" cy="296.5" r="45.7"/>
<path d="M520.5 78.1z"/>
</g>
</svg>
const reportWebVitals = (onPerfEntry) => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;
/* eslint-disable no-restricted-globals */
// This service worker can be customized!
// See https://developers.google.com/web/tools/workbox/modules
// for the list of available Workbox modules, or add any other
// code you'd like.
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.
import { clientsClaim } from 'workbox-core';
import { ExpirationPlugin } from 'workbox-expiration';
import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
clientsClaim();
// Precache all of the assets generated by your build process.
// Their URLs are injected into the manifest variable below.
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA
precacheAndRoute(self.__WB_MANIFEST);
// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developers.google.com/web/fundamentals/architecture/app-shell
const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$');
registerRoute(
// Return false to exempt requests from being fulfilled by index.html.
({ request, url }) => {
// If this isn't a navigation, skip.
if (request.mode !== 'navigate') {
return false;
} // If this is a URL that starts with /_, skip.
if (url.pathname.startsWith('/_')) {
return false;
} // If this looks like a URL for a resource, because it contains // a file extension, skip.
if (url.pathname.match(fileExtensionRegexp)) {
return false;
} // Return true to signal that we want to use the handler.
return true;
},
createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html')
);
// An example runtime caching route for requests that aren't handled by the
// precache, in this case same-origin .png requests like those from in public/
registerRoute(
// Add in any other file extensions or routing criteria as needed.
({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.png'), // Customize this strategy as needed, e.g., by changing to CacheFirst.
new StaleWhileRevalidate({
cacheName: 'images',
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({ maxEntries: 50 }),
],
})
);
// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
// Any other custom service worker logic can go here.
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://cra.link/PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://cra.link/PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://cra.link/PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch((error) => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' },
})
.then((response) => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log('No internet connection found. App is running in offline mode.');
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then((registration) => {
registration.unregister();
})
.catch((error) => {
console.error(error.message);
});
}
}
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment