Public repository commit for project.

master
Joshua Sigona 5 years ago
commit 9c87eaa2d4
  1. 68
      README.md
  2. 13880
      package-lock.json
  3. 34
      package.json
  4. BIN
      public/favicon.ico
  5. 44
      public/index.html
  6. BIN
      public/logo192.png
  7. BIN
      public/logo512.png
  8. 25
      public/manifest.json
  9. 3
      public/robots.txt
  10. 78
      src/App.css
  11. 375
      src/App.js
  12. 9
      src/App.test.js
  13. 49
      src/GroceryList.js
  14. 68
      src/Home.js
  15. 22
      src/PokemonAppContext.js
  16. 70
      src/PokemonBattle/Battle.js
  17. 30
      src/PokemonCollection/PokemonCollection.js
  18. 56
      src/PokemonData.js
  19. 40
      src/PokemonDetails.js
  20. 36
      src/PokemonSearch/PokemonSearch.js
  21. 60
      src/PokemonSearch/PokemonSearchPage.js
  22. 260
      src/PokemonSearch/PokemonSearchResults.js
  23. 44
      src/PokemonTypes/SimilarTypesPage.js
  24. BIN
      src/images/type_0_0.gif
  25. BIN
      src/images/type_0_1.gif
  26. BIN
      src/images/type_0_2.gif
  27. BIN
      src/images/type_1_0.gif
  28. BIN
      src/images/type_1_1.gif
  29. BIN
      src/images/type_1_2.gif
  30. BIN
      src/images/type_2_0.gif
  31. BIN
      src/images/type_2_1.gif
  32. BIN
      src/images/type_2_2.gif
  33. BIN
      src/images/type_3_0.gif
  34. BIN
      src/images/type_3_1.gif
  35. BIN
      src/images/type_3_2.gif
  36. BIN
      src/images/type_4_0.gif
  37. BIN
      src/images/type_4_1.gif
  38. BIN
      src/images/type_4_2.gif
  39. BIN
      src/images/type_5_0.gif
  40. BIN
      src/images/type_5_1.gif
  41. BIN
      src/images/type_5_2.gif
  42. 13
      src/index.css
  43. 17
      src/index.js
  44. 7
      src/logo.svg
  45. 141
      src/serviceWorker.js
  46. 5
      src/setupTests.js

@ -0,0 +1,68 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
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.
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.
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.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `yarn build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

13880
package-lock.json generated

File diff suppressed because it is too large Load Diff

@ -0,0 +1,34 @@
{
"name": "reactemon",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"/>
<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>Reactemon!</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>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

@ -0,0 +1,25 @@
{
"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"
}

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

@ -0,0 +1,78 @@
body{
background-color:#343a40;
}
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
.navigation{
display:inline-flex;
}
.navigation nav{
margin:4px;
}
.smallForm{
width:60px;
}
.flipped{
-webkit-transform: scaleX(-1);
transform: scaleX(-1);
}
.fit-image{
width:100%;
}
.type-small{
width:72px;
}
.link{
cursor:pointer;
}
.link:hover{
background-color:#333333;
border: 1px white solid;
}
.centered{
margin:auto;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

@ -0,0 +1,375 @@
import React, { useContext } from 'react';
import './App.css';
import {PokemonData} from './PokemonAppContext';
import GroceryList from './GroceryList';
import PokemonDetails from './PokemonDetails.js'
import PokemonSearchPage from './PokemonSearch/PokemonSearchPage.js'
import PokemonCollection from './PokemonCollection/PokemonCollection.js'
import SimilarTypesPage from './PokemonTypes/SimilarTypesPage.js'
import HomePage from './Home.js'
import Battle from './PokemonBattle/Battle'
const Navigation = (props) =>{
const data = useContext(PokemonData);
return (
<li className="nav-item link">
<a className="nav-link" id={props.Item} onClick={data.modifyPage}>{props.DisplayText}</a>
</li>
)
}
const NavBar = () =>{
const data = useContext(PokemonData);
return (
<ul className="navigation nav nav-pills">
<Navigation Item="HOME" DisplayText="HOME"/>
<Navigation Item="BROWSE" DisplayText="BROWSE"/>
<Navigation Item="SIMILARTYPES" DisplayText="SIMILARTYPES"/>
<Navigation Item="COLLECTION" DisplayText="COLLECTION"/>
{(data.debug)?<Navigation Item="POKEMONDETAILS" DisplayText="DETAILS"/>:""}
<Navigation Item="BATTLE" DisplayText="BATTLE"/>
<Navigation Item="GROCERYLIST" DisplayText="SHOPPING LIST"/>
</ul>
);
}
const PageContent = () => {
const data = useContext(PokemonData);
switch (data.currentPageViewing) {
case "HOME":{
return(
<div>
<HomePage />
</div>
)
}
case "BROWSE":{
return (<div>
<PokemonSearchPage />
</div>
);
}
case "SIMILARTYPES":{
return (
<div>
<SimilarTypesPage />
</div>
);
}
case "COLLECTION":{
return (
<div>
<PokemonCollection />
</div>
);
}
case "BATTLE":{
return (
<div>
<Battle/>
</div>
);
}
case "GROCERYLIST":{
return (
<div>
<GroceryList/>
</div>
);
}
case "POKEMONDETAILS":{
return (
<PokemonDetails />
);
}
default:{
return (
<div>
This is the {data.currentPageViewing} page.
</div>
);
}
}
}
class App extends React.Component{
constructor(props) {
super(props)
this.state={
currentPageViewing: "HOME",
currentPokemon: 'eevee',
currentPokemonType: 'normal',
Pokemon: {}, //Contains page-specific data
MyCollection: ['eevee', 'ditto'],
GroceryList: [{name:"Item1",quantity:3},{name:"Item2",quantity:5},{name:"Item3",quantity:1}],
GroceryListItem: "",
GroceryListAmt: 0,
GroceryListFormItem: undefined,
debug: false, //Turn off to hide navbar links used during testing.
BattleInfo1: <b></b>,
BattleInfo2: <b></b>,
BattleTurnCount: 0,
PokemonName1: "",
PokemonName2: "",
Pokemon1Data: {},
Pokemon2Data: {},
Pokemon1TypeData: [],
Pokemon2TypeData: [],
BattleLog: "",
BattleLog2: "",
PokemonEffectiveness: [1,1],
finalMult: 0,
setPokemon1: (e)=>{
this.setState({PokemonName1:e.target.value});
},
setPokemon2: (e)=>{
this.setState({PokemonName2:e.target.value});
},
modifyPage: (e)=>{
this.setState({currentPageViewing:e.target.id});
//alert(this.state.currentPageViewing)
},
updateAddedItem: (e)=>{
this.setState({GroceryListItem:e.target.value})
},
updateQuantityItem: (e)=>{
this.setState({GroceryListAmt:Number(e.target.value)})
},
addToGroceryList: (e)=>{
if (this.state.GroceryListItem.length>0) {
var list = this.state.GroceryList
var found=false;
var item = {name:this.state.GroceryListItem,quantity:this.state.GroceryListAmt};
for (var i=0;i<list.length;i++) {
if (list[i].name.toLowerCase()===item.name.toLowerCase()) {
found=true;
list[i].quantity+=item.quantity;
break;
}
}
if (!found) {
list.push(item)
}
this.setState({GroceryList:list})
document.getElementById("item").value=""
document.getElementById("quantity").value="1"
this.setState({GroceryListItem:e.target.value})
}
},
addItemToGroceryList: (item)=>{
var list = this.state.GroceryList
var found=false;
for (var i=0;i<list.length;i++) {
if (list[i].name.toLowerCase()===item.name.toLowerCase()) {
found=true;
list[i].quantity+=item.quantity;
break;
}
}
if (!found) {
list.push(item)
}
this.setState({GroceryList:list})
alert(item.name+" added to cart!");
},
removeFromGroceryList: (e)=>{
var list = this.state.GroceryList
list.splice(e.target.id,1)
this.setState({GroceryList:list})
},
updateTypeData: (pokemon,data)=>{
if (pokemon===1) {
var list = this.state.Pokemon1TypeData
list.push(data)
this.setState({Pokemon1TypeData:list})
} else {
var list = this.state.Pokemon2TypeData
list.push(data)
this.setState({Pokemon2TypeData:list})
}
},
BattleFightPhase: "SEARCHING",
doPhase: (e)=>{
switch (e.target.id) {
case "SEARCHING":{
this.setState({BattleInfo1:this.state.PokemonName1})
this.setState({BattleInfo2:this.state.PokemonName2})
this.setState({PokemonEffectiveness:[1,1]});
this.setState({Pokemon1TypeData:[]});
this.setState({Pokemon2TypeData:[]});
fetch(`https://pokeapi.co/api/v2/pokemon/${this.state.PokemonName1.toLowerCase()}`).then(res => res.json()).then(
(data)=>{this.setState({Pokemon1Data:data})}).then(()=>{
fetch(`https://pokeapi.co/api/v2/pokemon/${this.state.PokemonName2.toLowerCase()}`).then(res => res.json()).then(
(data)=>{this.setState({Pokemon2Data:data})})})/*.then(
fetch(`${this.state.Pokemon1Data.types[0].type.url}`)).then(res=>res.json()).then((data)=>{this.setState({Pokemon1TypeData:data})}).then(fetch(`${this.state.Pokemon2Data.types[0].type.url}`)).then(res=>res.json()).then((data)=>{this.setState({Pokemon2TypeData:data})}).*/.then(
//Something.
).catch(()=>{this.setState({BattleInfo1:"Something went wrong!"})})
setTimeout(()=>{
if (this.state.Pokemon1Data.types!==undefined) {
for (var i=0;i<this.state.Pokemon1Data.types.length;i++) {
fetch(this.state.Pokemon1Data.types[i].type.url).then(res=>res.json()).then((data)=>{
var list = this.state.Pokemon1TypeData
list.push(data)
this.setState({Pokemon1TypeData:list})})
}} else {
var info =<b>Something went wrong!</b>
this.setState({BattleInfo1:info})
}
if (this.state.Pokemon2Data.types!==undefined) {
for (var i=0;i<this.state.Pokemon2Data.types.length;i++) {
fetch(this.state.Pokemon2Data.types[i].type.url).then(res=>res.json()).then((data)=>{var list = this.state.Pokemon2TypeData
list.push(data)
this.setState({Pokemon2TypeData:list})})
}} else {
var info =<b>Something went wrong!</b>
this.setState({BattleInfo2:info})
}
},2000);
setTimeout(()=>{
this.state.determineBattleResults()
},4000)
}break;
}
},
compareDamageOnTypes: (numb)=>{
var finalMult = 1;
var opposingData = this.state.Pokemon2Data;
var opposingTypeData = this.state.Pokemon2Data;
if (Number(numb)===1) {
opposingData = this.state.Pokemon2Data;
opposingTypeData = this.state.Pokemon2TypeData;
} else {
opposingData = this.state.Pokemon1Data;
opposingTypeData = this.state.Pokemon1TypeData;
}
for (var i=0;i<opposingTypeData.length;i++) {
var typeData = opposingTypeData[i].damage_relations;
//Look at no damage from.
for (var j=0;j<typeData.no_damage_from.length;j++) {
var newType = typeData.no_damage_from[j].name
var enemyMatchingTypes = opposingData.types.filter((type)=>type.type.name===newType);
if (enemyMatchingTypes.length>0) {
finalMult*=0;
console.log("Vulnerability went down to "+finalMult+"! Matching types: "+JSON.stringify(enemyMatchingTypes))
}
return 0;
}
//Look at double damage from.
for (var j=0;j<typeData.double_damage_from.length;j++) {
var newType = typeData.double_damage_from[j].name
var enemyMatchingTypes = opposingData.types.filter((type)=>type.type.name===newType);
console.log(enemyMatchingTypes)
if (enemyMatchingTypes.length>0) {
finalMult*=2;
console.log("Vulnerability went up to "+finalMult+"! Matching types: "+JSON.stringify(enemyMatchingTypes))
}
}
//Look at half damage from.
for (var j=0;j<typeData.half_damage_from.length;j++) {
var newType = typeData.half_damage_from[j].name
var enemyMatchingTypes = opposingData.types.filter((type)=>type.type.name===newType);
if (enemyMatchingTypes.length>0) {
finalMult/=2;
console.log("Vulnerability went down to "+finalMult+"! Matching types: "+JSON.stringify(enemyMatchingTypes))
}
}
}
return finalMult;
},
determineBattleResults: ()=>{
if (this.state.Pokemon1Data.stats!==undefined) {
var p1Atk = this.state.Pokemon1Data.stats[1].base_stat;
var p2Atk = this.state.Pokemon2Data.stats[1].base_stat;
var p1MAtk = this.state.Pokemon1Data.stats[3].base_stat;
var p2MAtk = this.state.Pokemon2Data.stats[3].base_stat;
var p1Def = this.state.Pokemon1Data.stats[2].base_stat;
var p2Def = this.state.Pokemon2Data.stats[2].base_stat;
var p1MDef = this.state.Pokemon1Data.stats[4].base_stat;
var p2MDef = this.state.Pokemon2Data.stats[4].base_stat;
var p1HP = this.state.Pokemon1Data.stats[0].base_stat;
var p2HP = this.state.Pokemon2Data.stats[0].base_stat;
var pokemon1Power = this.state.compareDamageOnTypes(2)*((Math.max(p1Atk-p2Def,1)+Math.max(p1MAtk-p2MDef,1)));
var pokemon2Power = this.state.compareDamageOnTypes(1)*((Math.max(p2Atk-p1Def,1)+Math.max(p2MAtk-p1MDef,1)));
var turns1 = Math.ceil(p2HP/pokemon1Power);
var turns2 = Math.ceil(p1HP/pokemon2Power);
var log = "It will take "+turns1+"turns for p1 to kill p2, dealing "+pokemon1Power+" per attack w/p2 having "+p2HP+" HP. I have a type "+(this.state.compareDamageOnTypes(2)>1?"advantage":"disadvantage")+" against my opponent."
var log2 = "It will take "+turns2+" turns for p2 to kill p1, dealing "+pokemon2Power+" per attack w/p1 having "+p1HP+" HP. I have a type "+(this.state.compareDamageOnTypes(1)>1?"advantage":"disadvantage")+" against my opponent."
if (turns1>turns2) {
log="I will lose! "+log
log2="I will win! "+log2
} else {
log="I will win! "+log
log2="I will win! "+log2
}
} else {
log = "Loading...";
log2 = "Loading...";
}
this.setState({BattleLog:log})
this.setState({BattleLog2:log2})
},
addToCollection: (e) => {
if (this.state.MyCollection.indexOf(e.target.id) === -1) {
this.setState({
MyCollection: this.state.MyCollection.concat(e.target.id)
})
alert(`${e.target.id} added to collection!`)
} else {
alert(`${e.target.id} already in collection!`)
}
},
removeFromCollection: (e) => {
var list = this.state.MyCollection
list.splice(e.target.id, 1)
this.setState({MyCollection: list})
alert(this.state.MyCollection.join(', '))
},
setCurrentPokemon: (e) => {
this.setState({
currentPokemon: e.target.id,
currentPageViewing: 'POKEMONDETAILS'
})
},
setCurrentPokemonType: (e) => {
this.setState({
currentPokemonType: e.target.id,
currentPageViewing: 'SIMILARTYPES'
})
}
}
}
render() {
return (
<PokemonData.Provider value={this.state}>
<div className="container-fluid">
<div className="row">
<div className="col-md-12 bg-dark text-white p-3">
<NavBar className="" />
</div>
</div>
<div className="row bg-dark">
<div className="col-md-10 bg-dark text-white rounded p-3">
<PageContent />
</div>
</div>
</div>
</PokemonData.Provider>
);
}
}
export default App;

@ -0,0 +1,9 @@
import React from 'react';
import { render } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
const { getByText } = render(<App />);
const linkElement = getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

@ -0,0 +1,49 @@
import React, { useContext } from 'react';
import {PokemonData} from './PokemonAppContext';
const RemoveButton = (props) => {
const data = useContext(PokemonData);
return (
<button id={props.element} onClick={data.removeFromGroceryList}>
-
</button>
)
}
const ItemList = () => {
const data = useContext(PokemonData);
return (
<div>
<ul>
{data.GroceryList.map((item,id)=>(
<li>{item.name+" x"+item.quantity} <RemoveButton element={id}/></li>))
}
</ul>
</div>
)
}
const AddItem = () => {
const data = useContext(PokemonData);
return (
<div>
<label for="item"><b>Add Item:</b></label>
<input type="text" id="item" onChange={data.updateAddedItem}/>
<label for="quantity"><b>Quantity:</b></label>
<input className="smallForm" type="number"min="1" max="99" id="quantity" onChange={data.updateQuantityItem}/>
<button onClick={data.addToGroceryList}>Submit</button>
</div>
)
}
const GroceryList = () => {
const data = useContext(PokemonData);
return (
<div>
<ItemList/>
<AddItem/>
</div>
)
}
export default GroceryList;

@ -0,0 +1,68 @@
import React, { useState, useContext, useEffect } from 'react';
import PokemonSearchResult from './PokemonSearch/PokemonSearchResults.js'
import { PokemonData } from './PokemonAppContext';
const HomePage = (props) => {
const context = useContext(PokemonData)
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [pokemon, setPokemon] = useState([]);
const [nextUrl, setNextUrl] = useState('')
const [prevUrl, setPrevUrl] = useState('https://pokeapi.co/api/v2/pokemon')
const [url, setUrl] = useState('https://pokeapi.co/api/v2/pokemon')
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setPokemon(result);
if (result.next !== null) {
setNextUrl(result.next)
console.log("Next: "+result.next)
}
if (result.prevUrl !== null) {
setPrevUrl(result.previous)
console.log("Previous: "+result.previous)
}
},
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [url])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else if (pokemon.length === 0) {
return <div>No data</div>
} else {
return (
<div>
<div>
<h1>Home</h1>
<h3>View Pokemon - Total: {pokemon.count}</h3>
<button onClick={() => {setUrl(prevUrl)}} type='button'>Prev 20</button>
<button onClick={() => {setUrl(nextUrl)}} type='button'>Next 20</button>
<div className="row">
<PokemonSearchResult pokemon={pokemon.results.map((p,i) => {
let x = {
pokemon: {
name: p.name,
url: p.url
},
}
return x
})} />
</div>
</div>
</div>
);
}
}
export default HomePage

@ -0,0 +1,22 @@
import React from 'react';
const data = {
currentPageViewing: "GROCERYLIST",
Pokemon: {}, //Contains page-specific data
MyCollection: {},
GroceryList: [],
GroceryListItem: "",
debug: false, //Turn off to hide navbar links used during testing.
}
/*
PAGES:
"" = HOME
"BROWSE" - Browse all pokemon.
"SIMILARTYPES" - Show similarly-typed pokemon.
"COLLECTION" - View my pokemon collection.
"BATTLE" - Battle page.
"GROCERY LIST" - Grocery List page.
*/
export const PokemonData = React.createContext(data);

@ -0,0 +1,70 @@
import React, { useContext } from 'react';
import {PokemonData} from '../PokemonAppContext';
const PokemonDisplay = (props) => {
const data = useContext(PokemonData);
const line = props.pokemon==="1"?JSON.stringify(data.Pokemon1TypeData):JSON.stringify(data.Pokemon2TypeData);
const numb = props.pokemon
const myLog = props.pokemon==="1"?data.BattleLog:data.BattleLog2
if (props.data.sprites!==undefined) {
return (
<div>
<img src={props.data.sprites.front_default}/>
<b>Types: </b>{props.data.types.map((type,ind)=>{
if (ind>0) {
return "/"+type.type.name;
} else {
return type.type.name;
}
})}
<br/>
<b>Stats: </b>{props.data.stats.map((type,ind)=>{
return type.stat.name[0].toUpperCase()+type.stat.name.slice(1)+": "+type.base_stat+" ";
})}
<br/>
<b>Type benefits: </b> {data.compareDamageOnTypes(props.pokemon)}
<br/>
<b>Battle Outcome: </b> {myLog
}
</div>
)
} else {
return (
<div>
No data!
</div>
)
}
}
const Pokemon = (props) => {
const data = useContext(PokemonData);
return (
<input type="text" onChange={props.change}/>
)
}
const DisplayBattle = () => {
const data = useContext(PokemonData);
return (
<div>
<PokemonDisplay data={data.Pokemon1Data} typedata={data.Pokemon1TypeData} pokemon="1"/>
<PokemonDisplay data={data.Pokemon2Data} typedata={data.Pokemon2TypeData} pokemon="2"/>
</div>
);
}
const Battle = () => {
const data = useContext(PokemonData);
return (
<div id="fightContainer">
<Pokemon name="Pokemon1" change={data.setPokemon1}/>
VS
<Pokemon name="Pokemon2" change={data.setPokemon2}/>
<button id="SEARCHING" onClick={data.doPhase}>Start Fight</button>
<DisplayBattle/>
</div>
)
}
export default Battle;

@ -0,0 +1,30 @@
import React, { useContext } from 'react'
import {PokemonData} from '../PokemonAppContext';
const PokemonSearchResult = (props) => {
const context = useContext(PokemonData)
return (
<table>
<thead>
<tr>
<th>Pokemon Name</th>
<th>Remove To Collection</th>
</tr>
</thead>
<tbody>
{context.MyCollection.map((p, i) =>
<tr key={i}>
<td>
<div id={p} onClick={context.setCurrentPokemon}>{p}</div>
</td>
<td>
<div id={p} onClick={context.removeFromCollection}>X</div>
</td>
</tr>
)}
</tbody>
</table>
)
}
export default PokemonSearchResult

@ -0,0 +1,56 @@
import React, { useContext } from 'react';
import {PokemonData} from './PokemonAppContext';
class PokemonBattleData extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
pokemon: this.props.pokemon,
pokeData: []
};
}
componentDidMount() {
fetch(`https://pokeapi.co/api/v2/pokemon/${this.state.pokemon}`)
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
pokeData: result
});
},
(error) => {
this.setState({
isLoaded: true,
error
})
}
)
}
render() {
const { error, isLoaded, pokeData } = this.state;
if (error) {
return (
<div>Error: {error.message}</div>
)
} else if (!isLoaded) {
return (
<div>Loading...</div>
)
} else {
return (
<div>
<div>
<img src={pokeData.sprites.front_default} alt={`Sprite of ${pokeData.species.name}`} />
</div>
</div>
)
}
}
}
export default PokemonBattleData

@ -0,0 +1,40 @@
import React, { useContext, useEffect, useState } from 'react'
import { PokemonData } from './PokemonAppContext.js'
import PokemonSearchResult from './PokemonSearch/PokemonSearchResults.js'
const PokemonDetails = (props) => {
const context = useContext(PokemonData)
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [pokemon, setPokemon] = useState([]);
const url = `https://pokeapi.co/api/v2/pokemon/${context.currentPokemon}`
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setPokemon(result);
},
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [url])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else if (pokemon.length === 0) {
return <div>No data</div>
} else {
return (
<PokemonSearchResult pokemon={[{...pokemon,pokemon:{url:url}}]}/>
);
}
}
export default PokemonDetails

@ -0,0 +1,36 @@
import React, { useState, useEffect } from 'react'
import PokemonSearchResult from './PokemonSearchResults.js'
const PokemonSearch = (props) => {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [pokemon, setPokemon] = useState([]);
const url = `https://pokeapi.co/api/v2/${props.search.split('=')[0]}/${props.search.split('=')[1]}`
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setPokemon(result.pokemon);
},
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [url])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<PokemonSearchResult pokemon={pokemon} />
);
}
}
export default PokemonSearch

@ -0,0 +1,60 @@
import React, { useState } from 'react';
import PokemonSearch from './PokemonSearch.js'
const PokemonSearchPage = (props) => {
// Search bar state
const [searchError, setSearchError] = useState(true);
const [search, setSearch] = useState('')
const handleChange = (event) => {
setSearch(event.target.value)
setSearchError(true)
}
const handleSubmit = (event) => {
event.preventDefault();
if (search.indexOf('=') === -1) {
setSearchError(true)
} else {
setSearchError(false)
}
}
const renderForm = () => {
return (
<div>
<form onSubmit={handleSubmit}>
<label>
Search by properties: (e.g. type=ground, ability=battle-armor)
</label>
<div>
<input
type="text"
name="name"
value={search}
onChange={handleChange}
/>
</div>
<input type="submit" value="Submit" />
</form>
</div >
)
}
if (searchError !== true && search) {
return (
<div>
{renderForm()}
<PokemonSearch search={search} />
</div>
)
} else {
return (
<div>
{renderForm()}
</div>
)
}
}
export default PokemonSearchPage

@ -0,0 +1,260 @@
import React, { useState, useContext, useEffect } from 'react'
import {PokemonData} from '../PokemonAppContext';
const Berry = (props) => {
const context = useContext(PokemonData)
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [berry, setBerry] = useState([]);
//console.log(props.berry)
const [url, setUrl] = useState(props.berry.berry.url)
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setBerry(result);
},
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [url])
if (error) {
return <React.Fragment/>;
} else if (!isLoaded) {
return <React.Fragment/>;
} else if (berry.length === 0) {
return <div>No data</div>
} else {
var goodBerry = "";
//console.log(props)
for (var i=0;i<props.type.length;i++) {
if (berry.natural_gift_type.name===props.type[i].type.name) {
goodBerry=<img className="link" onClick={()=>{context.addItemToGroceryList({name:berry.name[0].toUpperCase()+berry.name.slice(1)+" Berry",quantity:1})}} alt="Click to add to cart!" src={"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/items/"+berry.name+"-berry.png"}/>
break;
}
}
return (
<React.Fragment>
{goodBerry}
</React.Fragment>
)
}
}
const GoodBerries = (props) => {
//console.log(props)
return (
<React.Fragment>
{props.berry.map((b, i) =>
<Berry type={props.type} berry={b}/>
)}
</React.Fragment>
);
}
const BerryData = (props) => {
const context = useContext(PokemonData)
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [berry, setBerry] = useState([]);
const [url, setUrl] = useState('https://pokeapi.co/api/v2/berry/?limit=64')
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setBerry(result);
},
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [url])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else if (berry.length === 0) {
return <div>No data</div>
} else {
return (
<GoodBerries type={props.types} berry={berry.results.map((b)=>{
let x = {
berry: {
name: b.name,
url: b.url
},
}
return x
})
}/>
)
}
//https://pokeapi.co/api/v2/berry/?limit=64
}
const SpeciesData = (props) => {
const context = useContext(PokemonData)
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [pokemon, setPokemon] = useState([]);
const [url, setUrl] = useState(props.url)
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setPokemon(result);
},
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [url])
//console.log(pokemon.flavor_text_entries)
var usableEntry = "";
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else if (pokemon.length === 0) {
return <div>No data</div>
} else {
for (var i=pokemon.flavor_text_entries.length-1;i>=0;i--) {
var entry = pokemon.flavor_text_entries[i];
if (entry.language.name==="en") {
usableEntry = entry.flavor_text
break;
}
}
return (
<div id={props.id}>
{usableEntry}
</div>
)
}
}
const Pokemon = (props) => {
const context = useContext(PokemonData)
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [pokemon, setPokemon] = useState([]);
const [url, setUrl] = useState(props.pokemon.pokemon.url)
function GetTypeImage(type) {
var image_folder = ""
switch (type.toLowerCase()) {
case "bug":{return "https://snipboard.io/JKNud5.jpg";}
case "dark":{return "https://snipboard.io/Dsamd7.jpg";}
case "dragon":{return "https://snipboard.io/6h3fRl.jpg";}
case "electric":{return "https://snipboard.io/FGthec.jpg";}
case "fairy":{return "https://snipboard.io/3yHceJ.jpg";}
case "fighting":{return "https://snipboard.io/A24gIu.jpg";}
case "fire":{return "https://snipboard.io/iXMvLx.jpg";}
case "flying":{return "https://snipboard.io/n6cloE.jpg";}
case "ghost":{return "https://snipboard.io/Lbq8Hg.jpg";}
case "grass":{return "https://snipboard.io/0UXhiJ.jpg";}
case "ground":{return "https://snipboard.io/OTWC8m.jpg";}
case "ice":{return "https://snipboard.io/HctKUC.jpg";}
case "normal":{return "https://snipboard.io/1IrhDK.jpg";}
case "poison":{return "https://snipboard.io/ic5eYz.jpg";}
case "psychic":{return "https://snipboard.io/V7QgZ0.jpg";}
case "rock":{return "https://snipboard.io/Sf8Lvq.jpg";}
case "steel":{return "https://snipboard.io/2peJxP.jpg";}
case "water":{return "https://snipboard.io/ex9D7c.jpg";}
}
}
if (props.name) {
props.pokemon.pokemon.url = `https://pokeapi.co/api/v2/pokemon/${props.name}`
}
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setPokemon(result);
},
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [url])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else if (pokemon.length === 0) {
return <div>No data</div>
} else {
//console.log(pokemon)
return (
<div className=" card bg-dark">
<div className="row">
<div className="col-md-4">
<img className="fit-image shadow-lg" src={pokemon.sprites.front_default}/>
<div className="row">
<div className="col-md-12">
<b>Favorite Berries:</b>
</div>
</div>
<div className="col-md-12">
<BerryData types={pokemon.types}/>
</div>
</div>
<div className="col-md-8">
<div className="row">
<div className="col-md-4">
<h2>#{pokemon.id}</h2>
</div>
<div className="col-md-8">
{pokemon.types.map((type)=>{
return (<span><img className="type-small link" id={type.type.name} onClick={context.setCurrentPokemonType} src={GetTypeImage(type.type.name)}/>
</span>)
})}
</div>
</div>
<div className="row">
<div className="col-md-12 link" id={pokemon.species.name} onClick={context.setCurrentPokemon}>
<h3 id={pokemon.species.name}>{pokemon.species.name[0].toUpperCase()+pokemon.species.name.slice(1)}</h3>
<SpeciesData id={pokemon.species.name} url={pokemon.species.url}/>
</div>
</div>
<div className="row">
<div className="col-md-8 pt-3 offset-md-2">
<span className="link centered" id={pokemon.name} name={props.pokemon.pokemon.url} onClick={context.addToCollection}>Add to Collection</span>
</div>
</div>
</div>
</div>
</div>)
}
}
const PokemonSearchResult = (props) => {
const context = useContext(PokemonData)
//console.log(props.pokemon)
return (
<React.Fragment>
{props.pokemon.map((p, i) =>
<div className="col-md-6">
<Pokemon pokemon={p}/>
</div>
)}
</React.Fragment>
)
}
export default PokemonSearchResult

@ -0,0 +1,44 @@
import React, { useState, useContext, useEffect } from 'react';
import PokemonSearchResult from '../PokemonSearch/PokemonSearchResults.js'
import {PokemonData} from '../PokemonAppContext';
const SimilarTypesPage = (props) => {
const context = useContext(PokemonData)
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [pokemon, setPokemon] = useState([]);
const url = `https://pokeapi.co/api/v2/type/${context.currentPokemonType}`
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setPokemon(result.pokemon);
},
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [url])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else if (pokemon.length === 0) {
return <div>No data</div>
} else {
return (
<div>
<h1>{`${context.currentPokemonType[0].toUpperCase()+context.currentPokemonType.slice(1)} Type Pokemon`}</h1>
<div>
<PokemonSearchResult pokemon={pokemon} />
</div>
</div>
);
}
}
export default SimilarTypesPage

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

@ -0,0 +1,13 @@
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;
}

@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
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://bit.ly/CRA-PWA
serviceWorker.unregister();

@ -0,0 +1,7 @@
<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>

After

Width:  |  Height:  |  Size: 2.6 KiB

@ -0,0 +1,141 @@
// 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://bit.ly/CRA-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://bit.ly/CRA-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://bit.ly/CRA-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);
});
}
}

@ -0,0 +1,5 @@
// 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/extend-expect';
Loading…
Cancel
Save