├── .gitignore ├── .prettierrc.json ├── .vscode └── settings.json ├── README.md ├── package-lock.json ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt └── src ├── App.css ├── App.js ├── App.test.js ├── PathfindingVisualizer ├── Node │ ├── Node.css │ └── Node.jsx ├── PathfindingVisualizer.css └── PathfindingVisualizer.jsx ├── algorithms └── dijkstra.js ├── index.css ├── index.js ├── logo.svg └── serviceWorker.js /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 80, 3 | "tabWidth": 2, 4 | "useTabs": false, 5 | "semi": true, 6 | "singleQuote": true, 7 | "jsxSingleQuote": false, 8 | "trailingComma": "all", 9 | "bracketSpacing": false, 10 | "jsxBracketSameLine": true, 11 | "arrowParens": "avoid" 12 | } 13 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true 3 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This project is meant to be a tutorial for Clement Mihailescu's [Pathfinding Visualizer project](https://github.com/clementmihailescu/Pathfinding-Visualizer). 2 | 3 | Everything related to the tutorial (i.e., all the code that I, Clement, wrote) is located under /src/PathfindingVisualizer and /src/algorithms. The PathfindingVisualizer component is imported and rendered in App.js. 4 | 5 | If you want to work off of this base to create your own Pathfinding Visualizer, feel free to fork this project or to just copy-paste code. Also, subscribe to my [YouTube channel](https://www.youtube.com/channel/UCaO6VoaYJv4kS-TQO_M-N_g) if you haven't already, and smash the like button on all my videos. Oh, and check out [AlgoExpert](https://www.algoexpert.io/product) if you're preparing for coding interviews. 6 | 7 | Everything below this line was automatically generated by Create React App. 8 | 9 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 10 | 11 | ## Available Scripts 12 | 13 | In the project directory, you can run: 14 | 15 | ### `npm start` 16 | 17 | Runs the app in the development mode.
18 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 19 | 20 | The page will reload if you make edits.
21 | You will also see any lint errors in the console. 22 | 23 | ### `npm test` 24 | 25 | Launches the test runner in the interactive watch mode.
26 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 27 | 28 | ### `npm run build` 29 | 30 | Builds the app for production to the `build` folder.
31 | It correctly bundles React in production mode and optimizes the build for the best performance. 32 | 33 | The build is minified and the filenames include the hashes.
34 | Your app is ready to be deployed! 35 | 36 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 37 | 38 | ### `npm run eject` 39 | 40 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 41 | 42 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 43 | 44 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 45 | 46 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 47 | 48 | ## Learn More 49 | 50 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 51 | 52 | To learn React, check out the [React documentation](https://reactjs.org/). 53 | 54 | ### Code Splitting 55 | 56 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 57 | 58 | ### Analyzing the Bundle Size 59 | 60 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 61 | 62 | ### Making a Progressive Web App 63 | 64 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 65 | 66 | ### Advanced Configuration 67 | 68 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 69 | 70 | ### Deployment 71 | 72 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 73 | 74 | ### `npm run build` fails to minify 75 | 76 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 77 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "my-app", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "react": "^16.10.1", 7 | "react-dom": "^16.10.1", 8 | "react-scripts": "3.1.2" 9 | }, 10 | "scripts": { 11 | "start": "react-scripts start", 12 | "build": "react-scripts build", 13 | "test": "react-scripts test", 14 | "eject": "react-scripts eject" 15 | }, 16 | "eslintConfig": { 17 | "extends": "react-app" 18 | }, 19 | "browserslist": { 20 | "production": [ 21 | ">0.2%", 22 | "not dead", 23 | "not op_mini all" 24 | ], 25 | "development": [ 26 | "last 1 chrome version", 27 | "last 1 firefox version", 28 | "last 1 safari version" 29 | ] 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clementmihailescu/Pathfinding-Visualizer-Tutorial/b31823759e7fddd66010019b326bdd3372b6d9f5/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clementmihailescu/Pathfinding-Visualizer-Tutorial/b31823759e7fddd66010019b326bdd3372b6d9f5/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clementmihailescu/Pathfinding-Visualizer-Tutorial/b31823759e7fddd66010019b326bdd3372b6d9f5/public/logo512.png -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | } 8 | 9 | .App-header { 10 | background-color: #282c34; 11 | min-height: 100vh; 12 | display: flex; 13 | flex-direction: column; 14 | align-items: center; 15 | justify-content: center; 16 | font-size: calc(10px + 2vmin); 17 | color: white; 18 | } 19 | 20 | .App-link { 21 | color: #09d3ac; 22 | } 23 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import './App.css'; 3 | import PathfindingVisualizer from './PathfindingVisualizer/PathfindingVisualizer'; 4 | 5 | function App() { 6 | return ( 7 |
8 | 9 |
10 | ); 11 | } 12 | 13 | export default App; 14 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /src/PathfindingVisualizer/Node/Node.css: -------------------------------------------------------------------------------- 1 | .node { 2 | width: 25px; 3 | height: 25px; 4 | outline: 1px solid rgb(175, 216, 248); 5 | display: inline-block; 6 | } 7 | 8 | .node-finish { 9 | background-color: red; 10 | } 11 | 12 | .node-start { 13 | background-color: green; 14 | } 15 | 16 | .node-visited { 17 | animation-name: visitedAnimation; 18 | animation-duration: 1.5s; 19 | animation-timing-function: ease-out; 20 | animation-delay: 0; 21 | animation-direction: alternate; 22 | animation-iteration-count: 1; 23 | animation-fill-mode: forwards; 24 | animation-play-state: running; 25 | } 26 | 27 | @keyframes visitedAnimation { 28 | 0% { 29 | transform: scale(0.3); 30 | background-color: rgba(0, 0, 66, 0.75); 31 | border-radius: 100%; 32 | } 33 | 34 | 50% { 35 | background-color: rgba(17, 104, 217, 0.75); 36 | } 37 | 38 | 75% { 39 | transform: scale(1.2); 40 | background-color: rgba(0, 217, 159, 0.75); 41 | } 42 | 43 | 100% { 44 | transform: scale(1); 45 | background-color: rgba(0, 190, 218, 0.75); 46 | } 47 | } 48 | 49 | .node-wall { 50 | background-color: rgb(12, 53, 71); 51 | } 52 | 53 | .node-shortest-path { 54 | animation-name: shortestPath; 55 | animation-duration: 1.5s; 56 | animation-timing-function: ease-out; 57 | animation-delay: 0; 58 | animation-direction: alternate; 59 | animation-iteration-count: 1; 60 | animation-fill-mode: forwards; 61 | animation-play-state: running; 62 | } 63 | 64 | @keyframes shortestPath { 65 | 0% { 66 | transform: scale(0.6); 67 | background-color: rgb(255, 254, 106); 68 | } 69 | 70 | 50% { 71 | transform: scale(1.2); 72 | background-color: rgb(255, 254, 106); 73 | } 74 | 75 | 100% { 76 | transform: scale(1); 77 | background-color: rgb(255, 254, 106); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/PathfindingVisualizer/Node/Node.jsx: -------------------------------------------------------------------------------- 1 | import React, {Component} from 'react'; 2 | 3 | import './Node.css'; 4 | 5 | export default class Node extends Component { 6 | render() { 7 | const { 8 | col, 9 | isFinish, 10 | isStart, 11 | isWall, 12 | onMouseDown, 13 | onMouseEnter, 14 | onMouseUp, 15 | row, 16 | } = this.props; 17 | const extraClassName = isFinish 18 | ? 'node-finish' 19 | : isStart 20 | ? 'node-start' 21 | : isWall 22 | ? 'node-wall' 23 | : ''; 24 | 25 | return ( 26 |
onMouseDown(row, col)} 30 | onMouseEnter={() => onMouseEnter(row, col)} 31 | onMouseUp={() => onMouseUp()}>
32 | ); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/PathfindingVisualizer/PathfindingVisualizer.css: -------------------------------------------------------------------------------- 1 | .grid { 2 | margin: 100px 0 0; 3 | } -------------------------------------------------------------------------------- /src/PathfindingVisualizer/PathfindingVisualizer.jsx: -------------------------------------------------------------------------------- 1 | import React, {Component} from 'react'; 2 | import Node from './Node/Node'; 3 | import {dijkstra, getNodesInShortestPathOrder} from '../algorithms/dijkstra'; 4 | 5 | import './PathfindingVisualizer.css'; 6 | 7 | const START_NODE_ROW = 10; 8 | const START_NODE_COL = 15; 9 | const FINISH_NODE_ROW = 10; 10 | const FINISH_NODE_COL = 35; 11 | 12 | export default class PathfindingVisualizer extends Component { 13 | constructor() { 14 | super(); 15 | this.state = { 16 | grid: [], 17 | mouseIsPressed: false, 18 | }; 19 | } 20 | 21 | componentDidMount() { 22 | const grid = getInitialGrid(); 23 | this.setState({grid}); 24 | } 25 | 26 | handleMouseDown(row, col) { 27 | const newGrid = getNewGridWithWallToggled(this.state.grid, row, col); 28 | this.setState({grid: newGrid, mouseIsPressed: true}); 29 | } 30 | 31 | handleMouseEnter(row, col) { 32 | if (!this.state.mouseIsPressed) return; 33 | const newGrid = getNewGridWithWallToggled(this.state.grid, row, col); 34 | this.setState({grid: newGrid}); 35 | } 36 | 37 | handleMouseUp() { 38 | this.setState({mouseIsPressed: false}); 39 | } 40 | 41 | animateDijkstra(visitedNodesInOrder, nodesInShortestPathOrder) { 42 | for (let i = 0; i <= visitedNodesInOrder.length; i++) { 43 | if (i === visitedNodesInOrder.length) { 44 | setTimeout(() => { 45 | this.animateShortestPath(nodesInShortestPathOrder); 46 | }, 10 * i); 47 | return; 48 | } 49 | setTimeout(() => { 50 | const node = visitedNodesInOrder[i]; 51 | document.getElementById(`node-${node.row}-${node.col}`).className = 52 | 'node node-visited'; 53 | }, 10 * i); 54 | } 55 | } 56 | 57 | animateShortestPath(nodesInShortestPathOrder) { 58 | for (let i = 0; i < nodesInShortestPathOrder.length; i++) { 59 | setTimeout(() => { 60 | const node = nodesInShortestPathOrder[i]; 61 | document.getElementById(`node-${node.row}-${node.col}`).className = 62 | 'node node-shortest-path'; 63 | }, 50 * i); 64 | } 65 | } 66 | 67 | visualizeDijkstra() { 68 | const {grid} = this.state; 69 | const startNode = grid[START_NODE_ROW][START_NODE_COL]; 70 | const finishNode = grid[FINISH_NODE_ROW][FINISH_NODE_COL]; 71 | const visitedNodesInOrder = dijkstra(grid, startNode, finishNode); 72 | const nodesInShortestPathOrder = getNodesInShortestPathOrder(finishNode); 73 | this.animateDijkstra(visitedNodesInOrder, nodesInShortestPathOrder); 74 | } 75 | 76 | render() { 77 | const {grid, mouseIsPressed} = this.state; 78 | 79 | return ( 80 | <> 81 | 84 |
85 | {grid.map((row, rowIdx) => { 86 | return ( 87 |
88 | {row.map((node, nodeIdx) => { 89 | const {row, col, isFinish, isStart, isWall} = node; 90 | return ( 91 | this.handleMouseDown(row, col)} 99 | onMouseEnter={(row, col) => 100 | this.handleMouseEnter(row, col) 101 | } 102 | onMouseUp={() => this.handleMouseUp()} 103 | row={row}> 104 | ); 105 | })} 106 |
107 | ); 108 | })} 109 |
110 | 111 | ); 112 | } 113 | } 114 | 115 | const getInitialGrid = () => { 116 | const grid = []; 117 | for (let row = 0; row < 20; row++) { 118 | const currentRow = []; 119 | for (let col = 0; col < 50; col++) { 120 | currentRow.push(createNode(col, row)); 121 | } 122 | grid.push(currentRow); 123 | } 124 | return grid; 125 | }; 126 | 127 | const createNode = (col, row) => { 128 | return { 129 | col, 130 | row, 131 | isStart: row === START_NODE_ROW && col === START_NODE_COL, 132 | isFinish: row === FINISH_NODE_ROW && col === FINISH_NODE_COL, 133 | distance: Infinity, 134 | isVisited: false, 135 | isWall: false, 136 | previousNode: null, 137 | }; 138 | }; 139 | 140 | const getNewGridWithWallToggled = (grid, row, col) => { 141 | const newGrid = grid.slice(); 142 | const node = newGrid[row][col]; 143 | const newNode = { 144 | ...node, 145 | isWall: !node.isWall, 146 | }; 147 | newGrid[row][col] = newNode; 148 | return newGrid; 149 | }; 150 | -------------------------------------------------------------------------------- /src/algorithms/dijkstra.js: -------------------------------------------------------------------------------- 1 | // Performs Dijkstra's algorithm; returns *all* nodes in the order 2 | // in which they were visited. Also makes nodes point back to their 3 | // previous node, effectively allowing us to compute the shortest path 4 | // by backtracking from the finish node. 5 | export function dijkstra(grid, startNode, finishNode) { 6 | const visitedNodesInOrder = []; 7 | startNode.distance = 0; 8 | const unvisitedNodes = getAllNodes(grid); 9 | while (!!unvisitedNodes.length) { 10 | sortNodesByDistance(unvisitedNodes); 11 | const closestNode = unvisitedNodes.shift(); 12 | // If we encounter a wall, we skip it. 13 | if (closestNode.isWall) continue; 14 | // If the closest node is at a distance of infinity, 15 | // we must be trapped and should therefore stop. 16 | if (closestNode.distance === Infinity) return visitedNodesInOrder; 17 | closestNode.isVisited = true; 18 | visitedNodesInOrder.push(closestNode); 19 | if (closestNode === finishNode) return visitedNodesInOrder; 20 | updateUnvisitedNeighbors(closestNode, grid); 21 | } 22 | } 23 | 24 | function sortNodesByDistance(unvisitedNodes) { 25 | unvisitedNodes.sort((nodeA, nodeB) => nodeA.distance - nodeB.distance); 26 | } 27 | 28 | function updateUnvisitedNeighbors(node, grid) { 29 | const unvisitedNeighbors = getUnvisitedNeighbors(node, grid); 30 | for (const neighbor of unvisitedNeighbors) { 31 | neighbor.distance = node.distance + 1; 32 | neighbor.previousNode = node; 33 | } 34 | } 35 | 36 | function getUnvisitedNeighbors(node, grid) { 37 | const neighbors = []; 38 | const {col, row} = node; 39 | if (row > 0) neighbors.push(grid[row - 1][col]); 40 | if (row < grid.length - 1) neighbors.push(grid[row + 1][col]); 41 | if (col > 0) neighbors.push(grid[row][col - 1]); 42 | if (col < grid[0].length - 1) neighbors.push(grid[row][col + 1]); 43 | return neighbors.filter(neighbor => !neighbor.isVisited); 44 | } 45 | 46 | function getAllNodes(grid) { 47 | const nodes = []; 48 | for (const row of grid) { 49 | for (const node of row) { 50 | nodes.push(node); 51 | } 52 | } 53 | return nodes; 54 | } 55 | 56 | // Backtracks from the finishNode to find the shortest path. 57 | // Only works when called *after* the dijkstra method above. 58 | export function getNodesInShortestPathOrder(finishNode) { 59 | const nodesInShortestPathOrder = []; 60 | let currentNode = finishNode; 61 | while (currentNode !== null) { 62 | nodesInShortestPathOrder.unshift(currentNode); 63 | currentNode = currentNode.previousNode; 64 | } 65 | return nodesInShortestPathOrder; 66 | } 67 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 4 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | --------------------------------------------------------------------------------