Weather app (#10)

* feat: base class added and api

* feat: async method/conversions

* feat: added styling and ui

* feat: added some colors

* feat: project complete
This commit is contained in:
Mike 2024-01-22 20:59:19 -05:00 committed by GitHub
parent 8cc79da6d9
commit 4d2291815a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 5771 additions and 0 deletions

12
weather/.eslintrc.js Normal file
View file

@ -0,0 +1,12 @@
module.exports = {
env: {
browser: true,
es2021: true,
node: true,
},
extends: ["eslint:recommended", "prettier"],
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
},
};

132
weather/.gitignore vendored Normal file
View file

@ -0,0 +1,132 @@
# ---> Node
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

4
weather/.prettierrc Normal file
View file

@ -0,0 +1,4 @@
{
"tabWidth": 4,
"singleQuote": true
}

5
weather/README.md Normal file
View file

@ -0,0 +1,5 @@
# webpack-template
Vanilla template for webpack
sets up common utilities needed for vanilla JS/HTML/CSS development

5036
weather/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

25
weather/package.json Normal file
View file

@ -0,0 +1,25 @@
{
"name": "webpack-template",
"version": "1.0.0",
"description": "Vanilla template for webpack",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack serve --open --config webpack.dev.js",
"build": "webpack --config webpack.prod.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^6.8.1",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"html-webpack-plugin": "^5.6.0",
"style-loader": "^3.3.3",
"webpack": "^5.89.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1",
"webpack-merge": "^5.10.0"
}
}

View file

@ -0,0 +1,86 @@
export default class WeatherComponent {
constructor(apiKey) {
this.apiKey = apiKey;
}
currentWeatherData = undefined;
async getWeatherReport(zipcode) {
const url = `https://api.openweathermap.org/data/2.5/weather?zip=${zipcode}&appid=${this.apiKey}`;
let response = await fetch(url);
if (response.status !== 200) {
return;
}
let data = await response.json();
// Set current weather data
if (data) {
this.setCurrentWeather(data);
this.parseWeatherData();
}
}
parseWeatherData() {
const self = this;
let data = {
time: this.currentWeatherData.dt,
icon: `https://openweathermap.org/img/wn/${this.currentWeatherData.weather[0].icon}@2x.png`,
weather: {
main: this.currentWeatherData.weather[0].main,
description: this.currentWeatherData.weather[0].description,
},
temp: {
current: this.currentWeatherData.main.temp,
feelsLike: this.currentWeatherData.main.feels_like,
minTemp: this.currentWeatherData.main.temp_min,
maxTemp: this.currentWeatherData.main.temp_max,
},
wind: this.currentWeatherData.wind,
sunrise: this.currentWeatherData.sys.sunrise,
sunset: this.currentWeatherData.sys.sunset,
city: this.currentWeatherData.name,
convertTemp(conversionType) {
this[conversionType] = {};
const method =
conversionType === 'F'
? self.convertToFarenheit
: self.convertToCelsius;
const tempKeys = Object.keys(this.temp);
tempKeys.forEach((element) => {
this[conversionType][element] = method(this.temp[element]);
});
},
};
if (data) this.parsedWeatherData = data;
}
async getWeather(zip) {
try {
await this.getWeatherReport(zip);
return (
this.parsedWeatherData || {
error: 'Sorry, unable to fetch current weather at this time. :(',
}
);
} catch (error) {
console.log(error.message);
return { error: 'issue occured while fetching weather data!' };
}
}
convertToCelsius(temp) {
return Math.round(temp - 273.15);
}
convertToFarenheit(temp) {
return Math.round((temp - 273.15) * 1.8 + 32);
}
setCurrentWeather(data) {
this.currentWeatherData = data;
}
}

View file

@ -0,0 +1,234 @@
import WeatherComponent from './weather';
class MainWebsite {
constructor(apikey) {
this.weatherComponent = new WeatherComponent(apikey);
this.container = document.createElement('div');
this.form = document.createElement('form');
}
websiteStructure() {
this.container.classList.add('container');
this.formStructure();
this.weatherComponentStructure();
const title = document.createElement('h1');
title.classList.add('title');
title.textContent = 'How is it outside?';
// Add form to container
this.container.append(title, this.weatherDiv);
return this.container;
}
weatherComponentStructure() {
// Main weather info component
this.weatherDiv = document.createElement('div');
this.weatherDiv.classList.add('weather-container');
// Related to fetched weather report
this.reportDiv = document.createElement('div');
this.reportStructure();
this.reportTempDetails.append(
this.reportTempFeelsLike,
this.reportMinTemp,
this.reportMaxTemp,
);
this.reportDiv.append(
this.reportCity,
// this.reportConditions,
this.reportConditionDescription,
this.reportTemp,
this.reportTime,
this.reportTempDetails,
this.reportIcon,
);
this.weatherDiv.append(this.form, this.reportDiv);
}
reportStructure() {
this.reportDiv.classList.add('report-container');
this.reportCity = document.createElement('h2');
this.reportCity.classList.add('city');
this.reportTemp = document.createElement('span');
this.reportTemp.classList.add('temp');
this.reportTime = document.createElement('span');
this.reportTime.classList.add('time');
this.reportTempDetails = document.createElement('div');
this.reportTempDetails.classList.add('temp-details-container');
this.reportTempFeelsLike = document.createElement('span');
this.reportTempFeelsLike.classList.add('feels-like');
this.reportMaxTemp = document.createElement('span');
this.reportMaxTemp.classList.add('max');
this.reportMinTemp = document.createElement('span');
this.reportMinTemp.classList.add('min');
this.reportIcon = document.createElement('img');
this.reportIcon.classList.add('icon-img');
// this.reportConditions = document.createElement('span');
// this.reportConditions.classList.add('conditions');
this.reportConditionDescription = document.createElement('span');
this.reportConditionDescription.classList.add('conditions-desc');
}
updateReportComponents() {
const items = [
this.reportTime,
this.reportCity,
this.reportTemp,
this.reportMaxTemp,
this.reportMinTemp,
this.reportConditionDescription,
// this.reportConditions,
];
function clearValues() {
items.forEach((e) => {
e.textContent = '';
});
}
function updateReportTemperatureText(item, temp, range) {
item.textContent = `${range}: ${temp}°`;
}
function updateReportText(item, text) {
item.textContent = `${text}`;
}
return { clearValues, updateReportTemperatureText, updateReportText };
}
formStructure() {
const div = document.createElement('div');
div.classList.add('form-input');
this.form.classList.add('form');
this.form.method = 'post';
this.form.action = '#';
const input = document.createElement('input');
input.id = 'zipcode';
input.name = 'zipcode';
input.type = 'text';
input.placeholder = 'Search by zipcode';
input.required = true;
input.addEventListener('input', (input) =>
this.formInputValidationChecker(input.target),
);
const span = document.createElement('span');
span.classList.add('zipcode-span');
this.button = document.createElement('button');
this.button.type = 'submit';
this.button.classList.add('btn');
this.button.textContent = 'Get report';
this.button.addEventListener('click', (e) => this.handleSubmit(e));
div.append(input, span);
this.form.append(div, this.button);
}
formInputValidationChecker(e) {
this.ensureValidZipCode(e);
}
handleSubmit(e) {
e.preventDefault();
// one more sanity check before submit
const span = document.querySelector('.zipcode-span');
const input = document.querySelector('#zipcode');
if (this.validZipcode && input.value !== '') {
this.weatherComponent
.getWeather(input.value)
.then((report) => this.updateWeatherComponent(report));
input.value = '';
} else {
span.textContent = 'Please enter a 5 digit zip code!';
}
}
ensureValidZipCode(zipcode) {
const validityMessage = 'Please enter a 5 digit zip code!';
zipcode.minLength = 5;
zipcode.maxLength = 5;
zipcode.pattern = '\\d{5}';
if (
zipcode.validity.tooShort ||
zipcode.validity.patternMismatch ||
zipcode.validity.tooLong
) {
zipcode.setCustomValidity(validityMessage);
zipcode.nextSibling.textContent = validityMessage;
this.validZipcode = false;
} else {
zipcode.setCustomValidity('');
zipcode.nextSibling.textContent = '';
this.validZipcode = true;
}
}
updateWeatherComponent(weatherReportData) {
// clear the values in the dom
const reportUpdater = this.updateReportComponents();
reportUpdater.clearValues();
// convert the F and C temps
weatherReportData.convertTemp('C');
weatherReportData.convertTemp('F');
reportUpdater.updateReportText(this.reportCity, weatherReportData.city);
reportUpdater.updateReportText(
this.reportTemp,
weatherReportData.F.current,
);
// reportUpdater.updateReportText(
// this.reportConditions,
// weatherReportData.weather.main,
// );
reportUpdater.updateReportText(
this.reportConditionDescription,
weatherReportData.weather.description,
);
reportUpdater.updateReportTemperatureText(
this.reportTempFeelsLike,
weatherReportData.F.feelsLike,
'Feels like',
);
reportUpdater.updateReportTemperatureText(
this.reportMaxTemp,
weatherReportData.F.maxTemp,
'max',
);
reportUpdater.updateReportTemperatureText(
this.reportMinTemp,
weatherReportData.F.minTemp,
'min',
);
this.reportIcon.src = weatherReportData.icon;
// Set report div desplay to flex
this.reportDiv.classList.add('show-report');
}
}
export { MainWebsite };

28
weather/src/index.js Normal file
View file

@ -0,0 +1,28 @@
import { MainWebsite } from './components/website';
import './style.css';
const api = 'bd5d23eea5751c12b0ef75344e3df932';
const web = new MainWebsite(api);
function fonts() {
let fontLink = document.createElement('link');
fontLink.rel = 'preconnect';
fontLink.href = 'https://fonts.googleapis.com';
let fontLinkTwo = document.createElement('link');
fontLinkTwo.rel = 'preconnect';
fontLinkTwo.href = 'https://fonts.gstatic.com';
fontLinkTwo.crossOrigin = true;
let style = document.createElement('link');
style.rel = 'stylesheet';
style.href =
'https://fonts.googleapis.com/css2?family=Indie+Flower&family=Inter:wght@100..900&display=swap';
document.head.appendChild(fontLink);
document.head.appendChild(fontLinkTwo);
document.head.appendChild(style);
}
fonts();
document.body.appendChild(web.websiteStructure());

159
weather/src/style.css Normal file
View file

@ -0,0 +1,159 @@
:root {
--dark-color: hsla(146, 14%, 10%, 0.897);
--lgiht-color: hsla(160, 6%, 90%, 0.89);
--light-color: hsl(0 0% 90%);
--interface-color: rgba(235, 236, 236, 0.726);
--font-size: 18px;
--report-box-shadow: 0px 1px 1px hsl(0deg 0% 0% / 0.075),
0px 2px 2px hsl(0deg 0% 0% / 0.075), 0px 4px 4px hsl(0deg 0% 0% / 0.075),
0px 8px 8px hsl(0deg 0% 0% / 0.075),
0px 16px 16px hsl(0deg 0% 0% / 0.075),
0px 32px 32px hsl(0deg 0% 0% / 0.075);
--title-box-shadow: 0px 2px 2px hsl(0deg 0% 0% / 0.1),
0px 4px 4px hsl(0deg 0% 0% / 0.1), 0px 8px 8px hsl(0deg 0% 0% / 0.1);
}
html,
body {
padding: 0;
margin: 0;
font-size: var(--font-size);
font-family: 'Inter', sans-serif;
font-optical-sizing: auto;
font-weight: 400;
font-style: normal;
font-variation-settings: 'slnt' 0;
background-color: var(--interface-color);
height: 100vh;
}
button {
border-radius: 0.2rem;
}
.title {
font-size: 3rem;
font-weight: 800;
text-align: center;
margin: 0;
background-color: var(--dark-color);
color: hsl(146, 30%, 90%);
font-family: 'Indie Flower', cursive;
box-shadow: var(--title-box-shadow);
}
.form {
display: flex;
gap: 10px;
padding: 20px;
margin: 20px 0;
}
.form-input {
display: flex;
flex-direction: column;
margin: auto;
align-items: center;
}
.form button {
align-self: baseline;
flex: 1;
height: 42px;
}
.form-input input {
padding: 10px;
font-size: 1rem;
margin-bottom: 5px;
color: var(--dark-color);
border: 1px;
box-shadow:
inset 0 2px 2px hsla(0, 0%, 0%, 0.2),
0 2px 0 hsla(0, 0%, 100%, 0.15);
}
.form-input input:focus {
outline: none;
}
.form-input span {
color: hsla(0, 79%, 54%, 0.829);
margin-left: 5px;
}
.form-input span {
font-size: 0.8rem;
}
.btn {
font-size: 0.8rem;
padding: 10px;
background-color: hsl(61.8, 85%, 66.7%);
box-shadow:
inset 0 1px 0 var(--light-color),
0 1px 3px hsla(0, 0%, 0%, 0.2);
}
.btn:hover {
background-color: hsl(62.1, 85%, 78.6%);
}
.weather-container {
display: flex;
flex-direction: column;
align-items: center;
}
.report-container {
display: none;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
justify-items: center;
align-items: center;
padding: 50px;
box-shadow: var(--report-box-shadow);
border-radius: 1rem;
background-color: var(--light-color);
}
.show-report {
display: grid;
}
.city {
grid-column: 1 / span 3;
}
.temp {
grid-column: 1 / span 1;
grid-row: 2 / span 1;
font-size: 4rem;
font-weight: 900;
}
.icon-img {
grid-column: 2 / span 2;
grid-row: 2;
}
/* .conditions { */
/* grid-column: 3 / span 1; */
/* grid-row: 2 / span 1; */
/* } */
.conditions-desc {
grid-column: 2 / span 2;
grid-row: 3 / span 1;
color: hsl(0 0% 30%);
align-self: start;
}
.temp-details-container {
grid-row: 3 / span 1;
display: flex;
flex-direction: column;
gap: 7px;
color: hsl(0 0% 30%);
}

34
weather/webpack.common.js Normal file
View file

@ -0,0 +1,34 @@
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
index: './src/index.js',
},
plugins: [
new HtmlWebpackPlugin({
title: 'Weatherize',
}),
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
],
},
};

10
weather/webpack.dev.js Normal file
View file

@ -0,0 +1,10 @@
const { merge } = require("webpack-merge");
const common = require("./webpack.common.js");
module.exports = merge(common, {
mode: "development",
devtool: "inline-source-map",
devServer: {
static: "./dist",
},
});

6
weather/webpack.prod.js Normal file
View file

@ -0,0 +1,6 @@
const { merge } = require("webpack-merge");
const common = require("./webpack.common.js");
module.exports = merge(common, {
mode: "production",
});