├── .gitignore ├── LICENSE.md ├── README.md ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt ├── src ├── App.css ├── App.tsx ├── CodeMirror.tsx ├── Plot │ ├── index.css │ └── index.tsx ├── Util.ts ├── index.css ├── index.tsx ├── react-app-env.d.ts ├── serviceWorker.ts └── setupTests.ts ├── tsconfig.json └── yarn.lock /.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 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Fredrik Norén 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jsplot 2 | 3 | A very simple utility for plotting a series of numbers. Just browse to https://fredriknoren.github.io/jsplot and 4 | paste any javascript that returns an array of numbers, and it'll be plotted. 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jsplot", 3 | "version": "0.1.0", 4 | "homepage": "https://FredrikNoren.github.io/jsplot", 5 | "private": true, 6 | "dependencies": { 7 | "@testing-library/jest-dom": "^4.2.4", 8 | "@testing-library/react": "^9.3.2", 9 | "@testing-library/user-event": "^7.1.2", 10 | "@types/codemirror": "^0.0.96", 11 | "@types/jest": "^24.0.0", 12 | "@types/lodash": "^4.14.157", 13 | "@types/node": "^12.0.0", 14 | "@types/react": "^16.9.0", 15 | "@types/react-dom": "^16.9.0", 16 | "codemirror": "^5.55.0", 17 | "codemirror-one-dark-theme": "^1.1.1", 18 | "gh-pages": "^3.1.0", 19 | "lodash": "^4.17.19", 20 | "react": "^16.13.1", 21 | "react-dom": "^16.13.1", 22 | "react-scripts": "3.4.1", 23 | "typescript": "~3.7.2" 24 | }, 25 | "scripts": { 26 | "start": "react-scripts start", 27 | "build": "react-scripts build", 28 | "test": "react-scripts test", 29 | "eject": "react-scripts eject", 30 | "predeploy": "npm run build", 31 | "deploy": "gh-pages -d build" 32 | }, 33 | "eslintConfig": { 34 | "extends": "react-app" 35 | }, 36 | "browserslist": { 37 | "production": [ 38 | ">0.2%", 39 | "not dead", 40 | "not op_mini all" 41 | ], 42 | "development": [ 43 | "last 1 chrome version", 44 | "last 1 firefox version", 45 | "last 1 safari version" 46 | ] 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FredrikNoren/jsplot/641cae8c55182b5a4cbd1b27e3449f784b4b38d9/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 14 | jsplot 15 | 16 | 17 | 18 |
19 | 20 | 21 | -------------------------------------------------------------------------------- /public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FredrikNoren/jsplot/641cae8c55182b5a4cbd1b27e3449f784b4b38d9/public/logo192.png -------------------------------------------------------------------------------- /public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FredrikNoren/jsplot/641cae8c55182b5a4cbd1b27e3449f784b4b38d9/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 | Disallow: 4 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | 2 | .App { 3 | display: flex; 4 | flex-direction: row; 5 | position: absolute; 6 | left: 0px; 7 | right: 0px; 8 | top: 0px; 9 | bottom: 0px; 10 | color: #bbb; 11 | } 12 | .Left, .Right { 13 | width: 50%; 14 | } 15 | .Right { 16 | min-width: 630px; 17 | } 18 | .Left > div { 19 | flex: 1; 20 | display: flex; 21 | flex-direction: column; 22 | height: 100%; 23 | } 24 | .Right .Plot { 25 | margin-top: 20px; 26 | } 27 | .CodeMirror { 28 | flex: 1; 29 | } 30 | .Error { 31 | margin-top: 20px; 32 | color: rgb(247, 78, 27); 33 | font-weight: bold; 34 | } 35 | 36 | .Header { 37 | font-size: 12px; 38 | position: absolute; 39 | top: 0px; 40 | right: 0px; 41 | z-index: 10; 42 | } 43 | a { 44 | color: #eaea70; 45 | } -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { CodeMirror } from './CodeMirror'; 3 | import './App.css'; 4 | import { Plot, PlotLine } from './Plot'; 5 | 6 | function resultToPlotLines(result: any): PlotLine[] { 7 | if (!result) { 8 | return []; 9 | } 10 | if (Array.isArray(result)) { 11 | for (let i=0; i < result.length; i++) { 12 | if (typeof result[i] !== 'number') { 13 | return []; 14 | } 15 | } 16 | return [{ data: result, label: 'Data' }]; 17 | } else if (typeof result === 'object') { 18 | let res: PlotLine[] = []; 19 | for (const key of Object.keys(result)) { 20 | res = [...res, ...resultToPlotLines(result[key]).map(x => ({...x, label: key }))]; 21 | } 22 | return res; 23 | } else { 24 | return []; 25 | } 26 | } 27 | 28 | function App() { 29 | const [data, setData] = React.useState([{ data: [3, 1, 2], label: 'Data' }]); 30 | const [source, setSource] = React.useState(`return [3, 1, 2];`); 31 | const [error, setError] = React.useState(''); 32 | return ( 33 |
34 |
35 | { 38 | setSource(newSource); 39 | let result; 40 | try { 41 | result = Function(newSource)(); 42 | } catch (ex) { 43 | setError(ex.message); 44 | return; 45 | } 46 | setError(''); 47 | setData(resultToPlotLines(result)); 48 | }} 49 | options={{ 50 | theme: 'one-dark', 51 | mode: 'javascript', 52 | lineNumbers: true 53 | }} 54 | /> 55 |
56 |
57 | 58 |
{error}
59 |
60 |
61 | jsplot by @jfnoren. Code on GitHub. Find it useful? Become a Patron! 62 |
63 |
64 | ); 65 | } 66 | 67 | export default App; 68 | -------------------------------------------------------------------------------- /src/CodeMirror.tsx: -------------------------------------------------------------------------------- 1 | // Tried https://github.com/JedWatson/react-codemirror first, but because of numerous small issues, 2 | // such as https://github.com/JedWatson/react-codemirror/issues/110 and 3 | // https://github.com/JedWatson/react-codemirror/issues/47 which is the root cause, which hasn't been 4 | // addressed in a long time, it was easier to just create this component. 5 | import * as React from 'react'; 6 | import CodeMirrorInstance from 'codemirror'; 7 | import "codemirror/lib/codemirror.css"; 8 | import 'codemirror-one-dark-theme/one-dark.css'; 9 | require('codemirror/mode/javascript/javascript'); 10 | 11 | export interface CodeMirrorProps { 12 | options?: CodeMirrorInstance.EditorConfiguration; 13 | value?: string; 14 | onChange?: (newValue: string) => void; 15 | onKeyDown?: (event: KeyboardEvent) => void; 16 | className?: string; 17 | } 18 | 19 | export class CodeMirror extends React.Component { 20 | componentDidMount() { 21 | if (!this.container) { 22 | return; 23 | } 24 | const cm = CodeMirrorInstance(this.container, { value: this.props.value || '', ...this.props.options }); 25 | cm.on('change', this.handleChange); 26 | cm.on('keydown', this.handleKeyDown as any); 27 | this.codeMirror = cm; 28 | } 29 | componentWillReceiveProps(nextProps: CodeMirrorProps) { 30 | const val = nextProps.value || ''; 31 | if (this.codeMirror && this.codeMirror.getValue() !== val) { 32 | this.codeMirror.setValue(val); 33 | } 34 | } 35 | handleChange = (cm: CodeMirrorInstance.Editor) => { 36 | if (this.props.onChange) { 37 | this.props.onChange(cm.getValue()); 38 | } 39 | } 40 | handleKeyDown = (cm: CodeMirrorInstance.Editor, event: KeyboardEvent) => { 41 | if (this.props.onKeyDown) { 42 | this.props.onKeyDown(event); 43 | } 44 | } 45 | container: HTMLDivElement | null = null; 46 | codeMirror: CodeMirrorInstance.Editor | undefined; 47 | shouldComponentUpdate(nextProps: CodeMirrorProps) { 48 | return nextProps.className !== this.props.className; 49 | } 50 | render() { 51 | return
this.container = e} />; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Plot/index.css: -------------------------------------------------------------------------------- 1 | .Plot { 2 | display: flex; 3 | flex-direction: column; 4 | align-items: flex-start; 5 | margin: 10px; 6 | } 7 | .Plots { 8 | display: flex; 9 | flex-direction: row; 10 | flex-wrap: wrap; 11 | } 12 | .PlotZoomOut { 13 | position: absolute; 14 | left: 50%; 15 | top: 50%; 16 | cursor: pointer; 17 | opacity: 0.3; 18 | padding: 5px; 19 | transform: translate(-50%, -50%); 20 | } 21 | .PlotZoomOut:hover { 22 | background: rgba(255, 255, 255, 0.1); 23 | } 24 | .PlotLegendItem { 25 | cursor: pointer; 26 | user-select: none; 27 | } 28 | .PlotCanvases { 29 | position: relative; 30 | } 31 | .PlotUICanvas { 32 | position: absolute; 33 | top: 0px; 34 | left: 0px; 35 | } -------------------------------------------------------------------------------- /src/Plot/index.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import './index.css'; 3 | import lodash from 'lodash'; 4 | import { stringToHSL, arrayReplaceIndex, clamp, interpolate } from '../Util'; 5 | 6 | type PlotWindow = [number, number]; 7 | export interface PlotLine { 8 | data: number[]; 9 | label: string; 10 | color?: string; 11 | yMin?: number; 12 | yMax?: number; 13 | } 14 | function windowedData(data: number[], window: PlotWindow | undefined) { 15 | if (window) { 16 | const start = Math.floor(window[0] * data.length); 17 | const end = Math.ceil(window[1] * data.length); 18 | return { data: data.slice(start, end), start, end }; 19 | } { 20 | return { data, start: 0, end: data.length }; 21 | } 22 | } 23 | function drawPlotLine(canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D, line: PlotLine, window: PlotWindow | undefined) { 24 | let data = windowedData(line.data, window).data; 25 | if (data.length === 0) { 26 | return; 27 | } 28 | const dataMin = line.yMin ?? data.reduce((p, x) => Math.min(p, x)); 29 | const dataMax = line.yMax ?? data.reduce((p, x) => Math.max(p, x)); 30 | const dataRange = dataMax - dataMin; 31 | const canvasCoord = (i: number, value: number): [number, number] => { 32 | const x = canvas.width * i / (data.length - 1); 33 | const y = canvas.height - canvas.height * (value - dataMin) / dataRange; 34 | return [x, y]; 35 | } 36 | ctx.beginPath(); 37 | ctx.moveTo(...canvasCoord(0, data[0])); 38 | ctx.strokeStyle = line.color ?? stringToHSL(line.label, 0.5, 0.5); 39 | for (let i=1; i < data.length; i++) { 40 | ctx.lineTo(...canvasCoord(i, data[i])); 41 | } 42 | ctx.stroke(); 43 | } 44 | 45 | export interface PlotProps { 46 | title?: string; 47 | lines: PlotLine[]; 48 | } 49 | export function Plot({ lines, title }: PlotProps) { 50 | const dataCanvas = React.createRef(); 51 | const uiCanvas = React.createRef(); 52 | const [windowStack, setWindowStack] = React.useState([]); 53 | const [hidden, setHidden] = React.useState([]); 54 | const [hover, setHover] = React.useState(); 55 | const setHoverThrottled = React.useCallback(lodash.throttle(setHover, 16), [setHover]); 56 | const [windowPreview, setWindowPreview] = React.useState(); 57 | React.useEffect(() => { 58 | if (dataCanvas.current) { 59 | const ctx = dataCanvas.current.getContext('2d')!; 60 | ctx.clearRect(0, 0, dataCanvas.current.width, dataCanvas.current.height); 61 | for (let i=0; i < lines.length; i++) { 62 | if (hidden[i] !== true) { 63 | drawPlotLine(dataCanvas.current, ctx, lines[i], lodash.last(windowStack)); 64 | } 65 | } 66 | } 67 | }, [lines, windowStack, hidden]); 68 | React.useEffect(() => { 69 | if (uiCanvas.current) { 70 | const ctx = uiCanvas.current.getContext('2d')!; 71 | ctx.clearRect(0, 0, uiCanvas.current.width, uiCanvas.current.height); 72 | if (hover !== undefined) { 73 | ctx.beginPath(); 74 | ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)'; 75 | ctx.moveTo(hover * uiCanvas.current.width, 0); 76 | ctx.lineTo(hover * uiCanvas.current.width, uiCanvas.current.height); 77 | ctx.stroke(); 78 | } 79 | if (windowPreview) { 80 | ctx.fillStyle = `rgba(255, 255, 255, 0.1)`; 81 | ctx.fillRect(windowPreview[0] * uiCanvas.current.width, 0, 82 | (windowPreview[1] - windowPreview[0]) * uiCanvas.current.width, uiCanvas.current.height); 83 | } 84 | } 85 | }, [hover, windowPreview]); 86 | const canvasSize = { width: 600, height: 250 }; 87 | return
88 | {title && {title}} 89 |
90 | 91 | { 97 | const c = e.target as HTMLCanvasElement; 98 | const b = c.getBoundingClientRect(); 99 | setHoverThrottled((e.clientX - b.left) / b.width); 100 | }} 101 | onMouseOut={e => setHoverThrottled(undefined)} 102 | onMouseDown={e => { 103 | const c = e.target as HTMLCanvasElement; 104 | const b = c.getBoundingClientRect(); 105 | const windowStart = (e.clientX - b.left) / b.width; 106 | setWindowPreview([windowStart, windowStart]); 107 | const getWindow = (e: MouseEvent): PlotWindow => { 108 | const windowEnd = clamp((e.clientX - b.left) / b.width, 0, 1); 109 | if (windowEnd < windowStart) { 110 | return [windowEnd, windowStart]; 111 | } else { 112 | return [windowStart, windowEnd]; 113 | } 114 | } 115 | const handleMouseMove = (e: MouseEvent) => { 116 | e.preventDefault(); 117 | e.stopPropagation(); 118 | setWindowPreview(getWindow(e)); 119 | } 120 | const handleMouseUp = (e: MouseEvent) => { 121 | let window = getWindow(e); 122 | const lastWindow = lodash.last(windowStack); 123 | if (lastWindow) { 124 | setWindowStack([...windowStack, [ 125 | interpolate(window[0], 0, 1, lastWindow[0], lastWindow[1]), 126 | interpolate(window[1], 0, 1, lastWindow[0], lastWindow[1]) 127 | ]]); 128 | } else { 129 | setWindowStack([window]); 130 | } 131 | setWindowPreview(undefined); 132 | document.removeEventListener('mouseup', handleMouseUp); 133 | document.removeEventListener('mousemove', handleMouseMove); 134 | } 135 | document.addEventListener('mouseup', handleMouseUp); 136 | document.addEventListener('mousemove', handleMouseMove); 137 | }} 138 | /> 139 | {windowStack.length > 0 &&
setWindowStack(windowStack.slice(0, windowStack.length - 1))}> 141 | Zoom out 142 |
} 143 |
144 | {lines.map((line, i) => { 145 | const data = windowedData(line.data, lodash.last(windowStack)); 146 | return
setHidden(arrayReplaceIndex(hidden, i, !hidden[i]))} 154 | > 155 | {line.label} 156 |  {hover !== undefined ? 157 | {Math.round(hover * data.data.length)}: {data.data[Math.round(hover * data.data.length)]} 158 | : [{data.start}:{data.data[0]}, ..., {data.end - 1}:{lodash.last(data.data)}]} 159 |
160 | })} 161 |
162 | } 163 | -------------------------------------------------------------------------------- /src/Util.ts: -------------------------------------------------------------------------------- 1 | 2 | // From: https://gist.github.com/hyamamoto/fd435505d29ebfa3d9716fd2be8d42f0 3 | export function hashCode(s: string): number { 4 | let h = 0; 5 | for(let i = 0; i < s.length; i++) { 6 | // tslint:disable-next-line:no-bitwise 7 | h = Math.imul(31, h) + s.charCodeAt(i) | 0; 8 | } 9 | 10 | return h; 11 | } 12 | 13 | export function stringToHSL(string: string, saturation: number, light: number) { 14 | return `hsl(${hashCode(string) % 360}, ${100*saturation}%, ${100*light}%)`; 15 | } 16 | 17 | export function arrayReplaceIndex(array: T[], index: number, value: T): T[] { 18 | const a2 = [...array]; 19 | a2[index] = value; 20 | return a2; 21 | } 22 | export function arrayInsertIndex(array: T[], index: number, value: T): T[] { 23 | return [...array.slice(0, index), value, ...array.slice(index)]; 24 | } 25 | export function arrayRemoveIndex(array: T[], index: number): T[] { 26 | return [...array.slice(0, index), ...array.slice(index + 1)]; 27 | } 28 | export function arrayMove(array: T[], fromIndex: number, toIndex: number): T[] { 29 | const arr = array.slice(); 30 | const [el] = arr.splice(fromIndex, 1); 31 | arr.splice(Math.max(toIndex, 0), 0, el); 32 | return arr; 33 | } 34 | 35 | export function clamp(value: number, min: number, max: number): number { 36 | return Math.min(Math.max(value, min), max); 37 | } 38 | export function mix(a: number, b: number, p: number) { 39 | return a * (1 - p) + b * p; 40 | } 41 | export function interpolate(x: number, x0: number, x1: number, y0: number, y1: number): number { 42 | const p = (x - x0) / (x1 - x0); 43 | return y0 + p * (y1 - y0); 44 | } 45 | export function interpolateClamped(x: number, x0: number, x1: number, y0: number, y1: number): number { 46 | const p = clamp((x - x0) / (x1 - x0), 0, 1); 47 | return y0 + p * (y1 - y0); 48 | } -------------------------------------------------------------------------------- /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 | background: #282c34; 9 | } 10 | 11 | code { 12 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', 13 | monospace; 14 | } 15 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 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( 8 | 9 | 10 | , 11 | document.getElementById('root') 12 | ); 13 | 14 | // If you want your app to work offline and load faster, you can change 15 | // unregister() to register() below. Note this comes with some pitfalls. 16 | // Learn more about service workers: https://bit.ly/CRA-PWA 17 | serviceWorker.unregister(); 18 | -------------------------------------------------------------------------------- /src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /src/serviceWorker.ts: -------------------------------------------------------------------------------- 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.0/8 are 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 | type Config = { 24 | onSuccess?: (registration: ServiceWorkerRegistration) => void; 25 | onUpdate?: (registration: ServiceWorkerRegistration) => void; 26 | }; 27 | 28 | export function register(config?: Config) { 29 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 30 | // The URL constructor is available in all browsers that support SW. 31 | const publicUrl = new URL( 32 | process.env.PUBLIC_URL, 33 | window.location.href 34 | ); 35 | if (publicUrl.origin !== window.location.origin) { 36 | // Our service worker won't work if PUBLIC_URL is on a different origin 37 | // from what our page is served on. This might happen if a CDN is used to 38 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 39 | return; 40 | } 41 | 42 | window.addEventListener('load', () => { 43 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 44 | 45 | if (isLocalhost) { 46 | // This is running on localhost. Let's check if a service worker still exists or not. 47 | checkValidServiceWorker(swUrl, config); 48 | 49 | // Add some additional logging to localhost, pointing developers to the 50 | // service worker/PWA documentation. 51 | navigator.serviceWorker.ready.then(() => { 52 | console.log( 53 | 'This web app is being served cache-first by a service ' + 54 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 55 | ); 56 | }); 57 | } else { 58 | // Is not localhost. Just register service worker 59 | registerValidSW(swUrl, config); 60 | } 61 | }); 62 | } 63 | } 64 | 65 | function registerValidSW(swUrl: string, config?: Config) { 66 | navigator.serviceWorker 67 | .register(swUrl) 68 | .then(registration => { 69 | registration.onupdatefound = () => { 70 | const installingWorker = registration.installing; 71 | if (installingWorker == null) { 72 | return; 73 | } 74 | installingWorker.onstatechange = () => { 75 | if (installingWorker.state === 'installed') { 76 | if (navigator.serviceWorker.controller) { 77 | // At this point, the updated precached content has been fetched, 78 | // but the previous service worker will still serve the older 79 | // content until all client tabs are closed. 80 | console.log( 81 | 'New content is available and will be used when all ' + 82 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 83 | ); 84 | 85 | // Execute callback 86 | if (config && config.onUpdate) { 87 | config.onUpdate(registration); 88 | } 89 | } else { 90 | // At this point, everything has been precached. 91 | // It's the perfect time to display a 92 | // "Content is cached for offline use." message. 93 | console.log('Content is cached for offline use.'); 94 | 95 | // Execute callback 96 | if (config && config.onSuccess) { 97 | config.onSuccess(registration); 98 | } 99 | } 100 | } 101 | }; 102 | }; 103 | }) 104 | .catch(error => { 105 | console.error('Error during service worker registration:', error); 106 | }); 107 | } 108 | 109 | function checkValidServiceWorker(swUrl: string, config?: Config) { 110 | // Check if the service worker can be found. If it can't reload the page. 111 | fetch(swUrl, { 112 | headers: { 'Service-Worker': 'script' } 113 | }) 114 | .then(response => { 115 | // Ensure service worker exists, and that we really are getting a JS file. 116 | const contentType = response.headers.get('content-type'); 117 | if ( 118 | response.status === 404 || 119 | (contentType != null && contentType.indexOf('javascript') === -1) 120 | ) { 121 | // No service worker found. Probably a different app. Reload the page. 122 | navigator.serviceWorker.ready.then(registration => { 123 | registration.unregister().then(() => { 124 | window.location.reload(); 125 | }); 126 | }); 127 | } else { 128 | // Service worker found. Proceed as normal. 129 | registerValidSW(swUrl, config); 130 | } 131 | }) 132 | .catch(() => { 133 | console.log( 134 | 'No internet connection found. App is running in offline mode.' 135 | ); 136 | }); 137 | } 138 | 139 | export function unregister() { 140 | if ('serviceWorker' in navigator) { 141 | navigator.serviceWorker.ready 142 | .then(registration => { 143 | registration.unregister(); 144 | }) 145 | .catch(error => { 146 | console.error(error.message); 147 | }); 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/setupTests.ts: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom/extend-expect'; 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "module": "esnext", 16 | "moduleResolution": "node", 17 | "resolveJsonModule": true, 18 | "isolatedModules": true, 19 | "noEmit": true, 20 | "jsx": "react" 21 | }, 22 | "include": [ 23 | "src" 24 | ] 25 | } 26 | --------------------------------------------------------------------------------