-
Notifications
You must be signed in to change notification settings - Fork 0
/
weather.js
533 lines (453 loc) · 16.4 KB
/
weather.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//=============================================================================
// Weather querying
//=============================================================================
async function fetchWeatherIn (locationStr) {
// Check for special values
let easterEggWeather = this.fetchEasterEggWeather(locationStr);
if (easterEggWeather) {
await sleep(200);
return easterEggWeather;
}
// The API key below is here for convenience; it's a free key for a demo app.
// It is generally not good practice to expose an API key on the front end,
// as a third party may discover the key and make unauthorized use of it.
// For this reason, paid API keys should be hidden securely on the server.
const MY_FREE_KEY = 'J9RKTKAX2HRTXCXKVAQE4DERZ';
const BASE_PATH = 'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline';
const RESPONSE_STATUS_OK = 200;
const location = encodeURIComponent(locationStr);
const INCLUDES = [
'current',
'days',
'hours',
'alerts',
];
const INCLUDES_STR = INCLUDES.join(',');
const query = `${BASE_PATH}/${location}?key=${MY_FREE_KEY}&include=${INCLUDES_STR}`;
const response = await fetch(query);
if (response.status != RESPONSE_STATUS_OK) {
throw new Error(`HTTP ${response.status} response`);
}
const report = await response.json();
console.log(report);
return simplifyWeather(report);
}
function simplifyWeather (fullReport) {
const today = fullReport.days[0];
return {
address: fullReport.resolvedAddress,
conditions: today.conditions.split(', '),
description: today.description,
highTemp: today.tempmax,
lowTemp: today.tempmin,
windDirection: today.winddir,
windSpeed: today.windspeed,
};
}
function fetchEasterEggWeather (locationStr) {
const str = locationStr.toLowerCase();
if (str == 'example') {
return {
address: 'Example Town, Kentuckiana, USA',
conditions: ['Partially cloudy'],
description: 'Default weather throughout the day',
highTemp: 55,
lowTemp: 45,
windDirection: 45,
windSpeed: 10,
};
} else if (str.includes('hotman') || str.includes('flamey-o')) {
return {
address: 'Flamey-O, Hotman',
conditions: ['Clear'],
description: 'Scorching hot all day',
highTemp: 120,
lowTemp: 90,
windDirection: 0,
windSpeed: 0,
};
} else if (str.endsWith('hoth')) {
return {
address: 'Ice Breeze, Hoth',
conditions: ['Snow', 'Hail', 'Cloudy'],
description: 'freezing winds all day',
highTemp: -20,
lowTemp: -50,
windDirection: 355,
windSpeed: 60,
};
} else if (str == 'one') {
return {
address: 'One',
conditions: '1',
description: 'ONE!!!1',
highTemp: 2,
lowTemp: 1,
windDirection: 1,
windSpeed: 1,
};
} else {
return null;
}
}
//=============================================================================
// Display Components
//=============================================================================
// General helpers
//-----------------------------------------------------------------------------
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function hideElement(element) {
element.classList.add('hidden');
}
async function showElement(element) {
element.classList.remove('hidden');
}
//-----------------------------------------------------------------------------
// Loading section
//-----------------------------------------------------------------------------
const LoadingDisplay = (function () {
const section = document.getElementById('loading');
const ellipsis = document.getElementById('ellipsis');
const INTERVAL_DELAY = 250;
let intervalId = null;
const hide = async function () {
hideElement(section);
clearInterval(intervalId);
}
const show = async function () {
intervalId = setInterval(function() {
if (ellipsis.innerText.length >= 3) {
ellipsis.innerText = '';
} else {
ellipsis.innerText += '.';
}
}, INTERVAL_DELAY);
showElement(section);
}
return { hide, show };
}());
//-----------------------------------------------------------------------------
// Title card
//-----------------------------------------------------------------------------
const TitleCard = (function () {
const locationNode = document.getElementById('location-output');
let card = {};
Object.defineProperty(card, 'location', {
get: function () {
return locationNode.innerText;
},
set: function (address) {
locationNode.innerText = address;
},
});
return card;
}());
//-----------------------------------------------------------------------------
// Thermometer cards
//-----------------------------------------------------------------------------
class ThermometerCard {
constructor (cardNode) {
this._colorMap = this._makeColorMap();
this._cardNode = cardNode;
this._thermometerNode = cardNode.querySelector('.thermometer');
this._headingNode = cardNode.querySelector('.heading');
this._temperatureNode = cardNode.querySelector('.temperature');
}
get heading() {
return this._headingNode.innerText;
}
set heading(text) {
this._headingNode.innerText = text;
}
get temperature () {
return Number.parseFloat(this._thermometerNode.value);
}
set temperature (temp) {
this._temperatureNode.innerText = temp;
this._thermometerNode.value = temp;
this._thermometerNode.innerText = `${temp} degrees Fahrenheit`;
this._setBackgroundForTemperature(temp);
this._setHaloForTemperature(temp);
}
_setBackgroundForTemperature (temp) {
const GRADIENT_DIFF = 5;
const top = this._colorMap.getColorAt(temp + GRADIENT_DIFF).toHexString();
const mid = this._colorMap.getColorAt(temp).toHexString();
const bottom = this._colorMap.getColorAt(temp - GRADIENT_DIFF).toHexString();
const bg = `linear-gradient(${top}, ${mid}, ${bottom})`;
this._cardNode.style.setProperty('background', bg);
}
_setHaloForTemperature (temp) {
const HEAT_HALO_CUTOFF = 80;
const COLD_HALO_CUTOFF = 32;
const HALO_SIZE_FACTOR = 0.5;
if (temp <= HEAT_HALO_CUTOFF && temp >= COLD_HALO_CUTOFF) {
this._cardNode.style.setProperty('box-shadow', 'none');
}
// Heat halos are hot red-orange; cold halos are frosty light blue.
const haloColor = temp > HEAT_HALO_CUTOFF ? '#ffbb11' : '#aaccff';
const tempIntensity = Math.max(
temp - HEAT_HALO_CUTOFF,
COLD_HALO_CUTOFF - temp
);
const haloSize = Math.ceil(tempIntensity * HALO_SIZE_FACTOR);
this._cardNode.style.setProperty(
'box-shadow',
`inset 0 0 ${haloSize}px ${haloColor}`
);
}
_makeColorMap () {
return new colorTools.GradientMap({
0: '#0011cc',
32: '#0077aa',
60: '#118811',
100: '#ff4400',
});
}
}
HighTempCard = new ThermometerCard(document.getElementById('high-temp-card'));
LowTempCard = new ThermometerCard(document.getElementById('low-temp-card'));
//-----------------------------------------------------------------------------
// Conditions card
//-----------------------------------------------------------------------------
class ConditionsCard {
constructor(cardNode) {
this._cardNode = cardNode;
this._descriptionNode = cardNode.querySelector('.description');
this._imageCreditNode = cardNode.querySelector('.image-credit');
}
setConditions({ conditions, description, address }) {
this._descriptionNode.innerText = this._editDescription(description);
const imageInfo = this._pickImage(conditions, description, address);
this._cardNode.style.setProperty(
'background-image',
`url("./img/${imageInfo.filename}")`
);
this._imageCreditNode.innerText = imageInfo.credit;
}
_editDescription(description) {
if (description.endsWith('.')) {
return description.slice(0, description.length - 1);
} else {
return description
}
}
_pickImage(conditions, description, address) {
// Get the appropriate image list
let conditionKey = 'partlyCloudy';
if (conditions.includes('Snow')) {
conditionKey = 'snow';
} else if (description.toLowerCase().includes('storm')) {
conditionKey = 'storm';
} else if (conditions.includes('Rain')) {
conditionKey = 'rain';
} else if (conditions.includes('Clear')) {
conditionKey = 'clear';
} else if (conditions.includes('Overcast') || conditions.includes('Cloudy')) {
conditionKey = 'cloudy';
}
const imageList = weatherImages[conditionKey];
// Pick a deterministically seeded element from it
const seed = this._makeDailySeed(address);
return imageList[seed % imageList.length];
}
_makeDailySeed(seedString) {
const now = new Date();
return this._makeSeedNumber(seedString) + now.getMonth() + now.getDate();
}
_makeSeedNumber(seedString) {
const BASE_CODE = 'a'.charCodeAt(0);
let num = 0;
for (let i = 0; i < seedString.length; i++) {
num += seedString.charCodeAt(i) - BASE_CODE;
}
return Math.abs(num);
}
}
TodayConditionsCard = new ConditionsCard(
document.getElementById('conditions-card'));
//-----------------------------------------------------------------------------
// Wind card
//-----------------------------------------------------------------------------
// Wind direction is in degrees clockwise, starting from north-sourced.
// 0 is from due north V (heading southward)
// 90 is from due west > (heading eastward)
// 180 is from due south ^ (heading northward)
// 270 is from due east < (heading westward)
class WindCard {
constructor(cardNode) {
this._cardNode = cardNode;
this._windSpeedNode = cardNode.querySelector('.wind-speed');
this._windArrowImage = cardNode.querySelector('.wind-arrow');
this._windArrowContainer = cardNode.querySelector('.wind-graphic');
this._windSpeed = null;
this._windDirection = null;
}
get windSpeed() {
return this._windSpeed;
}
get windDirection() {
return this._windDirection;
}
setWind({ windSpeed, windDirection }) {
this._windSpeed = windSpeed;
this._windDirection = windDirection;
this._windSpeedNode.innerText = windSpeed;
this._styleArrow(windSpeed, windDirection);
this._styleArrowContainer(windSpeed, windDirection);
this._styleCard(windSpeed, windDirection);
}
// The arrow points in the wind's direction,
// and its size depends on the wind's speed.
_styleArrow(windSpeed, windDirection) {
const MIN_ARROW_HEIGHT = 10;
const SIZE_MULTIPLIER = 5;
const arrowSize = MIN_ARROW_HEIGHT + (windSpeed * SIZE_MULTIPLIER);
this._windArrowImage.style.setProperty('height', `${arrowSize}px`);
this._windArrowImage.style.setProperty('transform', `rotate(${windDirection}deg)`);
}
// Thin stripes with just enough blur for anti-aliasing.
// Their direction lines up with the arrow, and their opacity depends on wind speed.
_styleArrowContainer(windSpeed, windDirection) {
const opacity = Math.min(0.02 * windSpeed, 1);
const gradientAngle = windDirection - 90;
const lightColor = new colorTools.Color(70, 140, 210, opacity);
const darkColor = new colorTools.Color(0, 0, 100, opacity);
const gradient = `#794186 repeating-linear-gradient(${gradientAngle}deg, ${lightColor}, ${lightColor} 6px, ${darkColor} 8px, ${darkColor} 14px, ${lightColor} 16px)`;
this._windArrowContainer.style.setProperty('background', gradient);
}
// Like the arrow container, but with larger, blurrier, and more subdued stripes.
_styleCard(windSpeed, windDirection) {
const opacity = Math.min(0.005 * windSpeed, 1);
const gradientAngle = windDirection - 90;
const lightColor = new colorTools.Color(70, 140, 210, opacity);
const darkColor = new colorTools.Color(0, 0, 100, opacity);
const gradient = `#5447a5 repeating-linear-gradient(${gradientAngle}deg, ${lightColor}, ${lightColor} 20px, ${darkColor} 30px, ${darkColor} 50px, ${lightColor} 60px)`;
this._cardNode.style.setProperty('background', gradient);
}
}
TodayWindCard = new WindCard(document.getElementById('wind-card'));
//-----------------------------------------------------------------------------
// Quote card
//-----------------------------------------------------------------------------
const QuoteCard = (function() {
const _quoteCard = document.getElementById('quote-card');
const _quoteTextNode = _quoteCard.querySelector('.quote-text');
const _quoteSourceNode = _quoteCard.querySelector('.quote-source');
const setWeather = function (weatherInfo) {
let quoteInfo = _fetchQuoteInfo(weatherInfo);
_quoteTextNode.innerText = quoteInfo.text;
_quoteSourceNode.innerText = quoteInfo.source;
if (quoteInfo.color) {
_quoteCard.style.setProperty('background-color', quoteInfo.color);
}
}
const _fetchQuoteInfo = function (weatherInfo) {
// weatherQuotes an defaultWeatherQuote are defined in weatherQuotes.js
const relevantQuotes = weatherQuotes.filter(
(quoteInfo) => _isRelevant(quoteInfo, weatherInfo)
);
if (0 == relevantQuotes.length) {
return defaultWeatherQuote;
}
const seed = Math.floor(weatherInfo.windDirection) + new Date().getDate();
console.log("seed", seed);
return relevantQuotes[seed % relevantQuotes.length];
}
const _isRelevant = function (quoteInfo, weather) {
if ('minTemp' in quoteInfo && weather.lowTemp < quoteInfo.minTemp) {
return false;
}
if ('maxTemp' in quoteInfo && weather.highTemp > quoteInfo.maxTemp) {
return false;
}
if ('minWindSpeed' in quoteInfo && weather.windSpeed < quoteInfo.minWindSpeed) {
return false;
}
if ('maxWindSpeed' in quoteInfo && weather.windSpeed > quoteInfo.maxWindSpeed) {
return false;
}
if ('condition' in quoteInfo) {
if (!weather.conditions.includes(quoteInfo.condition)) {
return false;
}
}
if ('precipitation' in quoteInfo) {
if (weather.conditions.includes('Rain') || weather.conditions.includes('Snow')) {
if (!quoteInfo.precipitation) {
return false;
}
} else {
if (quoteInfo.precipitation) {
return false;
}
}
}
// If we're here, all tests have passed.
return true;
}
return { setWeather };
}());
//=============================================================================
// Page Elements and Setup
//=============================================================================
// Page Elements
//-----------------------------------------------------------------------------
const locationInput = document.getElementById('location-input');
const fetchWeatherButton = document.getElementById('fetch-weather-button');
const errorSection = document.getElementById('error-message');
const resultsSection = document.getElementById('results');
//-----------------------------------------------------------------------------
// Event listeners
//-----------------------------------------------------------------------------
fetchWeatherButton.addEventListener('click', function(event) {
event.preventDefault();
loadWeatherResults();
});
document.addEventListener('keypress', function(event) {
if (event.key == "Enter") {
event.preventDefault();
loadWeatherResults();
}
});
//-----------------------------------------------------------------------------
// Display
//-----------------------------------------------------------------------------
async function loadWeatherResults () {
// If there's no location, ignore.
const location = locationInput.value.trim();
if (!location) {
return;
}
// Loading...
await hideElement(errorSection);
await hideElement(resultsSection);
await LoadingDisplay.show();
await sleep(500);
// Show the results when they're ready.
try {
const simpleWeather = await fetchWeatherIn(location);
await showWeatherResults(simpleWeather);
} catch (err) {
console.log(err);
await showErrorMessage();
}
}
async function showWeatherResults (simpleWeather) {
console.log("Simplified weather report:", simpleWeather);
TitleCard.location = simpleWeather.address;
HighTempCard.temperature = simpleWeather.highTemp;
LowTempCard.temperature = simpleWeather.lowTemp;
TodayWindCard.setWind(simpleWeather);
TodayConditionsCard.setConditions(simpleWeather);
QuoteCard.setWeather(simpleWeather);
await sleep(200);
await LoadingDisplay.hide();
await showElement(resultsSection);
}
async function showErrorMessage () {
await LoadingDisplay.hide();
await showElement(errorSection);
}