├── .gitignore
├── .travis.yml
├── LICENSE.md
├── README.md
├── images
└── banner.png
├── package-lock.json
├── package.json
├── public
├── favicon.ico
├── index.html
└── manifest.json
└── src
├── App.css
├── App.js
├── components
├── header.js
├── header.test.js
├── profileTextbox.js
├── statsSingle.js
├── statsTable.js
└── statsTable.test.js
├── graphqlQueries.js
├── img
└── svg-banner.svg
├── index.css
├── index.js
├── processData.js
├── redux
├── actions
│ ├── CardsActions.js
│ └── index.js
├── reducers
│ ├── CardsReducer.js
│ └── index.js
└── store.js
├── serviceWorker.js
└── setupTests.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*
17 | npm-debug.log*
18 | yarn-debug.log*
19 | yarn-error.log*
20 | .vscode
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - "stable"
4 | cache:
5 | directories:
6 | - node_modules
7 | script:
8 | - npm test
9 | - npm run build
10 |
11 | deploy:
12 | provider: pages
13 | skip_cleanup: true
14 | github_token: $github_token
15 | local_dir: build
16 | on:
17 | branch: master
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 Darsh Patel
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
18 |
19 |
20 |
21 |
22 |
23 | A single page webapp built using [React](https://reactjs.org/) and [Ant Design](https://ant.design/). Uses the github's GraphQL API to fetch user information and generate a score.
24 |
25 | ### Frameworks
26 |
27 | * React
28 | * Apollo GraphQL Client
29 | * React Redux
30 | * Ant Design Components
31 |
32 | ### Run Locally
33 |
34 | ```
35 | git clone https://github.com/darshkpatel/RateMyGit
36 | cd RateMyGit
37 | npm install
38 | echo "REACT_APP_GITHUB_TOKEN=[YOUR GITHUB TOKEN]"> .env
39 | npm run
40 | ```
41 |
42 | ### To Do
43 |
44 | * Write Proper Tests
45 | * UI Fixes
46 | * Buttons to share score on social media
47 | * Show more stats such as most used language
48 |
49 | ### Contributing
50 |
51 | Feel free to open an issue or send a PR for a new feature
52 |
53 | ### License
54 |
55 | [MIT](https://github.com/darshkpatel/RateMyGit/blob/master/LICENSE.md) Copyright (c) 2022 Darsh Patel
56 |
57 |
58 |
--------------------------------------------------------------------------------
/images/banner.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darshkpatel/RateMyGit/9c5f189c5e1f3bfb2e2871d22bbbd6f799e50081/images/banner.png
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "RateMyGit",
3 | "version": "0.1.0",
4 | "private": true,
5 | "homepage": "https://darshkpatel.github.io/RateMyGit/",
6 | "dependencies": {
7 | "antd": "^3.19.3",
8 | "apollo-boost": "^0.4.0",
9 | "enzyme": "^3.10.0",
10 | "enzyme-adapter-react-16": "^1.14.0",
11 | "graphql": "^14.3.1",
12 | "graphql-tag": "^2.10.1",
13 | "react": "^16.8.6",
14 | "react-apollo": "^2.5.6",
15 | "react-bootstrap": "^1.0.0-beta.8",
16 | "react-dom": "^16.8.6",
17 | "react-redux": "^7.1.0",
18 | "react-scripts": "3.0.1",
19 | "react-tap-event-plugin": "^3.0.3",
20 | "redux": "^4.0.1",
21 | "redux-thunk": "^2.3.0"
22 | },
23 | "scripts": {
24 | "start": "react-scripts start",
25 | "build": "react-scripts build",
26 | "test": "react-scripts test",
27 | "eject": "react-scripts eject"
28 | },
29 | "eslintConfig": {
30 | "extends": "react-app"
31 | },
32 | "browserslist": {
33 | "production": [
34 | ">0.2%",
35 | "not dead",
36 | "not op_mini all"
37 | ],
38 | "development": [
39 | "last 1 chrome version",
40 | "last 1 firefox version",
41 | "last 1 safari version"
42 | ]
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/darshkpatel/RateMyGit/9c5f189c5e1f3bfb2e2871d22bbbd6f799e50081/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | RateMyGit
9 |
10 |
11 | You need to enable JavaScript to run this app.
12 |
13 |
14 |
15 |
18 |
19 |
--------------------------------------------------------------------------------
/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 | "start_url": ".",
12 | "display": "standalone",
13 | "theme_color": "#000000",
14 | "background_color": "#ffffff"
15 | }
16 |
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | @import '~antd/dist/antd.css';
2 | .fullHeight
3 | {
4 | height: 100%;
5 | }
6 |
7 | .bodyStyles{
8 | max-width: 100% !important;
9 | overflow-x: hidden !important;
10 | }
11 |
12 | .headerStyle{
13 | padding: 10px;
14 | background: black;
15 | display: flex;
16 | flex-flow: column;
17 | align-items: center;
18 | }
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import './App.css';
3 | import Header from './components/header'
4 | import ProfileTextbox from './components/profileTextbox'
5 | import { ApolloProvider } from "react-apollo";
6 | import ApolloClient from "apollo-boost";
7 | const github_token = process.env.REACT_APP_GITHUB_TOKEN
8 | function App() {
9 | const client = new ApolloClient({
10 | uri: "https://api.github.com/graphql",
11 | request: operation => {
12 | operation.setContext({
13 | headers: {
14 | authorization: `Bearer ${github_token}`
15 | },
16 | });
17 | }
18 | });
19 |
20 | return (
21 |
22 |
23 |
24 |
25 | );
26 | }
27 |
28 | export default App;
29 |
--------------------------------------------------------------------------------
/src/components/header.js:
--------------------------------------------------------------------------------
1 | import React,{Component} from 'react';
2 | import '../App.css';
3 | import { ReactComponent as Logo } from'../img/svg-banner.svg'
4 |
5 | class Header extends Component{
6 | render(){
7 | return(
8 |
9 |
10 |
11 | );
12 | }
13 | }
14 |
15 | export default Header;
16 |
--------------------------------------------------------------------------------
/src/components/header.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import Header from './header'
3 | import ReactDOM from 'react-dom';
4 | import { shallow } from 'enzyme';
5 |
6 | it('renders without crashing', () => {
7 | const div = document.createElement('div');
8 | ReactDOM.render(, div);
9 | ReactDOM.unmountComponentAtNode(div);
10 | });
11 |
--------------------------------------------------------------------------------
/src/components/profileTextbox.js:
--------------------------------------------------------------------------------
1 | import React, {Component} from 'react';
2 | import StatsSingle from './statsSingle';
3 | import { Input,Button } from "antd";
4 | import { Row, Col, message, notification } from 'antd';
5 | import {connect} from 'react-redux';
6 | import {addCard} from '../redux/actions/index'
7 | class ProfileTextbox extends Component {
8 | constructor(props){
9 | super(props);
10 | this.onSubmit = this.onSubmit.bind(this);
11 | }
12 |
13 |
14 | onSubmit = input_text => {
15 | const usernameRegex = /^([a-z\d]+-)*[a-z\d]+$/ig; //Regex for valid github username
16 |
17 | //Check if github username is valid
18 | if(usernameRegex.test(input_text)){
19 |
20 | //Pushes Stats Component to display if user isn't already displayed
21 | if(!this.props.cards.some((obj)=>obj.username===input_text)){
22 | let newCard =
23 | this.props.addCard(newCard,input_text)
24 | }
25 |
26 | //Show notification to search another username if it's the first search
27 | if(this.props.cards.length===0){
28 | notification.info({
29 | message: 'Search for another username to compare scores',
30 | });
31 | }
32 |
33 | }
34 |
35 | else{ // If Username is invalid
36 | message.warning(`${input_text} is not a valid github username` );
37 | }
38 |
39 | };
40 |
41 | render() {
42 |
43 | return (
44 |
45 |
46 |
47 |
48 |
51 | Search
52 | }
53 | size="large"
54 | onSearch={value => this.onSubmit(value)}
55 | />
56 |
57 |
58 |
59 |
60 |
61 | {/* Returns an array of JSX objects to display */}
62 | {this.props.cards.reduce((acc,obj)=>[...acc,obj.card],[])}
63 |
64 |
65 |
66 |
67 | );
68 | }
69 | }
70 | const mapStateToProps = state => ({
71 | cards: state.CardsReducer.cards
72 | });
73 |
74 | export default connect(mapStateToProps, {addCard})(ProfileTextbox);
--------------------------------------------------------------------------------
/src/components/statsSingle.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { Query } from "react-apollo";
3 | import { statsQuery } from "../graphqlQueries"
4 | import { collectStats } from "../processData"
5 | import StatsTable from './statsTable'
6 | import {Card, Statistic, Button,Row,Col, notification}from "antd";
7 | import {connect} from 'react-redux';
8 | import {deleteCard} from '../redux/actions/index'
9 | class StatsSingle extends Component {
10 |
11 | render() {
12 | //Sanity check
13 | if (typeof (this.props.username) != "undefined") {
14 |
15 | return (
16 | //Graphql Query for User Stats
17 |
18 | {({ loading, error, data, fetchMore }) => {
19 | if (loading) {
20 | return(
21 |
22 | )
23 | } // Loader
24 | if (error) {
25 | console.log(JSON.stringify(error));
26 | this.props.cards[this.props.cards.findIndex((obj)=>obj.username===this.props.username)].error=true
27 | console.log(this.props.cards[this.props.cards.findIndex((obj)=>obj.username===this.props.username)], "Error Set True")
28 | return(
29 |
30 | Please check if {this.props.username} is a valid github username
31 |
32 | {this.props.deleteCard(this.props.username)}}>
33 | Remove
34 |
35 |
36 | )
37 | } //Display Error
38 | else {
39 | const stats = collectStats(data)// Collect stats form all repos to a dictionary
40 | return (
41 | // Stats Card
42 |
43 | }>
46 |
47 |
48 |
49 |
50 | {this.props.deleteCard(this.props.username)}}>
51 | Remove
52 |
53 |
54 |
55 | {notification.info({message: 'Detailed Profile Statistics Coming Soon'});}}>
56 | Show Stats
57 |
58 |
59 |
60 |
61 | )
62 | }
63 | }
64 | }
65 |
66 | )
67 | }
68 | // If no username is provided in props return null
69 | else {
70 | return null
71 | }
72 |
73 | }
74 |
75 |
76 | }
77 | const mapStateToProps = state => ({
78 | cards: state.CardsReducer.cards
79 | });
80 |
81 | export default connect(mapStateToProps, {deleteCard})(StatsSingle);
--------------------------------------------------------------------------------
/src/components/statsTable.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import {Table} from "antd";
3 |
4 | class StatsTable extends Component {
5 | constructor(props){
6 |
7 | super(props);
8 |
9 | //Data for table
10 | const columns = [
11 | {
12 | title: 'Metric',
13 | dataIndex: 'metric',
14 | },
15 | {
16 | title: 'Value',
17 | dataIndex: 'value',
18 | },
19 | ];
20 |
21 | const data = [
22 | {
23 | key: '1',
24 | metric: 'Followers',
25 | value:props.stats['followers']
26 | },
27 | {
28 | key: '2',
29 | metric: 'Public Repositories',
30 | value:props.stats['total_repos']
31 | },
32 | {
33 | key: '3',
34 | metric: 'Total Forks on repositories',
35 | value:props.stats['forks']
36 | },
37 | {
38 | key: '4',
39 | metric: 'Total Stars on repositories',
40 | value:props.stats['stars']
41 | },
42 | {
43 | key: '5',
44 | metric: 'Total Pull Requests on repositories',
45 | value:props.stats['prs']
46 | },
47 | {
48 | key: '6',
49 | metric: 'Total watchers of repositories',
50 | value:props.stats['watchers']
51 | },
52 | {
53 | key: '7',
54 | metric: 'Contributions in the last year',
55 | value:props.stats['contributions']
56 | },
57 |
58 | ];
59 |
60 | this.state={columns:columns,data:data}
61 | }
62 |
63 | render(){
64 | return(
65 |
66 | )
67 | }
68 | }
69 |
70 |
71 |
72 | export default StatsTable
--------------------------------------------------------------------------------
/src/components/statsTable.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import StatsTable from './statsTable'
3 | import { shallow } from 'enzyme';
4 |
5 | it('renders without crashing', () => {
6 | let stats = {"followers":0,"name":"","login":"","total_repos":0,"forks":0,"stars":0,"prs":0,"watchers":0}
7 | shallow();
8 | });
--------------------------------------------------------------------------------
/src/graphqlQueries.js:
--------------------------------------------------------------------------------
1 |
2 | import { gql } from "apollo-boost";
3 |
4 | export const datesQuery = (username) => gql`{
5 | user(login: ${username}) {
6 | createdAt,
7 | contributionsCollection{
8 | startedAt,
9 | endedAt,
10 | contributionYears,
11 | }
12 | }
13 | }
14 | `
15 |
16 | export const contributionsQuery = (username,from,to) => gql`
17 | {
18 | user(login: ${username}) {
19 | contributionsCollection(from: ${from}, to: ${to}) {
20 | totalCommitContributions,
21 | totalIssueContributions,
22 | totalPullRequestContributions,
23 | totalPullRequestReviewContributions,
24 | totalRepositoriesWithContributedPullRequests,
25 | totalRepositoriesWithContributedCommits,
26 | hasAnyContributions,
27 | hasActivityInThePast,
28 | }
29 | }
30 | }
31 |
32 | `
33 |
34 | export const statsQuery = gql`
35 | query User($username: String!) {
36 | user(login: $username) {
37 | name,
38 | url,
39 | login,
40 | createdAt,
41 | followers{totalCount},
42 |
43 | contributionsCollection{
44 | hasAnyContributions,
45 | contributionCalendar{totalContributions}
46 | }
47 |
48 | repositories(first:100 ){
49 | totalCount,
50 | edges{
51 | node{
52 | forkCount,
53 | nameWithOwner,
54 | watchers{totalCount},
55 | pullRequests{totalCount},
56 | stargazers{totalCount},
57 | }
58 | }
59 | }
60 | }
61 |
62 | rateLimit {
63 | limit
64 | cost
65 | remaining
66 | resetAt
67 | }
68 | }
69 | `
70 |
--------------------------------------------------------------------------------
/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-color: #0000000a !important;
9 | }
10 |
11 | code {
12 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
13 | monospace;
14 | }
15 |
--------------------------------------------------------------------------------
/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 | import { Provider } from 'react-redux'
7 | import store from './redux/store'
8 | ReactDOM.render( , document.getElementById('root'));
9 |
10 | // If you want your app to work offline and load faster, you can change
11 | // unregister() to register() below. Note this comes with some pitfalls.
12 | // Learn more about service workers: https://bit.ly/CRA-PWA
13 | serviceWorker.unregister();
14 |
--------------------------------------------------------------------------------
/src/processData.js:
--------------------------------------------------------------------------------
1 |
2 | export function collectStats(data) {
3 | var processed_obj = {}
4 | processed_obj['followers'] = data.user.followers.totalCount
5 | processed_obj['name'] = data.user.name
6 | processed_obj['login'] = data.user.login
7 | processed_obj['contributions'] = data.user.contributionsCollection.contributionCalendar.totalContributions
8 | processed_obj['total_repos'] = data.user.repositories.totalCount
9 | processed_obj = {...processed_obj, ...data.user.repositories.edges.reduce((acc, obj) => {
10 | return {
11 | "forks": acc.forks + obj.node.forkCount,
12 | "stars": acc.stars + obj.node.stargazers.totalCount,
13 | "prs": acc.prs + obj.node.pullRequests.totalCount,
14 | "watchers": acc.watchers + obj.node.watchers.totalCount
15 | }
16 | }, { "forks": 0, "stars": 0, "prs": 0, "watchers": 0 })
17 | }
18 |
19 | processed_obj['score'] = Object.values(processed_obj).reduce((sum,val)=>sum+(isNaN(val)?0:val))
20 | console.log(`Stats for user ${data.user.login}`, processed_obj)
21 | return processed_obj
22 | }
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/src/redux/actions/CardsActions.js:
--------------------------------------------------------------------------------
1 |
2 | export const addCard = (card, username, error=false) => (dispatch) => {
3 | dispatch({
4 | type:"SAVE_CARD",
5 | payload:{card,username,error}
6 | });
7 | }
8 |
9 | export const deleteCard = (username) => (dispatch) => {
10 | dispatch({
11 | type:"DELETE_CARD",
12 | payload:{username}
13 | });
14 | }
--------------------------------------------------------------------------------
/src/redux/actions/index.js:
--------------------------------------------------------------------------------
1 | export * from './CardsActions'
--------------------------------------------------------------------------------
/src/redux/reducers/CardsReducer.js:
--------------------------------------------------------------------------------
1 | const initial_state ={
2 | cards:[]
3 | }
4 |
5 | export default (state = initial_state,action) => {
6 | switch (action.type) {
7 | case 'SAVE_CARD':
8 | return {cards:[...state.cards, action.payload]}
9 | case 'DELETE_CARD':
10 | return {cards:state.cards.filter((obj)=>obj.username!==action.payload.username)}
11 | default:
12 | return state
13 | }
14 | }
--------------------------------------------------------------------------------
/src/redux/reducers/index.js:
--------------------------------------------------------------------------------
1 | import { combineReducers } from 'redux';
2 | import CardsReducer from './CardsReducer'
3 |
4 | export default combineReducers({
5 | CardsReducer
6 | })
--------------------------------------------------------------------------------
/src/redux/store.js:
--------------------------------------------------------------------------------
1 | import reducer from './reducers/index';
2 | import { createStore, applyMiddleware } from 'redux';
3 | import reduxThunk from 'redux-thunk';
4 | const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
5 | const store = createStoreWithMiddleware(reducer);
6 |
7 | export default store
8 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/src/setupTests.js:
--------------------------------------------------------------------------------
1 | import { configure } from 'enzyme';
2 | import Adapter from 'enzyme-adapter-react-16';
3 |
4 | configure({ adapter: new Adapter() });
--------------------------------------------------------------------------------