Merge branch 'eslint-update' into update-basemaps

This commit is contained in:
Matt Walsh committed 2026-09-18 15:09:58 -05:00
commit df3474600a
48 files changed
+804 -991

No files matched your search

+1 -1
View File
@@ -17,7 +17,7 @@
],
"runtimeArgs": [
"--autoplay-policy=no-user-gesture-required"
]
],
},
{
"name": "Data:stations",
+2 -2
View File
@@ -71,7 +71,7 @@ const webpackOptions = {
'./server/scripts/modules/progress.mjs',
'./server/scripts/modules/settings.mjs',
'./server/scripts/modules/utils/setting.mjs',
'./server/scripts/modules/icons.mjs',
'./server/scripts/modules/icons/*.mjs',
'./server/scripts/modules/utils/cache.mjs',
'./server/scripts/modules/utils/debug.mjs',
'./server/scripts/modules/utils/preload-image.mjs',
@@ -113,7 +113,7 @@ const mjsSources = [
'server/scripts/modules/currentweather.mjs',
'server/scripts/modules/almanac.mjs',
'server/scripts/modules/spc-outlook.mjs',
'server/scripts/modules/icons.mjs',
'server/scripts/modules/icons/*.mjs',
'server/scripts/modules/extendedforecast.mjs',
'server/scripts/modules/hourly.mjs',
'server/scripts/modules/hourly-graph.mjs',
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 765 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 602 B

+27 -22
View File
@@ -33,7 +33,7 @@ const categories = [
const category = categories.join(',');
const TXT_ADDRESS_SELECTOR = '#txtLocation';
const TOGGLE_FULL_SCREEN_SELECTOR = '#ToggleFullScreen';
const BNT_GET_GPS_SELECTOR = '#btnGetGps';
const BTN_GET_GPS_SELECTOR = '#btnGetGps';
const init = async () => {
// Load core data first - app cannot function without it
@@ -71,7 +71,7 @@ const init = async () => {
fullscreenButton.addEventListener('click', btnFullScreenClick);
}
const btnGetGps = document.querySelector(BNT_GET_GPS_SELECTOR);
const btnGetGps = document.querySelector(BTN_GET_GPS_SELECTOR);
btnGetGps.addEventListener('click', btnGetGpsClick);
if (!navigator.geolocation) btnGetGps.style.display = 'none';
@@ -163,7 +163,7 @@ const init = async () => {
// Auto-play logic: also play immediately if kiosk mode is enabled
const play = settings.kiosk.value || urlKioskCheckbox === 'true' ? 'true' : localStorage.getItem('play');
if (play === null || play === 'true') postMessage('navButton', 'play');
if (play === null || play === 'true') sendNavButtonMessage('navButton', 'play');
document.querySelector('#btnClearQuery').addEventListener('click', () => {
document.querySelector('#spanCity').innerHTML = '';
@@ -175,12 +175,12 @@ const init = async () => {
document.querySelector('#spanGridPoint').innerHTML = '';
localStorage.removeItem('play');
postMessage('navButton', 'play');
sendNavButtonMessage('navButton', 'play');
localStorage.removeItem('latLonQuery');
localStorage.removeItem('latLon');
localStorage.removeItem('latLonFromGPS');
document.querySelector(BNT_GET_GPS_SELECTOR).classList.remove('active');
document.querySelector(BTN_GET_GPS_SELECTOR).classList.remove('active');
});
// swipe functionality
@@ -225,7 +225,7 @@ const autocompleteOnSelect = async (suggestion) => {
const loc = data.locations[0];
if (loc) {
localStorage.removeItem('latLonFromGPS');
document.querySelector(BNT_GET_GPS_SELECTOR).classList.remove('active');
document.querySelector(BTN_GET_GPS_SELECTOR).classList.remove('active');
doRedirectToGeometry(loc.feature.geometry);
} else {
console.error('An unexpected error occurred. Please try a different search string.');
@@ -329,20 +329,21 @@ const exitFullScreenVisibilityChanges = () => {
};
const btnNavigateMenuClick = () => {
postMessage('navButton', 'menu');
sendNavButtonMessage('navButton', 'menu');
return false;
};
let currentLatLon;
const loadData = (_latLon, haveDataCallback) => {
// if latlon is provided store it locally
if (_latLon) loadData.latLon = _latLon;
if (_latLon) currentLatLon = _latLon;
// get the data
const { latLon } = loadData;
// if there's no data stop
if (!latLon) return;
if (!currentLatLon) return;
document.querySelector(TXT_ADDRESS_SELECTOR).blur();
latLonReceived(latLon, haveDataCallback);
latLonReceived(currentLatLon, haveDataCallback);
};
const swipeCallBack = (direction) => {
@@ -366,13 +367,13 @@ const btnNavigateRefreshClick = () => {
};
const btnNavigateNextClick = () => {
postMessage('navButton', 'next');
sendNavButtonMessage('navButton', 'next');
return false;
};
const btnNavigatePreviousClick = () => {
postMessage('navButton', 'previous');
sendNavButtonMessage('navButton', 'previous');
return false;
};
@@ -458,7 +459,7 @@ const documentKeydown = (e) => {
};
const btnNavigatePlayClick = () => {
postMessage('navButton', 'playToggle');
sendNavButtonMessage('navButton', 'playToggle');
return false;
};
@@ -469,17 +470,17 @@ const btnNavigateToggleScanlines = () => {
};
// post a message to the iframe
const postMessage = (type, myMessage = {}) => {
const sendNavButtonMessage = (type, myMessage = {}) => {
navMessage({ type, message: myMessage });
};
const getPosition = async () => new Promise((resolve) => {
navigator.geolocation.getCurrentPosition(resolve);
const getPosition = async () => new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject);
});
const btnGetGpsClick = async () => {
if (!navigator.geolocation) return;
const btn = document.querySelector(BNT_GET_GPS_SELECTOR);
const btn = document.querySelector(BTN_GET_GPS_SELECTOR);
// toggle first
if (btn.classList.contains('active')) {
@@ -492,10 +493,14 @@ const btnGetGpsClick = async () => {
btn.classList.add('active');
// get position
const position = await getPosition();
const { latitude, longitude } = position.coords;
getForecastFromLatLon(latitude, longitude, true);
try {
const position = await getPosition();
const { latitude, longitude } = position.coords;
getForecastFromLatLon(latitude, longitude, true);
} catch (error) {
btn.classList.remove('active');
console.error('Unable to get GPS location:', error.message);
}
};
const getForecastFromLatLon = (latitude, longitude, fromGps = false) => {
+3 -9
View File
@@ -19,10 +19,7 @@ class Almanac extends WeatherDisplay {
};
// preload the moon images
preloadImg(this.iconPaths.Full);
preloadImg(this.iconPaths.Last);
preloadImg(this.iconPaths.New);
preloadImg(this.iconPaths.First);
Object.values(this.iconPaths).forEach(preloadImg);
this.timing.totalScreens = 1;
}
@@ -53,7 +50,7 @@ class Almanac extends WeatherDisplay {
const sun = dayOffsets.map((days) => getTimes(DateTime.local().plus({ days }).toJSDate(), weatherParameters.latitude, weatherParameters.longitude));
const moonTransit = dayOffsets.map((days) => getMoonTimes(DateTime.local().plus({ days }).toJSDate(), weatherParameters.latitude, weatherParameters.longitude));
// brute force the moon phases by scanning the next 30 days
// brute force the moon phases by scanning the next 45 days
const moon = [];
// start with yesterday
let moonDate = DateTime.local().minus({ days: 1 });
@@ -89,9 +86,6 @@ class Almanac extends WeatherDisplay {
let iterations = 0;
const step = {
hours: iteration === 0 ? -1 : 0,
minutes: iteration === 1 ? 1 : 0,
seconds: iteration === 2 ? -1 : 0,
milliseconds: iteration === 3 ? 1 : 0,
};
// increasing test
@@ -115,7 +109,7 @@ class Almanac extends WeatherDisplay {
return this.getMoonTransition(threshold, phaseName, moonDate, iteration + 1);
}
iterations += 1;
} while (iterations < 1000);
} while (iterations < 100);
return { phase: phaseName, date: moonDate };
}
+29 -36
View File
@@ -4,7 +4,7 @@ import preloadImg from './utils/preload-image.mjs';
import { safeJson } from './utils/fetch.mjs';
import { directionToNSEW } from './utils/calc.mjs';
import { locationCleanup } from './utils/string.mjs';
import { getLargeIcon } from './icons.mjs';
import largeIcon from './icons/large.mjs';
import WeatherDisplay from './weatherdisplay.mjs';
import { registerDisplay } from './navigation.mjs';
import augmentObservationWithMetar from './utils/metar.mjs';
@@ -34,6 +34,30 @@ class CurrentWeather extends WeatherDisplay {
let observations;
let station;
const metarFields = [
{ name: 'temperature', check: (orig, metar) => orig.temperature?.value === null && metar.temperature?.value !== null },
{ name: 'windSpeed', check: (orig, metar) => orig.windSpeed?.value === null && metar.windSpeed?.value !== null },
{ name: 'windDirection', check: (orig, metar) => orig.windDirection?.value === null && metar.windDirection?.value !== null },
{ name: 'windGust', check: (orig, metar) => orig.windGust?.value === null && metar.windGust?.value !== null },
{ name: 'dewpoint', check: (orig, metar) => orig.dewpoint?.value === null && metar.dewpoint?.value !== null },
{ name: 'barometricPressure', check: (orig, metar) => orig.barometricPressure?.value === null && metar.barometricPressure?.value !== null },
{ name: 'relativeHumidity', check: (orig, metar) => orig.relativeHumidity?.value === null && metar.relativeHumidity?.value !== null },
{ name: 'visibility', check: (orig, metar) => orig.visibility?.value === null && metar.visibility?.value !== null },
{ name: 'ceiling', check: (orig, metar) => orig.cloudLayers?.[0]?.base?.value === null && metar.cloudLayers?.[0]?.base?.value !== null },
];
// test data quality - check required fields and allow one optional field to be missing
const requiredFields = [
{ name: 'temperature', check: (props) => props.temperature?.value === null, required: true },
{ name: 'textDescription', check: (props) => props.textDescription === null || props.textDescription === '', required: true },
{ name: 'windSpeed', check: (props) => props.windSpeed?.value === null, required: false },
{ name: 'dewpoint', check: (props) => props.dewpoint?.value === null, required: false },
{ name: 'barometricPressure', check: (props) => props.barometricPressure?.value === null, required: false },
{ name: 'visibility', check: (props) => props.visibility?.value === null, required: false },
{ name: 'relativeHumidity', check: (props) => props.relativeHumidity?.value === null, required: false },
{ name: 'ceiling', check: (props) => props.cloudLayers?.[0]?.base?.value === null, required: false },
];
// station number counter
let stationNum = 0;
while (!observations && stationNum < stations.length) {
@@ -63,35 +87,12 @@ class CurrentWeather extends WeatherDisplay {
// Attempt making observation data usable with METAR data
const originalData = { ...candidateObservation.features[0].properties };
candidateObservation.features[0].properties = augmentObservationWithMetar(candidateObservation.features[0].properties);
const metarFields = [
{ name: 'temperature', check: (orig, metar) => orig.temperature?.value === null && metar.temperature?.value !== null },
{ name: 'windSpeed', check: (orig, metar) => orig.windSpeed?.value === null && metar.windSpeed?.value !== null },
{ name: 'windDirection', check: (orig, metar) => orig.windDirection?.value === null && metar.windDirection?.value !== null },
{ name: 'windGust', check: (orig, metar) => orig.windGust?.value === null && metar.windGust?.value !== null },
{ name: 'dewpoint', check: (orig, metar) => orig.dewpoint?.value === null && metar.dewpoint?.value !== null },
{ name: 'barometricPressure', check: (orig, metar) => orig.barometricPressure?.value === null && metar.barometricPressure?.value !== null },
{ name: 'relativeHumidity', check: (orig, metar) => orig.relativeHumidity?.value === null && metar.relativeHumidity?.value !== null },
{ name: 'visibility', check: (orig, metar) => orig.visibility?.value === null && metar.visibility?.value !== null },
{ name: 'ceiling', check: (orig, metar) => orig.cloudLayers?.[0]?.base?.value === null && metar.cloudLayers?.[0]?.base?.value !== null },
];
const augmentedData = candidateObservation.features[0].properties;
const metarReplacements = metarFields.filter((field) => field.check(originalData, augmentedData)).map((field) => field.name);
if (debugFlag('currentweather') && metarReplacements.length > 0) {
console.log(`Current Conditions for station ${stationId} were augmented with METAR data for ${metarReplacements.join(', ')}`);
}
// test data quality - check required fields and allow one optional field to be missing
const requiredFields = [
{ name: 'temperature', check: (props) => props.temperature?.value === null, required: true },
{ name: 'textDescription', check: (props) => props.textDescription === null || props.textDescription === '', required: true },
{ name: 'windSpeed', check: (props) => props.windSpeed?.value === null, required: false },
{ name: 'dewpoint', check: (props) => props.dewpoint?.value === null, required: false },
{ name: 'barometricPressure', check: (props) => props.barometricPressure?.value === null, required: false },
{ name: 'visibility', check: (props) => props.visibility?.value === null, required: false },
{ name: 'relativeHumidity', check: (props) => props.relativeHumidity?.value === null, required: false },
{ name: 'ceiling', check: (props) => props.cloudLayers?.[0]?.base?.value === null, required: false },
];
// Use enhanced observation with MapClick fallback
// eslint-disable-next-line no-await-in-loop
const enhancedResult = await enhanceObservationWithMapClick(augmentedData, {
@@ -106,15 +107,7 @@ class CurrentWeather extends WeatherDisplay {
candidateObservation.features[0].properties = enhancedResult.data;
const { missingFields } = enhancedResult;
const missingRequired = missingFields.filter((fieldName) => {
const field = requiredFields.find((f) => f.name === fieldName && f.required);
return !!field;
});
const missingOptional = missingFields.filter((fieldName) => {
const field = requiredFields.find((f) => f.name === fieldName && !f.required);
return !!field;
});
const { missingRequired, missingOptional } = enhancedResult;
const missingOptionalCount = missingOptional.length;
// Check final data quality
@@ -168,7 +161,7 @@ class CurrentWeather extends WeatherDisplay {
// preload the icon if available
if (observations.features[0].properties.icon) {
const iconResult = getLargeIcon(observations.features[0].properties.icon);
const iconResult = largeIcon(observations.features[0].properties.icon);
if (iconResult) {
preloadImg(iconResult);
}
@@ -195,7 +188,7 @@ class CurrentWeather extends WeatherDisplay {
// get location (city name) from StationInfo if available (allows for overrides)
// longer name allowed if in wide-enhanced
const locationLimit = (settings.wide?.value && settings.enhanced?.value) ? 25 : 20;
const location = (StationInfo[this.data.station.properties.stationIdentifier]?.city ?? locationCleanup(this.data.station.properties.name)).substr(0, locationLimit);
const location = (StationInfo[this.data.station.properties.stationIdentifier]?.city ?? locationCleanup(this.data.station.properties.name)).substring(0, locationLimit);
const fill = {
temp: this.data.Temperature + String.fromCharCode(176),
@@ -306,7 +299,7 @@ const parseData = (data) => {
data.Humidity = Math.round(observations.relativeHumidity.value);
// Get the large icon, but provide a fallback if it returns false
const iconResult = getLargeIcon(observations.icon);
const iconResult = largeIcon(observations.icon);
data.Icon = iconResult || observations.icon; // Use original icon if getLargeIcon returns false
data.PressureDirection = '';
+39 -29
View File
@@ -91,9 +91,9 @@ const drawScreen = async () => {
// add the hazards if on screen 0
if (screenIndex === 0) {
const hazards = await getHazards();
if (hazards && hazards.length > 0) {
scrollData.hazards = hazards;
const hazardsData = await getHazards();
if (hazardsData && hazardsData.length > 0) {
scrollData.hazards = hazardsData;
}
}
@@ -103,7 +103,7 @@ const drawScreen = async () => {
const thisScreen = workingScreens[screenIndex](scrollData, parameters);
// update classes on the scroll area
mainScroll.classList.forEach((cls) => {
Array.from(mainScroll.classList).forEach((cls) => {
if (cls !== 'scroll') mainScroll.classList.remove(cls);
});
thisScreen?.classes?.forEach((cls) => mainScroll.classList.add(cls));
@@ -198,7 +198,13 @@ let workingScreens = [...baseScreens, ...additionalScreens];
// internal draw function with preset parameters
const drawCondition = (text) => {
// re-apply the "typing" effect
fixedScroll.classList.remove('reveal');
fixedScroll.innerHTML = text;
// force the reflow of the element
// eslint-disable-next-line no-void
void fixedScroll.offsetWidth;
fixedScroll.classList.add('reveal');
setHeader('');
};
@@ -221,41 +227,45 @@ const addScreen = (screen, keepBase = true) => {
};
const drawScrollCondition = (screen) => {
// remove the reveal class
fixedScroll.classList.remove('reveal');
// create the scroll element
const scrollElement = document.createElement('div');
scrollElement.classList.add('scroll-area');
scrollElement.innerHTML = screen.text;
// add it to the page to get the width
fixedScroll.innerHTML = scrollElement.outerHTML;
// grab the width
const { scrollWidth, clientWidth } = document.querySelector('#container>.scroll .fixed .scroll-area');
// calculate the scroll distance and set a minimum scroll
const scrollDistance = Math.max(scrollWidth - clientWidth, 0);
// calculate the scroll time (scaled by global speed setting), minimum 2s (4s when added to start and end delays)
const scrollTime = Math.max((scrollDistance / SCROLL_SPEED) * settings.speed.value, 2);
// add 1 second pause at the end of the scroll animation
const endPauseTime = 1.0;
const totalAnimationTime = scrollTime + endPauseTime;
// calculate total on-screen time: animation time + start delay + end pause
const startDelayTime = 1.0; // setTimeout delay below
const totalDisplayTime = totalAnimationTime + startDelayTime;
nextUpdate = secondsToTicks(totalDisplayTime);
// update the element with initial position and transition
scrollElement.style.transform = 'translateX(0px)';
scrollElement.style.transition = `transform ${scrollTime.toFixed(1)}s linear`;
scrollElement.style.willChange = 'transform'; // Hint to browser for hardware acceleration
scrollElement.style.backfaceVisibility = 'hidden'; // Force hardware acceleration
scrollElement.style.perspective = '1000px'; // Enable 3D rendering context
scrollElement.classList.add('reveal');
// empty and attach the new element
fixedScroll.innerHTML = '';
fixedScroll.append(scrollElement.cloneNode(true));
fixedScroll.append(scrollElement);
// start the scroll after the specified delay
const startDelayTime = 1.0 * settings.speed.value; // setTimeout delay below
setTimeout(() => {
// this must be calculated after the delay because the .reveal class collapses width to 0 temporarily
scrollElement.classList.remove('reveal');
const { scrollWidth, clientWidth } = scrollElement;
// calculate the scroll distance and set a minimum scroll
const scrollDistance = Math.max(scrollWidth - clientWidth, 0);
// calculate the scroll time (scaled by global speed setting), minimum 2s (4s when added to start and end delays)
const scrollTime = Math.max((scrollDistance / SCROLL_SPEED) * settings.speed.value, 2);
// add 1 second pause at the end of the scroll animation
const endPauseTime = 1.0;
const totalAnimationTime = scrollTime + endPauseTime;
// calculate total on-screen time: animation time + start delay + end pause
const totalDisplayTime = totalAnimationTime + startDelayTime;
nextUpdate = secondsToTicks(totalDisplayTime);
// update the element with initial position and transition
scrollElement.style.transform = 'translateX(0px)';
scrollElement.style.transition = `transform ${scrollTime.toFixed(1)}s linear`;
scrollElement.style.willChange = 'transform'; // Hint to browser for hardware acceleration
scrollElement.style.backfaceVisibility = 'hidden'; // Force hardware acceleration
scrollElement.style.perspective = '1000px'; // Enable 3D rendering context
// change the transform to trigger the scroll
document.querySelector('#container>.scroll .fixed .scroll-area').style.transform = `translateX(-${scrollDistance.toFixed(0)}px)`;
scrollElement.style.transform = `translateX(-${scrollDistance.toFixed(0)}px)`;
}, startDelayTime * 1000);
};
@@ -5,6 +5,7 @@ let firstRun = true;
// change of enable handler
const changeEnable = (newValue) => {
if (firstRun) return;
let newDisplay;
if (newValue) {
// add the text to the scroll
@@ -17,7 +18,7 @@ const changeEnable = (newValue) => {
// hide the string entry
newDisplay = 'none';
}
const stringEntry = document.getElementById('settings-customText-string');
const stringEntry = customText.element;
if (stringEntry) {
stringEntry.style.display = newDisplay;
}
@@ -31,6 +32,7 @@ const parseText = (textInput) => {
// test validity
if (textInput === undefined || textInput === '') {
resetScroll();
return;
}
// split the text at pipe characters
+12 -9
View File
@@ -4,7 +4,7 @@
import STATUS from './status.mjs';
import { safeJson } from './utils/fetch.mjs';
import { DateTime } from '../vendor/auto/luxon.mjs';
import { getLargeIcon } from './icons.mjs';
import largeIcon from './icons/large.mjs';
import preloadImg from './utils/preload-image.mjs';
import WeatherDisplay from './weatherdisplay.mjs';
import { registerDisplay } from './navigation.mjs';
@@ -36,7 +36,7 @@ class ExtendedForecast extends WeatherDisplay {
try {
// request us or si units using centralized safe handling
this.data = await safeJson(this.weatherParameters.forecast, {
const data = await safeJson(this.weatherParameters.forecast, {
data: {
units: settings.units.value,
},
@@ -45,12 +45,15 @@ class ExtendedForecast extends WeatherDisplay {
});
// if there's no new data and no previous data, fail
if (!this.data) {
// console.warn(`Unable to get extended forecast for ${this.weatherParameters.latitude},${this.weatherParameters.longitude} in ${this.weatherParameters.state}`);
if (!data) {
console.warn(`Unable to get extended forecast for ${this.weatherParameters.latitude},${this.weatherParameters.longitude} in ${this.weatherParameters.state}`);
if (this.isEnabled) this.setStatus(STATUS.failed);
return;
}
// parse the data
this.data = parse(data.properties.periods, this.weatherParameters.forecast);
// we only get here if there was data (new or existing)
this.screenIndex = 0;
this.setStatus(STATUS.loaded);
@@ -68,7 +71,7 @@ class ExtendedForecast extends WeatherDisplay {
// determine bounds
// grab the first three or second set of three array elements
const forecast = parse(this.data.properties.periods, this.weatherParameters.forecast).slice(0 + this.perPage * this.screenIndex, this.perPage + this.screenIndex * this.perPage);
const forecast = this.data.slice(0 + this.perPage * this.screenIndex, this.perPage + this.screenIndex * this.perPage);
// create each day template
const days = forecast.map((Day) => {
@@ -142,7 +145,7 @@ const parse = (fullForecast, forecastUrl) => {
if (period.isDaytime) {
// day time is the high temperature
fDay.high = period.temperature;
fDay.icon = getLargeIcon(period.icon);
fDay.icon = largeIcon(period.icon);
fDay.text = shortenExtendedForecastText(period.shortForecast);
fDay.dayName = DateTime.fromISO(period.startTime).startOf('day').toLocaleString({ weekday: 'short' });
// preload the icon
@@ -182,18 +185,18 @@ const shortenExtendedForecastText = (long) => {
const short = regexList.reduce((working, [regex, replace]) => working.replace(regex, replace), long);
let conditions = short.split(' ');
if (short.indexOf('then') !== -1) {
if (short.indexOf(' then ') !== -1) {
conditions = short.split(' then ');
conditions = conditions[1].split(' ');
}
let short1 = conditions[0].substr(0, 10);
let short1 = conditions[0].substring(0, 10);
let short2 = '';
if (conditions[1]) {
if (short1.endsWith('.')) {
short1 = short1.replace(/\./, '');
} else {
short2 = conditions[1].substr(0, 10);
short2 = conditions[1].substring(0, 10);
}
if (short2 === 'Blowing') {
+42 -149
View File
@@ -1,10 +1,9 @@
// hourly forecast list
// hazards (alerts, warnings, etc)
import STATUS from './status.mjs';
import { safeJson } from './utils/fetch.mjs';
import WeatherDisplay from './weatherdisplay.mjs';
import ScrollWeatherDisplay from './scroll-weather-display.mjs';
import { registerDisplay } from './navigation.mjs';
import calculateScrollTiming from './utils/scroll-timing.mjs';
import { debugFlag } from './utils/debug.mjs';
const hazardLevels = {
@@ -20,12 +19,17 @@ const hazardModifiers = {
// A cheap, stable signature of the content about to be rendered. Alert ids alone are not enough:
// an alert can be reissued under the same id with updated text, which changes the rendered height.
const contentSignature = (alerts) => alerts.map((alert) => `${alert.id}|${alert.properties.event}|${alert.properties.description ?? ''}`).join('\u0000');
const rowsSignature = (alerts) => alerts.map((alert) => `${alert.id}|${alert.properties.event}|${alert.properties.description ?? ''}`).join('\u0000');
class Hazards extends WeatherDisplay {
class Hazards extends ScrollWeatherDisplay {
constructor(navId, elemId, defaultActive) {
// special height and width for scrolling
super(navId, elemId, 'Hazards', defaultActive);
super(navId, elemId, 'Hazards', defaultActive, {
linesSelector: '.hazard-lines',
scrollTiming: {
finalPause: 2.0, // shorter final pause for hazards
},
});
this.showOnProgress = false;
this.okToDrawCurrentConditions = false;
@@ -38,23 +42,6 @@ class Hazards extends WeatherDisplay {
// take note of the already-shown alert ids
this.viewedAlerts = new Set();
this.viewedGetCount = 0;
// cache for scroll calculations
// This cache is essential because baseCountChange() is called 25 times per second (every 40ms)
// during scrolling. Hazard scrolls can vary greatly in length depending on active alerts, but
// without caching we'd perform hundreds of expensive DOM layout queries during each scroll cycle.
// The cache reduces this to one calculation when content changes, then reuses cached values to try
// and get smoother scrolling.
this.scrollCache = {
displayHeight: 0,
contentHeight: 0,
maxOffset: 0,
hazardLines: null,
};
// signature of the content currently rendered into the DOM, so a refresh that returns
// identical alerts can skip the rebuild entirely
this.lastContentSignature = null;
}
async getData(weatherParameters, refresh) {
@@ -66,16 +53,16 @@ class Hazards extends WeatherDisplay {
// auto reload must be set up specifically for hazards in case it is disabled via checkbox (for the bottom line scroll)
if (this.autoRefreshHandle === null) this.setAutoReload();
const alert = this.checkbox.querySelector('.alert');
alert.classList.remove('show');
// if not a refresh (new site), all alerts are new
if (!refresh) {
this.viewedGetCount = 0;
this.viewedAlerts.clear();
}
try {
const alert = this.checkbox.querySelector('.alert');
alert.classList.remove('show');
// if not a refresh (new site), all alerts are new
if (!refresh) {
this.viewedGetCount = 0;
this.viewedAlerts.clear();
}
// get the forecast using centralized safe handling
const url = new URL('https://api.weather.gov/alerts/active');
url.searchParams.append('point', `${this.weatherParameters.latitude},${this.weatherParameters.longitude}`);
@@ -89,11 +76,10 @@ class Hazards extends WeatherDisplay {
this.data = [];
} else {
const allUnsortedAlerts = alerts.features ?? [];
const unsortedAlerts = allUnsortedAlerts.slice(0, 5);
const hasImmediate = unsortedAlerts.reduce((acc, hazard) => acc || hazard.properties.urgency === 'Immediate', false);
const sortedAlerts = unsortedAlerts.sort((a, b) => (calcSeverity(b.properties.severity, b.properties.event)) - (calcSeverity(a.properties.severity, a.properties.event)));
const hasImmediate = allUnsortedAlerts.reduce((acc, hazard) => acc || hazard.properties.urgency === 'Immediate', false);
const sortedAlerts = allUnsortedAlerts.sort((a, b) => (calcSeverity(b.properties.severity, b.properties.event)) - (calcSeverity(a.properties.severity, a.properties.event)));
const filteredAlerts = sortedAlerts.filter((hazard) => hazard.properties.severity !== 'Unknown' && (!hasImmediate || (hazard.properties.urgency === 'Immediate')));
this.data = filteredAlerts;
this.data = filteredAlerts.slice(0, 5);
}
// every 10 times through the get process (10 minutes), reset the viewed messages
@@ -111,11 +97,6 @@ class Hazards extends WeatherDisplay {
// show alert indicator
if (unViewed > 0) alert.classList.add('show');
// draw the canvas to calculate the new timings and activate hazards in the slide deck again
// unless this has been disabled
if (this.isEnabled) {
this.drawLongCanvas();
}
} catch (error) {
console.error(`Unexpected Active Alerts error: ${error.message}`);
if (this.isEnabled) this.setStatus(STATUS.failed);
@@ -131,123 +112,35 @@ class Hazards extends WeatherDisplay {
return;
}
this.drawLongCanvas();
}
async drawLongCanvas() {
// get the list element and populate
const list = this.elem.querySelector('.hazard-lines');
// filter viewed alerts
const unViewed = this.data.filter((data) => !this.viewedAlerts.has(data.id));
// If the content is identical to what is already rendered, leave the DOM and the scroll
// position alone. Hazards refresh every 60 seconds but a long multi-alert scroll can run for
// several minutes, so rebuilding on every refresh would restart it from the top and it would
// never reach the end. The populated-list check means an empty list is always rebuilt.
const signature = contentSignature(unViewed);
if (signature === this.lastContentSignature && list.children.length > 0) {
this.setStatus(STATUS.loaded);
return;
}
this.lastContentSignature = signature;
list.innerHTML = '';
const lines = unViewed.map((data) => {
const fillValues = {};
const description = data.properties.description
.replaceAll('\n\n', '<br/><br/>')
.replaceAll('\n', ' ')
.replace(/(\S)\.\.\.(\S)/g, '$1... $2'); // Add space after ... when surrounded by non-whitespace to improve text-wrappability
fillValues['hazard-text'] = `${data.properties.event}<br/><br/>${description}<br/><br/><br/><br/>`; // Add some padding to scroll off the bottom a bit
return this.fillTemplate('hazard', fillValues);
});
list.append(...lines);
// The scroll cache is invalidated by comparing element identity, but .hazard-lines is
// persistent - only its children are replaced above - and displayHeight is a fixed value
// from css. Both conditions in baseCountChange() therefore stay false after the first
// measurement, so maxOffset keeps the height of whatever content was measured first and
// clamps the scroll partway through anything taller, leaving it frozen there. Invalidate
// explicitly so the next base count re-measures.
this.scrollCache.displayHeight = 0;
this.scrollCache.hazardLines = null;
// new content scrolls from the top
this.navBaseCount = 0;
// no alerts, skip this display by setting timing to zero
if (lines.length === 0) {
this.setStatus(STATUS.loaded);
this.timing.totalScreens = 0;
this.setStatus(STATUS.loaded);
return;
}
// update timing
this.setTiming(list);
this.setStatus(STATUS.loaded);
}
setTiming(list) {
const container = this.elem.querySelector('.main');
const timingConfig = calculateScrollTiming(list, container, {
finalPause: 2.0, // shorter final pause for hazards
});
// Apply the calculated timing
this.timing.baseDelay = timingConfig.baseDelay;
this.timing.delay = timingConfig.delay;
this.scrollTiming = timingConfig.scrollTiming;
this.calcNavTiming();
// alerts that have already been scrolled through are not shown again until the next reset
scrollRows() {
return this.data.filter((data) => !this.viewedAlerts.has(data.id));
}
drawCanvas() {
super.drawCanvas();
this.finishDraw();
// Alert ids alone are not enough: an alert can be reissued under the same id with updated
// text, which changes the rendered height. Hazards refresh every 60 seconds but a long
// multi-alert scroll can run for several minutes, so rebuilding on every refresh would
// restart it from the top and it would never reach the end.
// eslint-disable-next-line class-methods-use-this
contentSignature(alerts) {
return rowsSignature(alerts);
}
showCanvas() {
// special to hourly to draw the remainder of the canvas
this.drawCanvas();
super.showCanvas();
}
buildRow(data) {
// protect against a null description
if (!data.properties.description) return false;
const fillValues = {};
const description = data.properties.description
.replaceAll('\n\n', '<br/><br/>')
.replaceAll('\n', ' ')
.replace(/(\S)\.\.\.(\S)/g, '$1... $2'); // Add space after ... when surrounded by non-whitespace to improve text-wrappability
// screen index change callback just runs the base count callback
screenIndexChange() {
this.baseCountChange(this.navBaseCount);
}
fillValues['hazard-text'] = `${data.properties.event}<br/><br/>${description}<br/><br/><br/><br/>`; // Add some padding to scroll off the bottom a bit
// base count change callback
baseCountChange(count) {
// get the hazard lines element and cache measurements if needed
const hazardLines = this.elem.querySelector('.hazard-lines');
if (!hazardLines) return;
// update cache if needed (when content changes or first run)
if (this.scrollCache.hazardLines !== hazardLines || this.scrollCache.displayHeight === 0) {
this.scrollCache.displayHeight = this.elem.querySelector('.main').offsetHeight;
this.scrollCache.contentHeight = hazardLines.offsetHeight;
this.scrollCache.maxOffset = Math.max(0, this.scrollCache.contentHeight - this.scrollCache.displayHeight);
this.scrollCache.hazardLines = hazardLines;
// Set up hardware acceleration on the hazard lines element
hazardLines.style.willChange = 'transform';
hazardLines.style.backfaceVisibility = 'hidden';
}
// calculate scroll offset and don't go past end
let offsetY = Math.min(this.scrollCache.maxOffset, (count - this.scrollTiming.initialCounts) * this.scrollTiming.pixelsPerCount);
// don't let offset go negative
if (offsetY < 0) offsetY = 0;
// use transform instead of scrollTo for hardware acceleration
hazardLines.style.transform = `translateY(-${Math.round(offsetY)}px)`;
return this.fillTemplate('hazard', fillValues);
}
// after we roll through the hazards once, don't display again until the next refresh (10 minutes)
+15 -24
View File
@@ -59,6 +59,7 @@ class HourlyGraph extends WeatherDisplay {
}
async getData(weatherParameters, refresh) {
// called deliberately with undefined because hourly.mjs is the source of data
if (!super.getData(undefined, refresh)) return;
const data = await getHourlyData(() => this.stillWaiting());
@@ -91,12 +92,13 @@ class HourlyGraph extends WeatherDisplay {
}
drawCanvas() {
super.drawCanvas();
// get scaling parameters
const { dataLength, available } = scaling();
// get the image
if (!this.image) this.image = this.elem.querySelector('.chart img');
if (!this.portraitImage) this.portraitImage = this.elem.querySelector('.bottom .chart img');
if (!this.image) this.image = this.elem.querySelector('.chart canvas');
if (!this.portraitImage) this.portraitImage = this.elem.querySelector('.bottom .chart canvas');
// set up images
this.image.width = available.width;
@@ -105,10 +107,9 @@ class HourlyGraph extends WeatherDisplay {
this.portraitImage.height = available.height;
// get context
const canvas = document.createElement('canvas');
canvas.width = available.width;
canvas.height = available.height;
const ctx = canvas.getContext('2d');
this.image.width = available.width;
this.image.height = available.height;
const ctx = this.image.getContext('2d');
ctx.imageSmoothingEnabled = false;
// set the canvas for each graph to the top one by default
@@ -120,12 +121,10 @@ class HourlyGraph extends WeatherDisplay {
];
// if in portrait-enhanced, change out the second two contexts with a second canvas
let portraitCanvas;
if (settings.portrait?.value && settings.enhanced?.value) {
portraitCanvas = document.createElement('canvas');
portraitCanvas.width = available.width;
portraitCanvas.height = available.height;
const portraitCtx = portraitCanvas.getContext('2d');
this.portraitImage.width = available.width;
this.portraitImage.height = available.height;
const portraitCtx = this.portraitImage.getContext('2d');
portraitCtx.imageSmoothingEnabled = false;
contexts[2] = portraitCtx;
@@ -135,7 +134,7 @@ class HourlyGraph extends WeatherDisplay {
// calculate time scale
const timeScale = calcScale(0, 5, this.data.temperature.length - 1, available.width);
const timeStep = this.data.temperature.length / (dataLength.xTicks);
const startTime = DateTime.now().startOf('hour');
const startTime = DateTime.now().setZone(timeZone()).startOf('hour');
// there are two x axes in portrait
chartAreas.forEach((area) => {
@@ -198,19 +197,10 @@ class HourlyGraph extends WeatherDisplay {
this.elem.querySelector('.y-axis .l-3').innerHTML = (midScale1 + degree).substring(0, 3);
this.elem.querySelector('.y-axis .l-4').innerHTML = (minScale + degree).substring(0, 3);
// set the image source
this.image.src = canvas.toDataURL();
// if a portrait canvas was created set that image as well
if (portraitCanvas) {
this.portraitImage.src = portraitCanvas.toDataURL();
}
// change the units in the header
this.elem.querySelector('.temperature').innerHTML = `Temperature ${String.fromCharCode(176)}${this.data.temperatureUnit}`;
this.elem.querySelector('.dewpoint').innerHTML = `Dewpoint ${String.fromCharCode(176)}${this.data.temperatureUnit}`;
super.drawCanvas();
this.finishDraw();
}
}
@@ -231,7 +221,7 @@ const drawPath = (path, ctx, options) => {
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.lineWidth = (options?.lineWidth ?? 2) + 2;
ctx.moveTo(path[0][0], path[0][1]);
ctx.moveTo(path[0][0], path[0][1] + 2);
path.slice(1).forEach((point) => ctx.lineTo(point[0], point[1] + 2));
ctx.stroke();
@@ -246,12 +236,13 @@ const drawPath = (path, ctx, options) => {
// format as 1p, 12a, etc.
const formatTime = (time, prev) => {
// apply the time zone
const ts = time.setZone(timeZone());
// if the day of the week changes, show the day of the week in the label
let format = 'ha';
if (prev.weekday !== time.weekday) format = 'ccc ha';
const ts = time.setZone(timeZone());
return {
ts,
formatted: ts.toFormat(format).slice(0, -1),
+51 -143
View File
@@ -4,42 +4,26 @@ import STATUS from './status.mjs';
import { DateTime, Interval, Duration } from '../vendor/auto/luxon.mjs';
import { safeJson } from './utils/fetch.mjs';
import { temperature as temperatureUnit, windSpeed as windUnit } from './utils/units.mjs';
import { getHourlyIcon } from './icons.mjs';
import hourlyIcon from './icons/hourly.mjs';
import { directionToNSEW } from './utils/calc.mjs';
import WeatherDisplay from './weatherdisplay.mjs';
import ScrollWeatherDisplay from './scroll-weather-display.mjs';
import { registerDisplay, timeZone } from './navigation.mjs';
import getSun from './almanac.mjs';
import calculateScrollTiming from './utils/scroll-timing.mjs';
import { debugFlag } from './utils/debug.mjs';
// A cheap, stable signature of the content about to be rendered. The starting hour is included
// because the row labels are derived from the current time, so an hour rollover changes the display
// even when every forecast value is unchanged.
const contentSignature = (startingHour, rows) => [
startingHour.startOf('hour').toISO(),
...rows.map((row) => `${row.temperature}|${row.apparentTemperature}|${row.windSpeed}|${row.windDirection}|${row.icon}`),
// A cheap, stable signature of the content about to be rendered. The hour is included per row
// because the row labels are derived from the current time, so an hour rollover changes the
// display even when every forecast value is unchanged.
const rowsSignature = (rows) => [
...rows.map((row) => `${row.hour.toISO()}|${row.temperature}|${row.apparentTemperature}|${row.windSpeed}|${row.windDirection}|${row.icon}`),
].join('\u0000');
class Hourly extends WeatherDisplay {
class Hourly extends ScrollWeatherDisplay {
constructor(navId, elemId, defaultActive) {
// special height and width for scrolling
super(navId, elemId, 'Hourly Forecast', defaultActive);
// cache for scroll calculations
// This cache is essential because baseCountChange() is called 25 times per second (every 40ms)
// during scrolling. Without caching, we'd perform hundreds of expensive DOM layout queries during
// the full scroll cycle. The cache reduces this to one calculation when content changes, then
// reuses cached values to try and get smoother scrolling.
this.scrollCache = {
displayHeight: 0,
contentHeight: 0,
maxOffset: 0,
hourlyLines: null,
};
// signature of the content currently rendered into the DOM, so a refresh that returns
// identical rows can skip the rebuild entirely
this.lastContentSignature = null;
super(navId, elemId, 'Hourly Forecast', defaultActive, {
linesSelector: '.hourly-lines',
});
}
async getData(weatherParameters, refresh) {
@@ -80,119 +64,55 @@ class Hourly extends WeatherDisplay {
}
}
async drawLongCanvas() {
// get the list element and populate
const list = this.elem.querySelector('.hourly-lines');
const startingHour = DateTime.local().setZone(timeZone());
// shorten to 24 hours
const shortData = this.data.slice(0, 24);
// if the content is identical to what is already rendered, leave the DOM and the scroll
// position alone rather than rebuilding and restarting an in-progress scroll
const signature = contentSignature(startingHour, shortData);
if (signature === this.lastContentSignature && list.children.length > 0) return;
this.lastContentSignature = signature;
list.innerHTML = '';
const lines = shortData.map((data, index) => {
const fillValues = {};
// hour
const hour = startingHour.plus({ hours: index });
fillValues.hour = hour.toLocaleString({ weekday: 'short', hour: 'numeric' });
// temperatures, convert to strings with no decimal
const temperature = data.temperature.toString().padStart(3);
const feelsLike = data.apparentTemperature.toString().padStart(3);
fillValues.temp = temperature;
// apparent temperature is color coded if different from actual temperature (after fill is applied)
fillValues.like = feelsLike;
// wind
fillValues.wind = 'Calm';
if (data.windSpeed > 0) {
const windSpeed = Math.round(data.windSpeed).toString();
fillValues.wind = data.windDirection + (Array(6 - data.windDirection.length - windSpeed.length).join(' ')) + windSpeed;
}
// image
fillValues.icon = { type: 'img', src: data.icon };
const filledRow = this.fillTemplate('hourly-row', fillValues);
// alter the color of the feels like column to reflect wind chill or heat index
if (data.apparentTemperature < data.temperature) {
filledRow.querySelector('.like').classList.add('wind-chill');
} else if (feelsLike > temperature) {
filledRow.querySelector('.like').classList.add('heat-index');
}
return filledRow;
});
list.append(...lines);
// The scroll cache is invalidated by comparing element identity, but .hourly-lines is
// persistent - only its children are replaced above - and displayHeight is a fixed value
// from css. Both conditions in baseCountChange() therefore stay false after the first
// measurement, so maxOffset keeps the height of whatever content was measured first and
// clamps the scroll partway through anything taller, leaving it frozen there. Invalidate
// explicitly so the next base count re-measures.
this.scrollCache.displayHeight = 0;
this.scrollCache.hourlyLines = null;
// new content scrolls from the top
this.navBaseCount = 0;
// update timing based on actual content
this.setTiming(list);
// shorten to 24 hours, and attach the hour each row represents so the label and the
// signature stay in agreement. truncating to the hour keeps the signature stable between
// refreshes within the same hour; the label only renders the weekday and hour anyway.
scrollRows() {
const startingHour = DateTime.local().setZone(timeZone()).startOf('hour');
return this.data.slice(0, 24).map((data, index) => ({
...data,
hour: startingHour.plus({ hours: index }),
}));
}
drawCanvas() {
super.drawCanvas();
this.finishDraw();
// eslint-disable-next-line class-methods-use-this
contentSignature(rows) {
return rowsSignature(rows);
}
showCanvas() {
// special to hourly to draw the remainder of the canvas
this.drawCanvas();
super.showCanvas();
}
buildRow(data) {
const fillValues = {};
// hour
fillValues.hour = data.hour.toLocaleString({ weekday: 'short', hour: 'numeric' });
// screen index change callback just runs the base count callback
screenIndexChange() {
this.baseCountChange(this.navBaseCount);
}
// temperatures, convert to strings with no decimal
const temperature = data.temperature.toString().padStart(3);
const feelsLike = data.apparentTemperature.toString().padStart(3);
fillValues.temp = temperature;
// base count change callback
baseCountChange(count) {
// get the hourly lines element and cache measurements if needed
const hourlyLines = this.elem.querySelector('.hourly-lines');
if (!hourlyLines) return;
// apparent temperature is color coded if different from actual temperature (after fill is applied)
fillValues.like = feelsLike;
// update cache if needed (when content changes or first run)
if (this.scrollCache.hourlyLines !== hourlyLines || this.scrollCache.displayHeight === 0) {
this.scrollCache.displayHeight = this.elem.querySelector('.main').offsetHeight;
this.scrollCache.contentHeight = hourlyLines.offsetHeight;
this.scrollCache.maxOffset = Math.max(0, this.scrollCache.contentHeight - this.scrollCache.displayHeight);
this.scrollCache.hourlyLines = hourlyLines;
// Set up hardware acceleration on the hourly lines element
hourlyLines.style.willChange = 'transform';
hourlyLines.style.backfaceVisibility = 'hidden';
// wind
fillValues.wind = 'Calm';
if (data.windSpeed > 0) {
const windSpeed = Math.round(data.windSpeed).toString();
fillValues.wind = data.windDirection.padEnd(3, ' ') + windSpeed.padStart(3, ' ');
}
// calculate scroll offset and don't go past end
let offsetY = Math.min(this.scrollCache.maxOffset, (count - this.scrollTiming.initialCounts) * this.scrollTiming.pixelsPerCount);
// image
fillValues.icon = { type: 'img', src: data.icon };
// don't let offset go negative
if (offsetY < 0) offsetY = 0;
const filledRow = this.fillTemplate('hourly-row', fillValues);
// use transform instead of scrollTo for hardware acceleration
hourlyLines.style.transform = `translateY(-${Math.round(offsetY)}px)`;
// alter the color of the feels like column to reflect wind chill or heat index
if (data.apparentTemperature < data.temperature) {
filledRow.querySelector('.like').classList.add('wind-chill');
} else if (data.apparentTemperature > data.temperature) {
filledRow.querySelector('.like').classList.add('heat-index');
}
return filledRow;
}
// make data available outside this class
@@ -207,18 +127,6 @@ class Hourly extends WeatherDisplay {
this.getDataCallbacks.push(() => resolve(this.data));
});
}
setTiming(list) {
const container = this.elem.querySelector('.main');
const timingConfig = calculateScrollTiming(list, container);
// Apply the calculated timing
this.timing.baseDelay = timingConfig.baseDelay;
this.timing.delay = timingConfig.delay;
this.scrollTiming = timingConfig.scrollTiming;
this.calcNavTiming();
}
}
// extract specific values from forecast and format as an array
@@ -257,14 +165,14 @@ const parseForecast = async (data) => {
// given forecast paramaters determine a suitable icon
const determineIcon = async (skyCover, weather, iceAccumulation, probabilityOfPrecipitation, snowfallAmount, windSpeed) => {
const startOfHour = DateTime.local().startOf('hour');
const startOfHour = DateTime.local().setZone(timeZone()).startOf('hour');
const sunTimes = (await getSun()).sun;
const overnight = Interval.fromDateTimes(DateTime.fromJSDate(sunTimes[0].sunset), DateTime.fromJSDate(sunTimes[1].sunrise));
const tomorrowOvernight = DateTime.fromJSDate(sunTimes[1].sunset);
return skyCover.map((val, idx) => {
const hour = startOfHour.plus({ hours: idx });
const isNight = overnight.contains(hour) || (hour > tomorrowOvernight);
return getHourlyIcon(skyCover[idx], weather[idx], iceAccumulation[idx], probabilityOfPrecipitation[idx], snowfallAmount[idx], windSpeed[idx], isNight);
return hourlyIcon(skyCover[idx], weather[idx], iceAccumulation[idx], probabilityOfPrecipitation[idx], snowfallAmount[idx], windSpeed[idx], isNight);
});
};
-9
View File
@@ -1,9 +0,0 @@
import largeIcon from './icons/icons-large.mjs';
import smallIcon from './icons/icons-small.mjs';
import hourlyIcon from './icons/icons-hourly.mjs';
export {
largeIcon as getLargeIcon,
smallIcon as getSmallIcon,
hourlyIcon as getHourlyIcon,
};
@@ -1,5 +1,5 @@
/* spell-checker: disable */
import parseIconUrl from './icons-parse.mjs';
import parseIconUrl from './parse.mjs';
const addPath = (icon) => `images/icons/current-conditions/${icon}`;
@@ -1,4 +1,4 @@
import parseIconUrl from './icons-parse.mjs';
import parseIconUrl from './parse.mjs';
const addPath = (icon) => `images/icons/regional-maps/${icon}`;
+118 -114
View File
@@ -1,4 +1,4 @@
// current weather conditions display
// latest nearby observations display
import { distance as calcDistance, directionToNSEW } from './utils/calc.mjs';
import { safeJson, safePromiseAll } from './utils/fetch.mjs';
import STATUS from './status.mjs';
@@ -11,12 +11,11 @@ import settings from './settings.mjs';
import { debugFlag } from './utils/debug.mjs';
import { enhanceObservationWithMapClick } from './utils/mapclick.mjs';
const MAX_REGIONAL_STATIONS = 7;
class LatestObservations extends WeatherDisplay {
constructor(navId, elemId) {
super(navId, elemId, 'Latest Observations', true);
// constants
this.MaximumRegionalStations = 7;
}
async getData(weatherParameters, refresh) {
@@ -32,30 +31,23 @@ class LatestObservations extends WeatherDisplay {
// sort the stations by distance
const sortedStations = stationsByDistance.sort((a, b) => a.distance - b.distance);
// try up to 30 regional stations
const regionalStations = sortedStations.slice(0, 30);
// store the stations to be processed by the recursive loop
const queue = { stations: sortedStations.slice(0, 30), index: 0 };
// helper to grab the next station in line
// eslint-disable-next-line no-plusplus
const nextStation = () => queue.stations[queue.index++];
// Fetch stations sequentially in batches to avoid unnecessary API calls.
// We start with the 7 closest stations and only fetch more if some fail,
// stopping as soon as we have 7 valid stations with data.
const actualConditions = [];
const stationLimit = this.MaximumRegionalStations * ((settings.portrait?.value) ? 2 : 1);
let lastStation = Math.min(regionalStations.length, stationLimit);
let firstStation = 0;
while (actualConditions.length < stationLimit && (lastStation) <= regionalStations.length) {
// Sequential fetching is intentional here - we want to try closest stations first
// and only fetch additional batches if needed, rather than hitting all 30 stations at once
// eslint-disable-next-line no-await-in-loop
const someStations = await this.getStations(regionalStations.slice(firstStation, lastStation));
// get stations via the recurrent getStation function and the length of queue.stations
const stationLimit = MAX_REGIONAL_STATIONS * ((settings.portrait?.value) ? 2 : 1);
const workerCount = Math.min(queue.stations.length, stationLimit);
actualConditions.push(...someStations);
// update counters
firstStation += lastStation;
lastStation = Math.min(regionalStations.length + 1, firstStation + stationLimit - actualConditions.length);
}
// run the loop (and filter out empty responses)
const actualConditions = (await safePromiseAll(Array.from({ length: workerCount }).map(() => this.getStation(nextStation)))).filter((d) => d);
// cut down to the maximum that fit on the page
this.data = actualConditions.slice(0, stationLimit);
// sort by distance is added in case a mid-station fails and a further one is inserted in its place
this.data = actualConditions.sort((a, b) => a.distance - b.distance);
// test for at least one station
if (this.data.length === 0) {
@@ -65,86 +57,81 @@ class LatestObservations extends WeatherDisplay {
this.setStatus(STATUS.loaded);
}
// self recurring station data get function to ensure a call to it returns some data before the end-of-bound check
async getStation(nextStation) {
// see if there are any stations available
const station = nextStation();
if (!station) return false;
// fire up a station worker
const stationData = await this.getStationWorker(station);
// if data was returned use this, otherwise recur
if (stationData) return stationData;
// recur (loop is ended when nextStation is exhausted with the length of regional stations)
return this.getStation(nextStation);
}
// This is a class method because it needs access to the instance's `stillWaiting` method
async getStations(stations) {
// Use centralized safe Promise handling to avoid unhandled AbortError rejections
const stationData = await safePromiseAll(stations.map(async (station) => {
try {
const data = await safeJson(`https://api.weather.gov/stations/${station.id}/observations/latest`, {
retryCount: 1,
stillWaiting: () => this.stillWaiting(),
});
async getStationWorker(station) {
try {
const data = await safeJson(`https://api.weather.gov/stations/${station.id}/observations/latest`, {
retryCount: 0, // there are other stations in the list that can take this place
stillWaiting: () => this.stillWaiting(),
});
if (!data) {
if (debugFlag('verbose-failures')) {
console.log(`Failed to get Latest Observations for station ${station.id}`);
}
return false;
if (!data) {
if (debugFlag('verbose-failures')) {
console.log(`Failed to get Latest Observations for station ${station.id}`);
}
// Enhance observation data with METAR parsing for missing fields
const originalData = { ...data.properties };
data.properties = augmentObservationWithMetar(data.properties);
const metarFields = [
{ name: 'temperature', check: (orig, metar) => orig.temperature.value === null && metar.temperature.value !== null },
{ name: 'windSpeed', check: (orig, metar) => orig.windSpeed.value === null && metar.windSpeed.value !== null },
{ name: 'windDirection', check: (orig, metar) => orig.windDirection.value === null && metar.windDirection.value !== null },
];
const augmentedData = data.properties;
const metarReplacements = metarFields.filter((field) => field.check(originalData, augmentedData)).map((field) => field.name);
if (debugFlag('latestobservations') && metarReplacements.length > 0) {
console.log(`Latest Observations for station ${station.id} were augmented with METAR data for ${metarReplacements.join(', ')}`);
}
// test data quality
const requiredFields = [
{ name: 'temperature', check: (props) => props.temperature?.value === null },
{ name: 'windSpeed', check: (props) => props.windSpeed?.value === null },
{ name: 'windDirection', check: (props) => props.windDirection?.value === null },
{ name: 'textDescription', check: (props) => props.textDescription === null || props.textDescription === '' },
];
// Use enhanced observation with MapClick fallback
const enhancedResult = await enhanceObservationWithMapClick(data.properties, {
requiredFields,
stationId: station.id,
stillWaiting: () => this.stillWaiting(),
debugContext: 'latestobservations',
});
data.properties = enhancedResult.data;
const { missingFields } = enhancedResult;
// Check final data quality
if (missingFields.length > 0) {
if (debugFlag('latestobservations')) {
console.log(`Latest Observations for station ${station.id} is missing fields: ${missingFields.join(', ')}`);
}
return false;
}
// format the return values
return {
...data.properties,
StationId: station.id,
city: station.city,
};
} catch (error) {
console.error(`Unexpected error getting latest observations for station ${station.id}: ${error.message}`);
return false;
}
}));
// filter false (no data or other error)
return stationData.filter((d) => d);
// Enhance observation data with METAR parsing for missing fields
const originalData = { ...data.properties };
data.properties = augmentObservationWithMetar(data.properties);
const augmentedData = data.properties;
const metarReplacements = metarFields.filter((field) => field.check(originalData, augmentedData)).map((field) => field.name);
if (debugFlag('latestobservations') && metarReplacements.length > 0) {
console.log(`Latest Observations for station ${station.id} were augmented with METAR data for ${metarReplacements.join(', ')}`);
}
// Use enhanced observation with MapClick fallback
const enhancedResult = await enhanceObservationWithMapClick(data.properties, {
requiredFields,
stationId: station.id,
stillWaiting: () => this.stillWaiting(),
debugContext: 'latestobservations',
});
data.properties = enhancedResult.data;
const { missingRequired, missingOptional } = enhancedResult;
// Check final data quality
if ((missingRequired.length + missingOptional.length) > 0) {
if (debugFlag('latestobservations')) {
console.log(`Latest Observations for station ${station.id} is missing fields: ${[...missingRequired, ...missingOptional].join(', ')}`);
}
return false;
}
// format the return values
return {
...data.properties,
StationId: station.id,
city: station.city,
distance: station.distance,
};
} catch (error) {
console.error(`Unexpected error getting latest observations for station ${station.id}: ${error.message}`);
return false;
}
}
async drawCanvas() {
super.drawCanvas();
const conditions = this.data;
// sort array by station name
const sortedConditions = conditions.sort((a, b) => ((a.Name < b.Name) ? -1 : 1));
if (settings.units.value === 'us') {
this.elem.querySelector('.column-headers .temp.english').classList.add('show');
this.elem.querySelector('.column-headers .temp.metric').classList.remove('show');
@@ -156,7 +143,7 @@ class LatestObservations extends WeatherDisplay {
const windConverter = windSpeed();
const temperatureConverter = temperature();
const lines = sortedConditions.map((condition) => {
const lines = conditions.map((condition) => {
const windDirection = directionToNSEW(condition.windDirection.value);
const Temperature = temperatureConverter(condition.temperature.value);
@@ -167,15 +154,15 @@ class LatestObservations extends WeatherDisplay {
const weatherLimit = (settings.wide?.value && settings.enhanced?.value) ? 10 : 9;
const fill = {
location: locationCleanup(condition.city).substr(0, locationLimit),
location: locationCleanup(condition.city).substring(0, locationLimit),
temp: Temperature,
like: Like.value,
weather: shortenCurrentConditions(condition.textDescription).substr(0, weatherLimit),
weather: shortenCurrentConditions(condition.textDescription).substring(0, weatherLimit),
};
if (WindSpeed > 0) {
fill.wind = windDirection + (Array(6 - windDirection.length - WindSpeed.toString().length).join(' ')) + WindSpeed.toString();
} else if (WindSpeed === 'NA') {
fill.wind = windDirection.padEnd(3, ' ') + WindSpeed.toString().padStart(2, ' ');
} else if (WindSpeed === '-') {
fill.wind = 'NA';
} else {
fill.wind = 'Calm';
@@ -200,9 +187,13 @@ class LatestObservations extends WeatherDisplay {
// generate a "feels like" temperature from heat index and wind chill.
const likeTemperature = (heat, wind, actual, converter) => {
// figure out the feels like value
// wind chill wins, not that both can happen at the same time
let value = '';
if (heat) value = converter(heat);
if (wind) value = converter(wind);
if (wind !== null && wind !== undefined) {
value = converter(wind);
} else if (heat !== null && heat !== undefined) {
value = converter(heat);
}
// determine if there's a red/blue color class to add
let cssClass;
@@ -216,22 +207,35 @@ const likeTemperature = (heat, wind, actual, converter) => {
};
};
// test data quality
const requiredFields = [
{ name: 'temperature', check: (props) => props.temperature?.value === null },
{ name: 'windSpeed', check: (props) => props.windSpeed?.value === null },
{ name: 'windDirection', check: (props) => props.windDirection?.value === null },
{ name: 'textDescription', check: (props) => props.textDescription === null || props.textDescription === '' },
];
const metarFields = [
{ name: 'temperature', check: (orig, metar) => orig.temperature.value === null && metar.temperature.value !== null },
{ name: 'windSpeed', check: (orig, metar) => orig.windSpeed.value === null && metar.windSpeed.value !== null },
{ name: 'windDirection', check: (orig, metar) => orig.windDirection.value === null && metar.windDirection.value !== null },
];
const shortenCurrentConditions = (_condition) => {
let condition = _condition;
condition = condition.replace(/Light/, 'L');
condition = condition.replace(/Heavy/, 'H');
condition = condition.replace(/Partly/, 'P');
condition = condition.replace(/Mostly/, 'M');
condition = condition.replace(/Few/, 'F');
condition = condition.replace(/Thunderstorm/, 'T\'storm');
condition = condition.replace(/ in /, '');
condition = condition.replace(/Vicinity/, '');
condition = condition.replace(/ and /, ' ');
condition = condition.replace(/Freezing Rain/, 'Frz Rn');
condition = condition.replace(/Freezing/, 'Frz');
condition = condition.replace(/Unknown Precip/, '');
condition = condition.replace(/L Snow Fog/, 'L Snw/Fog');
condition = condition.replace(/ with /, '/');
condition = condition.replace(/Light/g, 'L');
condition = condition.replace(/Heavy/g, 'H');
condition = condition.replace(/Partly/g, 'P');
condition = condition.replace(/Mostly/g, 'M');
condition = condition.replace(/Few/g, 'F');
condition = condition.replace(/Thunderstorm/g, 'T\'storm');
condition = condition.replace(/ in /g, '');
condition = condition.replace(/Vicinity/g, '');
condition = condition.replace(/ and /g, ' ');
condition = condition.replace(/Freezing Rain/g, 'Frz Rn');
condition = condition.replace(/Freezing/g, 'Frz');
condition = condition.replace(/Unknown Precip/g, '');
condition = condition.replace(/L Snow Fog/g, 'L Snw/Fog');
condition = condition.replace(/ with /g, '/');
return condition;
};
// register display
+57 -75
View File
@@ -8,14 +8,26 @@ import settings from './settings.mjs';
import filterExpiredPeriods from './utils/forecast-utils.mjs';
import { debugFlag } from './utils/debug.mjs';
class LocalForecast extends WeatherDisplay {
static BASE_FORECAST_DURATION_MS = 5000; // Base duration (in ms) for a standard 3-5 line forecast page
// Screen durations below are seconds at normal speed. WeatherDisplay multiplies the base count
// interval by the user's speed setting, so nothing here applies that factor a second time.
const SECONDS_PER_LINE = 1.5; // hold each screen in proportion to how much text it carries
const MIN_SCREEN_SECONDS = 5; // floor so a one or two line screen does not flash past
const BASE_DELAY_MS = 250; // milliseconds per base count, fine enough to express the above
// only used when the forecast container cannot be measured
const FALLBACK_PAGE_LINES = 7;
// convert a normal-speed duration to base counts
const secondsToCounts = (seconds) => Math.round((seconds * 1000) / BASE_DELAY_MS);
// how long a screen holding the given number of text lines should remain up, at normal speed
const screenSeconds = (lines) => Math.max(MIN_SCREEN_SECONDS, lines * SECONDS_PER_LINE);
class LocalForecast extends WeatherDisplay {
constructor(navId, elemId) {
super(navId, elemId, 'Local Forecast', true);
// set timings
this.timing.baseDelay = LocalForecast.BASE_FORECAST_DURATION_MS;
this.timing.baseDelay = BASE_DELAY_MS;
}
async getData(weatherParameters, refresh) {
@@ -39,7 +51,7 @@ class LocalForecast extends WeatherDisplay {
// process the text
let text = `${condition.DayName}...`;
const conditionText = condition.Text;
text += conditionText.replace('...', ' ');
text += conditionText.replaceAll('...', ' ');
return text;
});
@@ -67,12 +79,7 @@ class LocalForecast extends WeatherDisplay {
forecastsElem.innerHTML = '';
forecastsElem.append(...templates);
// Get page height for screen calculations
this.pageHeight = 280;
if (settings.portrait?.value && settings.enhanced?.value) {
this.pageHeight = 950;
}
// measures the rendered page, sets this.pageHeight, and builds the timing array
this.calculateContentAwareTiming(templates);
this.calcNavTiming();
@@ -80,22 +87,17 @@ class LocalForecast extends WeatherDisplay {
this.setStatus(STATUS.loaded);
}
// get the unformatted data (also used by extended forecast)
// get the unformatted data
async getRawData(weatherParameters) {
// request us or si units using centralized safe handling
const data = await safeJson(weatherParameters.forecast, {
// safeJson resolves to null on failure
return safeJson(weatherParameters.forecast, {
data: {
units: settings.units.value,
},
retryCount: 3,
stillWaiting: () => this.stillWaiting(),
});
if (!data) {
return false;
}
return data;
}
async drawCanvas() {
@@ -109,45 +111,37 @@ class LocalForecast extends WeatherDisplay {
// calculate dynamic timing based on height measurement template approach
calculateContentAwareTiming(templates) {
const forecastContainer = this.elem.querySelector('.local-forecast .container');
if (!templates || templates.length === 0) {
this.timing.delay = 1; // fallback to single delay if no templates
// nothing to measure or paginate, hold one minimum-length screen
this.pageHeight = forecastContainer?.offsetHeight ?? 0;
this.timing.delay = secondsToCounts(MIN_SCREEN_SECONDS);
return;
}
// Use the original base duration constant for timing calculations
const originalBaseDuration = LocalForecast.BASE_FORECAST_DURATION_MS;
this.timing.baseDelay = 250; // use 250ms per count for precise timing control
// Get line height from CSS for accurate calculations
const sampleForecast = templates[0];
const computedStyle = window.getComputedStyle(sampleForecast);
const lineHeight = parseInt(computedStyle.lineHeight, 10);
// Calculate the actual width that forecast text uses
// Use the forecast container that's already been set up
const forecastContainer = this.elem.querySelector('.local-forecast .container');
let effectiveWidth;
// Page geometry is measured from the rendered container so it cannot drift from the
// stylesheet, then snapped down to a whole number of lines. A page height that is not an
// exact multiple of the line height puts the page boundary partway through a wrapped line.
let maxLinesPerScreen = Math.floor((forecastContainer?.offsetHeight ?? 0) / lineHeight);
if (!Number.isFinite(maxLinesPerScreen) || maxLinesPerScreen < 1) {
console.error(`LocalForecast: could not measure the forecast container, falling back to ${FALLBACK_PAGE_LINES} lines per page`);
maxLinesPerScreen = FALLBACK_PAGE_LINES;
}
this.pageHeight = maxLinesPerScreen * lineHeight;
if (!forecastContainer) {
console.error('LocalForecast: Could not find forecast container for width calculation, using fallback width');
effectiveWidth = 492; // "magic number" from manual calculations as fallback
} else {
const containerStyle = window.getComputedStyle(forecastContainer);
const containerWidth = forecastContainer.offsetWidth;
const paddingLeft = parseInt(containerStyle.paddingLeft, 10) || 0;
const paddingRight = parseInt(containerStyle.paddingRight, 10) || 0;
effectiveWidth = containerWidth - paddingLeft - paddingRight;
if (debugFlag('localforecast')) {
console.log(`LocalForecast: Using measurement width of ${effectiveWidth}px (container=${containerWidth}px, padding=${paddingLeft}+${paddingRight}px)`);
}
if (debugFlag('localforecast')) {
console.log(`LocalForecast: page holds ${maxLinesPerScreen} lines (${this.pageHeight}px at ${lineHeight}px line-height)`);
}
// Measure each forecast period to get actual line counts
const forecastLineCounts = [];
const maxLinesPerScreen = Math.floor(this.pageHeight / 40); // page height / 40px line height
templates.forEach((template, index) => {
const currentHeight = template.offsetHeight;
const currentLines = Math.round(currentHeight / lineHeight);
@@ -160,9 +154,9 @@ class LocalForecast extends WeatherDisplay {
console.log(`LocalForecast: Forecast ${index} measured ${currentLines} lines (${currentHeight}px direct measurement, ${lineHeight}px line-height)`);
}
} else {
// If may be 7 lines or less, we need to pad the content to ensure proper height measurement
// Short forecasts are capped by CSS min-height: 280px (7 lines)
// Add 7 <br> tags to force height beyond the minimum, then subtract the padding
// Short forecasts are floored by the css min-height, so a two line and a full page
// forecast measure the same. Pad past that floor with one <br/> per page line,
// measure, then subtract the padding to recover the real line count.
const originalHTML = template.innerHTML;
const paddingBRs = '<br/>'.repeat(maxLinesPerScreen);
template.innerHTML = originalHTML + paddingBRs;
@@ -171,7 +165,7 @@ class LocalForecast extends WeatherDisplay {
const paddedHeight = template.offsetHeight;
const paddedLines = Math.round(paddedHeight / lineHeight);
// Calculate actual content lines by subtracting the 7 BR lines we added
// Calculate actual content lines by subtracting the padding lines we added
const actualLines = Math.max(1, paddedLines - maxLinesPerScreen);
// Restore original content
@@ -180,7 +174,7 @@ class LocalForecast extends WeatherDisplay {
forecastLineCounts.push(actualLines);
if (debugFlag('localforecast')) {
console.log(`LocalForecast: Forecast ${index} measured ${actualLines} lines (${paddedHeight}px with padding - ${7 * lineHeight}px = ${actualLines * lineHeight}px actual, ${lineHeight}px line-height)`);
console.log(`LocalForecast: Forecast ${index} measured ${actualLines} lines (${paddedHeight}px with padding - ${maxLinesPerScreen * lineHeight}px = ${actualLines * lineHeight}px actual, ${lineHeight}px line-height)`);
}
}
});
@@ -219,45 +213,35 @@ class LocalForecast extends WeatherDisplay {
}
});
// Create timing array based on measured line counts
// Hold each screen in proportion to how much text it carries so the reading rate is the same
// on a sparse standard page and a dense portrait one. These are normal-speed durations; the
// user's speed setting is applied downstream when the base count interval is scheduled.
const screenDelays = screenTimings.map((screenInfo, screenIndex) => {
const screenLines = screenInfo.lines;
// Apply timing rules based on actual screen content lines
let timingMultiplier;
if (screenLines === 1) {
timingMultiplier = 0.6; // 1 line = shortest (3.0s at normal speed)
} else if (screenLines === 2) {
timingMultiplier = 0.8; // 2 lines = shorter (4.0s at normal speed)
} else if (screenLines >= 6) {
timingMultiplier = 1.4; // 6+ lines = longer (7.0s at normal speed)
} else {
timingMultiplier = 1.0; // 3-5 lines = normal (5.0s at normal speed)
}
// Convert to base counts
const desiredDurationMs = timingMultiplier * originalBaseDuration;
const baseCounts = Math.round(desiredDurationMs / this.timing.baseDelay);
const seconds = screenSeconds(screenInfo.lines);
const baseCounts = secondsToCounts(seconds);
if (debugFlag('localforecast')) {
console.log(`LocalForecast: Screen ${screenIndex}: ${screenLines} lines, ${timingMultiplier.toFixed(2)}x multiplier, ${desiredDurationMs}ms desired, ${baseCounts} counts (forecast ${screenInfo.forecastIndex}, ${screenInfo.type})`);
console.log(`LocalForecast: Screen ${screenIndex}: ${screenInfo.lines} lines, ${seconds.toFixed(1)}s at normal speed, ${baseCounts} counts (forecast ${screenInfo.forecastIndex}, ${screenInfo.type})`);
}
return baseCounts;
});
// Adjust timing array to match actual screen count if needed
// Reconcile against the screen count the padded heights produced. The two agree whenever the
// page height is a whole number of lines, so a mismatch means the geometry changed underneath.
while (screenDelays.length < this.timing.totalScreens) {
// Add fallback timing for extra screens
const fallbackCounts = Math.round(originalBaseDuration / this.timing.baseDelay);
screenDelays.push(fallbackCounts);
console.warn(`LocalForecast: using fallback timing for Screen ${screenDelays.length - 1}: 5 lines, 1.00x multiplier, ${fallbackCounts} counts`);
screenDelays.push(secondsToCounts(MIN_SCREEN_SECONDS));
if (debugFlag('localforecast')) {
console.warn(`LocalForecast: using fallback timing for screen ${screenDelays.length - 1}`);
}
}
// Truncate if we have too many calculated screens
if (screenDelays.length > this.timing.totalScreens) {
const removed = screenDelays.splice(this.timing.totalScreens);
console.warn(`LocalForecast: Truncated ${removed.length} excess screen timings`);
if (debugFlag('localforecast')) {
console.warn(`LocalForecast: truncated ${removed.length} excess screen timings`);
}
}
// Set the timing array based on screen content
@@ -265,9 +249,7 @@ class LocalForecast extends WeatherDisplay {
if (debugFlag('localforecast')) {
console.log(`LocalForecast: Final screen count - calculated: ${screenTimings.length}, actual: ${this.timing.totalScreens}, timing array: ${screenDelays.length}`);
const multipliers = screenDelays.map((counts) => (counts * this.timing.baseDelay) / originalBaseDuration);
console.log('LocalForecast: Screen multipliers:', multipliers);
console.log('LocalForecast: Expected durations (ms):', screenDelays.map((counts) => counts * this.timing.baseDelay));
console.log('LocalForecast: Screen durations (s at normal speed):', screenDelays.map((counts) => (counts * BASE_DELAY_MS) / 1000));
}
}
}
+32 -21
View File
@@ -17,8 +17,16 @@ const mediaPlaying = new Setting('mediaPlaying', {
});
document.addEventListener('DOMContentLoaded', () => {
// add the event handler to the page
document.getElementById('ToggleMedia').addEventListener('click', handleMediaClick);
// #ToggleMedia is a pure play/stop toggle, independent of the volume popup
document.getElementById('ToggleMedia').addEventListener('click', toggleMediaPlayback);
// #ToggleMediaVolume opens/closes the volume popup, independent of playback.
// it responds to click (so it works on touch/kiosk, which has no hover) and to hovering
// the whole control cluster (a convenience for a mouse, not a requirement for anyone else)
const mediaContainer = document.getElementById('ToggleMediaContainer');
const volumeToggle = document.getElementById('ToggleMediaVolume');
volumeToggle.addEventListener('click', toggleVolumeSlider);
// get the slider elements
volumeSlider = document.querySelector('#ToggleMediaContainer .volume-slider');
volumeSliderInput = volumeSlider.querySelector('input');
@@ -28,9 +36,6 @@ document.addEventListener('DOMContentLoaded', () => {
volumeSlider.addEventListener('input', setSliderTimeout);
volumeSlider.addEventListener('input', sliderChanged);
// add listener for mute (pause) button under the volume slider
volumeSlider.querySelector('img').addEventListener('click', stopMedia);
// get the playlist
getMedia();
});
@@ -59,6 +64,8 @@ const getMedia = async () => {
let playlistSource = '';
try {
// deliberate fetch (instead of safejson or others)
// we need to examine the headers to determine the deployment mode and path forward
const response = await fetch('playlist.json');
if (response.ok) {
playlist = await response.json();
@@ -114,24 +121,22 @@ const setIcon = () => {
}
};
const handleMediaClick = () => {
// if media is off, start it
if (mediaPlaying.value === false) {
mediaPlaying.value = true;
}
if (mediaPlaying.value === true && !volumeSlider.classList.contains('show')) {
// if media is playing and the slider isn't open, open it
showVolumeSlider();
} else {
// hide the volume slider
hideVolumeSlider();
}
// handle the state change
// pure toggle: flips playback on/off and nothing else. Does not touch the volume popup.
const toggleMediaPlayback = () => {
mediaPlaying.value = !mediaPlaying.value;
stateChanged();
};
// open/close the volume popup. Independent of playback: volume can be adjusted whether or
// not music is currently playing.
const toggleVolumeSlider = () => {
if (volumeSlider.classList.contains('show')) {
hideVolumeSlider();
} else {
showVolumeSlider();
}
};
// set a timeout for the volume slider (called by interactions with the slider)
const setSliderTimeout = () => {
// clear existing timeout
@@ -229,6 +234,12 @@ const sliderChanged = () => {
const cleanValue = parseFloat(newValue) / 100;
setVolume(cleanValue);
mediaVolume.value = cleanValue;
// interacting with the slider while stopped starts playback at the volume just set
if (!mediaPlaying.value) {
mediaPlaying.value = true;
stateChanged();
}
}
};
@@ -303,4 +314,4 @@ const setTrackName = (fileName) => {
document.getElementById('musicTrack').innerHTML = trackName;
};
export default handleMediaClick;
export default toggleMediaPlayback;
+5 -4
View File
@@ -346,13 +346,17 @@ const handleNavButton = (button) => {
case 'menu':
setPlaying(false);
postMessage({ type: 'current-weather-scroll', method: 'hide' });
hideAllCanvases();
if (progress) {
progress.showCanvas();
// close the render-start hideAllCanvases() just triggered, instead of leaving it
// to whichever display's status happens to change next
progress.drawCanvas(displays, countLoadedDisplays());
} else if (settings?.kiosk?.value) {
// In kiosk mode without progress, show the loading screen
document.querySelector('#loading').style.display = 'flex';
}
hideAllCanvases();
break;
default:
console.error(`Unknown navButton ${button}`);
@@ -790,9 +794,6 @@ window.applyScanlineScaling = applyScanlineScaling;
const registerDisplay = (display) => {
if (displays[display.navId]) console.warn(`Display nav ID ${display.navId} already in use`);
displays[display.navId] = display;
// generate checkboxes
generateCheckboxes();
};
const generateCheckboxes = () => {
@@ -50,13 +50,11 @@ const imageFetcher = async (stepBack, attempts, user, projection) => {
try {
const radarBlob = await fetchImageBlob(modifiedRadarUrl);
console.time(`process radar ${path}`);
const canvas = await processRadar({
user,
projection,
radarBlob,
});
console.timeEnd(`process radar ${path}`);
// store the processed radar
processedRadars.push({
@@ -1,4 +1,4 @@
import { getSmallIcon } from './icons.mjs';
import smallIcon from './icons/small.mjs';
import preloadImg from './utils/preload-image.mjs';
import { safeJson } from './utils/fetch.mjs';
import { temperature as temperatureUnit } from './utils/units.mjs';
@@ -67,19 +67,19 @@ const getRegionalObservation = async (point, city) => {
});
augmentedObservation = enhancedResult.data;
const { missingFields } = enhancedResult;
const { missingRequired, missingOptional } = enhancedResult;
// Check final data quality
if (missingFields.length > 0) {
if ((missingRequired.length + missingOptional.length) > 0) {
if (debugFlag('regionalforecast')) {
console.log(`Regional Observations for station ${stationId} is missing fields: ${missingFields.join(', ')} (skipping)`);
console.log(`Regional Observations for station ${stationId} is missing fields: ${[...missingRequired, ...missingOptional].join(', ')} (skipping)`);
}
return false;
}
// preload the image
if (!augmentedObservation.icon) return false;
const icon = getSmallIcon(augmentedObservation.icon, !augmentedObservation.daytime);
const icon = smallIcon(augmentedObservation.icon, !augmentedObservation.daytime);
if (!icon) return false;
preloadImg(icon);
// return the observation
+3 -3
View File
@@ -5,7 +5,7 @@ import STATUS from './status.mjs';
import { distance as calcDistance } from './utils/calc.mjs';
import { safeJson, safePromiseAll } from './utils/fetch.mjs';
import { temperature as temperatureUnit } from './utils/units.mjs';
import { getSmallIcon } from './icons.mjs';
import smallIcon from './icons/small.mjs';
import preloadImg from './utils/preload-image.mjs';
import { DateTime } from '../vendor/auto/luxon.mjs';
import WeatherDisplay from './weatherdisplay.mjs';
@@ -250,7 +250,7 @@ class RegionalForecast extends WeatherDisplay {
};
// preload the icon
preloadImg(getSmallIcon(regionalObservation.icon, !regionalObservation.daytime));
preloadImg(smallIcon(regionalObservation.icon, !regionalObservation.daytime));
// filter out expired periods first, then use the next two periods for forecast
const activePeriods = filterExpiredPeriods(forecast.properties.periods);
@@ -355,7 +355,7 @@ class RegionalForecast extends WeatherDisplay {
const fill = {};
const period = city[this.screenIndex];
fill.icon = { type: 'img', src: getSmallIcon(period.icon, !period.daytime) };
fill.icon = { type: 'img', src: smallIcon(period.icon, !period.daytime) };
fill.city = period.name;
const { temperature } = period;
fill.temp = temperature;
@@ -0,0 +1,101 @@
// shared behavior for displays that render a long, vertically scrolling list of rows
//
// subclasses provide the per-display pieces:
// scrollRows() -> array of row data to render
// contentSignature(rows) -> string identifying what is rendered, used to skip redundant rebuilds
// buildRow(row, index) -> element for the row, or a falsy value to skip it
// drawScreenContent() -> optional, extra DOM work on each draw
import WeatherDisplay from './weatherdisplay.mjs';
import calculateScrollTiming from './utils/scroll-timing.mjs';
class ScrollWeatherDisplay extends WeatherDisplay {
constructor(navId, elemId, name, defaultActive, options = {}) {
super(navId, elemId, name, defaultActive);
this.linesSelector = options.linesSelector;
this.scrollTimingOptions = options.scrollTiming ?? {};
// signature of the content currently rendered into the DOM, so a refresh that returns
// identical rows can skip the rebuild entirely
this.lastContentSignature = null;
}
async drawLongCanvas() {
const list = this.elem.querySelector(this.linesSelector);
if (!list) return;
const rows = this.scrollRows();
// identical content is left in place so an in-progress scroll is not restarted from the top.
// the populated-list check means an empty list is always rebuilt.
const signature = this.contentSignature(rows);
if (signature === this.lastContentSignature && list.children.length > 0) return;
this.lastContentSignature = signature;
list.innerHTML = '';
const lines = rows.map((row, index) => this.buildRow(row, index)).filter((line) => line);
list.append(...lines);
// new content scrolls from the top
this.navBaseCount = 0;
// nothing to show, take this display out of the rotation
if (lines.length === 0) {
this.timing.totalScreens = 0;
return;
}
this.setTiming(list);
}
setTiming(list) {
const container = this.elem.querySelector('.main');
const timingConfig = calculateScrollTiming(list, container, this.scrollTimingOptions);
// apply the calculated timing
this.timing.baseDelay = timingConfig.baseDelay;
this.timing.delay = timingConfig.delay;
this.scrollTiming = timingConfig.scrollTiming;
this.calcNavTiming();
}
// screen index change callback just runs the base count callback
screenIndexChange() {
this.baseCountChange(this.navBaseCount);
}
// base count change callback
baseCountChange(count) {
const lines = this.elem.querySelector(this.linesSelector);
if (!lines || !this.scrollTiming) return;
// calculate the scroll offset, clamped to the distance calculated alongside the timing
const offsetY = Math.max(0, Math.min(
this.scrollTiming.maxOffset,
(count - this.scrollTiming.initialCounts) * this.scrollTiming.pixelsPerCount,
));
// use transform instead of scrollTo for hardware acceleration
lines.style.transform = `translateY(-${Math.round(offsetY)}px)`;
}
// hook for subclasses that update something outside the scrolling list
// eslint-disable-next-line class-methods-use-this
drawScreenContent() {}
drawCanvas() {
super.drawCanvas();
this.drawScreenContent();
this.finishDraw();
}
showCanvas() {
// draw the remainder of the canvas before it is shown
this.drawCanvas();
super.showCanvas();
}
}
export default ScrollWeatherDisplay;
+8 -7
View File
@@ -7,8 +7,10 @@ const settings = { speed: { value: 1.0 } };
// Track settings that need DOM changes after early initialization
const deferredDomSettings = new Set();
let unitChangefirstRunDone = false;
// don't show checkboxes for these settings
const hiddenSettings = [
const hiddenSettingNames = [
'scanLines',
// wide, portrait and enhanced are handled by a dropdown which sets these individual settings accordingly
@@ -71,7 +73,7 @@ const enhancedChange = (value) => {
} else {
container.classList.remove('enhanced');
}
// Trigger resize to recalculate scaling for new width, on next event loop to allow settings to propigate
// Trigger resize to recalculate scaling for new width, on next event loop to allow settings to propagate
setTimeout(() => window.dispatchEvent(new Event('redraw')), 0);
};
@@ -113,12 +115,11 @@ const kioskChange = (value) => {
if (value) {
body.classList.add('kiosk');
document.querySelector('#divTwc')?.classList.add('no-cursor');
window.dispatchEvent(new Event('resize'));
} else {
body.classList.remove('kiosk');
document.querySelector('#divTwc')?.classList.remove('no-cursor');
window.dispatchEvent(new Event('resize'));
}
window.dispatchEvent(new Event('resize'));
// Conditionally store the kiosk setting based on the "Sticky Kiosk" setting
// (Need to check if the method exists to handle initialization race condition)
@@ -186,10 +187,10 @@ window.changeScanlineMode = (mode) => {
const unitChange = () => {
// reload the data at the top level to refresh units
// after the initial load
if (unitChange.firstRunDone) {
if (unitChangefirstRunDone) {
window.location.reload();
}
unitChange.firstRunDone = true;
unitChangefirstRunDone = true;
};
const init = () => {
@@ -323,7 +324,7 @@ document.addEventListener('DOMContentLoaded', () => {
// Then generate the settings UI
const settingHtml = Object.values(settings).map((setting) => {
if (hiddenSettings.includes(setting.shortName)) {
if (hiddenSettingNames.includes(setting.shortName)) {
// setting is hidden, register it
registerHiddenSetting(setting.shortName, setting);
return false;
+11 -27
View File
@@ -17,38 +17,22 @@ const init = () => {
}
};
const createLink = async (e) => {
const createLink = (e) => {
// cancel default event (click on hyperlink)
e.preventDefault();
// list to receive checkbox statuses
const queryStringElements = {};
elemForEach('input[type=checkbox]', (elem) => {
// use name, and fallback to id (older prefix/suffix permalinks)
const key = elem?.name ?? elem?.id;
if (key) {
queryStringElements[key] = elem?.checked ?? false;
}
});
// get all select boxes
elemForEach('select', (elem) => {
// use name, and fallback to id (older prefix/suffix permalinks)
const key = elem?.name ?? elem?.id;
if (key) {
queryStringElements[key] = encodeURIComponent(elem?.value ?? '');
}
});
// get all text boxes
elemForEach('input[type=text]', ((elem) => {
// use name, and fallback to id (older prefix/suffix permalinks)
const key = elem?.name ?? elem?.id;
if (key && key !== '') {
queryStringElements[key] = elem?.value ?? 0;
}
}));
const captureField = (selector, getValue) => {
elemForEach(selector, (elem) => {
const key = elem?.name ?? elem?.id;
if (key) queryStringElements[key] = getValue(elem);
});
};
captureField('input[type=checkbox]', (elem) => elem?.checked ?? false);
captureField('select', (elem) => elem?.value ?? '');
captureField('input[type=text]', (elem) => elem?.value ?? '');
// get any hidden settings
hiddenSettings.forEach((setting) => {
@@ -86,6 +70,7 @@ const copyToClipboard = async (url) => {
}, 5000);
} catch (error) {
console.error(error);
writeLinkToPage(url);
}
};
@@ -102,7 +87,6 @@ const writeLinkToPage = (url) => {
};
const registerHiddenSetting = (name, value) => {
// name is the id of the element
// value can be a function that returns the current value of the setting
// or an instance of Setting
hiddenSettings.push({
+36 -32
View File
@@ -7,6 +7,7 @@ import WeatherDisplay from './weatherdisplay.mjs';
import { registerDisplay } from './navigation.mjs';
import testPolygon from './utils/polygon.mjs';
import { debugFlag } from './utils/debug.mjs';
import settings from './settings.mjs';
// list of interesting files ordered [0] = today, [1] = tomorrow...
const urlPattern = (day, type) => `https://www.spc.noaa.gov/products/outlook/day${day}otlk_${type}.nolyr.geojson`;
@@ -77,7 +78,7 @@ class SpcOutlook extends WeatherDisplay {
// store the data
rawOutlookData.forEach((outlookDay, index) => {
this.data[index].categorical = outlookDay.features;
this.data[index].categorical = outlookDay?.features;
});
// check for at least one day of data
@@ -103,10 +104,13 @@ class SpcOutlook extends WeatherDisplay {
// see if we're inside any of the polygons
const daysToGet = this.testAllPoints([this.weatherParameters.longitude, this.weatherParameters.latitude], 'categorical');
// determine if all detail data is present
const allDataPresent = this.data.every((day, dayIndex) => (!daysToGet[dayIndex] || Object.values(day).every((cur) => (cur !== undefined))));
if (!allDataPresent) {
await this.getRemainingData(daysToGet);
// only get detailed data if in portrait
if (settings.portrait?.value) {
// determine if all detail data is present
const allDataPresent = this.data.every((day, dayIndex) => (!daysToGet[dayIndex]?.categorical || Object.values(day).every((cur) => (cur !== undefined))));
if (!allDataPresent) {
await this.getRemainingData(daysToGet);
}
}
this.filteredData = this.testAllPoints([this.weatherParameters.longitude, this.weatherParameters.latitude]);
@@ -155,34 +159,35 @@ class SpcOutlook extends WeatherDisplay {
dayContainer.innerHTML = '';
dayContainer.append(...days);
// add details for portrait
// header first
this.data.forEach((day, index) => {
if (index > 1) return;
const header = this.elem.querySelector(`.header.day-${index}`);
const dayName = DateTime.now().plus({ days: index }).toLocaleString({ weekday: 'long' });
header.innerHTML = dayName;
});
// add details for portrait if in portrait
if (settings.portrait?.value) { // header first
this.data.forEach((day, index) => {
if (index > 1) return;
const header = this.elem.querySelector(`.header.day-${index}`);
const dayName = DateTime.now().plus({ days: index }).toLocaleString({ weekday: 'long' });
header.innerHTML = dayName;
});
// first column labels
const rowLabels = ['Tornado', 'Wind', 'Hail'];
// first column labels
const rowLabels = ['Tornado', 'Wind', 'Hail'];
const detailLines = rowLabels.map((label) => {
const row = [];
// type of phenomena
row.push(this.fillTemplate('type', { 'grid-item': label }));
const phenomena = label.toLowerCase();
// probability
row.push(this.fillTemplate('day-0', { 'grid-item': formatProbability(this.filteredData[0]?.[phenomena]?.DN) }));
row.push(this.fillTemplate('day-1', { 'grid-item': formatProbability(this.filteredData[1]?.[phenomena]?.DN) }));
return row;
}).flat(1);
const detailLines = rowLabels.map((label) => {
const row = [];
// type of phenomena
row.push(this.fillTemplate('type', { 'grid-item': label }));
const phenomena = label.toLowerCase();
// probability
row.push(this.fillTemplate('day-0', { 'grid-item': formatProbability(this.filteredData[0]?.[phenomena]?.DN) }));
row.push(this.fillTemplate('day-1', { 'grid-item': formatProbability(this.filteredData[1]?.[phenomena]?.DN) }));
return row;
}).flat(1);
// add the lines to the page
const details = this.elem.querySelector('.container-details .table');
const replaceable = details.querySelectorAll('.replaceable');
replaceable.forEach((elem) => elem.remove());
details.append(...detailLines);
// add the lines to the page
const details = this.elem.querySelector('.container-details .table');
const replaceable = details.querySelectorAll('.replaceable');
replaceable.forEach((elem) => elem.remove());
details.append(...detailLines);
}
// finish drawing
this.finishDraw();
@@ -190,7 +195,7 @@ class SpcOutlook extends WeatherDisplay {
async getRemainingData(daysToGet) {
await Promise.allSettled(this.data.map(async (day, index) => {
if (!daysToGet[index]) return;
if (!daysToGet[index]?.categorical) return;
const dayPromises = Object.entries(day).map(async ([key, value]) => {
// if data is already present, no work to do
if (value) return true;
@@ -212,7 +217,6 @@ class SpcOutlook extends WeatherDisplay {
// types can be specificed as a string, array of strings or defaults to all types
let types = Object.keys(phenomenonTypes);
if (Array.isArray(_types)) types = +types;
if (typeof _types === 'string') types = [_types];
const result = [];
+51 -155
View File
@@ -1,45 +1,32 @@
// travel forecast display
import STATUS from './status.mjs';
import { safeJson, safePromiseAll } from './utils/fetch.mjs';
import { getSmallIcon } from './icons.mjs';
import smallIcon from './icons/small.mjs';
import { DateTime } from '../vendor/auto/luxon.mjs';
import WeatherDisplay from './weatherdisplay.mjs';
import ScrollWeatherDisplay from './scroll-weather-display.mjs';
import { registerDisplay } from './navigation.mjs';
import settings from './settings.mjs';
import calculateScrollTiming from './utils/scroll-timing.mjs';
import { debugFlag } from './utils/debug.mjs';
// A cheap, stable signature of the content about to be rendered. Only the fields that reach the DOM
// are included. Rows for cities whose forecast failed are dropped from the rendered list, so the row
// count - and therefore the rendered height - changes as individual cities come and go.
const contentSignature = (cities) => cities.map((city) => (city.error
const rowsSignature = (cities) => cities.map((city) => (city.error
? `${city.name}|error`
: `${city.name}|${city.high}|${city.low}|${city.icon}`)).join('\u0000');
class TravelForecast extends WeatherDisplay {
class TravelForecast extends ScrollWeatherDisplay {
constructor(navId, elemId, defaultActive) {
// special height and width for scrolling
super(navId, elemId, 'Travel Forecast', defaultActive);
super(navId, elemId, 'Travel Forecast', defaultActive, {
linesSelector: '.travel-lines',
scrollTiming: {
staticDisplay: 5.0, // special static display time for travel forecast
},
});
// add previous data cache
this.previousData = [];
// cache for scroll calculations
// This cache is essential because baseCountChange() is called 25 times per second (every 40ms)
// during scrolling. Travel forecast scroll duration varies based on the number of cities configured.
// Without caching, we'd perform hundreds of expensive DOM layout queries during each scroll cycle.
// The cache reduces this to one calculation when content changes, then reuses cached values to try
// and get smoother scrolling.
this.scrollCache = {
displayHeight: 0,
contentHeight: 0,
maxOffset: 0,
travelLines: null,
};
// signature of the content currently rendered into the DOM, so a refresh that returns
// identical cities can skip the rebuild entirely
this.lastContentSignature = null;
}
async getData(weatherParameters, refresh) {
@@ -55,8 +42,7 @@ class TravelForecast extends WeatherDisplay {
try {
// get point then forecast
if (!city.point) throw new Error('No pre-loaded point');
let forecast;
forecast = await safeJson(`https://api.weather.gov/gridpoints/${city.point.wfo}/${city.point.x},${city.point.y}/forecast`, {
let forecast = await safeJson(`https://api.weather.gov/gridpoints/${city.point.wfo}/${city.point.x},${city.point.y}/forecast`, {
data: {
units: settings.units.value,
},
@@ -86,7 +72,7 @@ class TravelForecast extends WeatherDisplay {
high: forecast.properties.periods[todayShift].temperature,
low: forecast.properties.periods[todayShift + 1].temperature,
name: city.Name,
icon: getSmallIcon(forecast.properties.periods[todayShift].icon),
icon: smallIcon(forecast.properties.periods[todayShift].icon),
};
} catch (error) {
console.error(`Unexpected error getting Travel Forecast for ${city.Name}: ${error.message}`);
@@ -99,7 +85,7 @@ class TravelForecast extends WeatherDisplay {
this.data = forecasts;
// test for some data available in at least one forecast
const hasData = this.data.some((forecast) => forecast.high);
const hasData = this.data.some((forecast) => !forecast.error);
if (!hasData) {
this.setStatus(STATUS.noData);
return;
@@ -109,147 +95,57 @@ class TravelForecast extends WeatherDisplay {
this.drawLongCanvas();
}
async drawLongCanvas() {
// get the element and populate
const list = this.elem.querySelector('.travel-lines');
// set up variables
const cities = this.data;
// if the content is identical to what is already rendered, leave the DOM and the scroll
// position alone rather than rebuilding and restarting an in-progress scroll
const signature = contentSignature(cities);
if (signature === this.lastContentSignature && list.children.length > 0) return;
this.lastContentSignature = signature;
list.innerHTML = '';
const lines = cities.map((city) => {
if (city.error) return false;
const fillValues = {
city,
};
// check for forecast data
if (city.icon) {
fillValues.city = city.name;
// get temperatures and convert if necessary
const { low, high } = city;
// convert to strings with no decimal
const lowString = Math.round(low).toString();
const highString = Math.round(high).toString();
fillValues.low = lowString;
fillValues.high = highString;
const { icon } = city;
fillValues.icon = { type: 'img', src: icon };
} else {
fillValues.error = 'NO TRAVEL DATA AVAILABLE';
}
return this.fillTemplate('travel-row', fillValues);
}).filter((d) => d);
list.append(...lines);
// The scroll cache is invalidated by comparing element identity, but .travel-lines is
// persistent - only its children are replaced above - and displayHeight is a fixed value
// from css. Both conditions in baseCountChange() therefore stay false after the first
// measurement, so maxOffset keeps the height of whatever content was measured first and
// clamps the scroll partway through anything taller, leaving it frozen there. Invalidate
// explicitly so the next base count re-measures.
this.scrollCache.displayHeight = 0;
this.scrollCache.travelLines = null;
// new content scrolls from the top
this.navBaseCount = 0;
// update timing based on actual content
this.setTiming(list);
scrollRows() {
return this.data;
}
async drawCanvas() {
// there are technically 2 canvases: the standard canvas and the extra-long canvas that contains the complete
// list of cities. The second canvas is copied into the standard canvas to create the scroll
super.drawCanvas();
// set up variables
const cities = this.data;
this.elem.querySelector('.header .title.dual .bottom').innerHTML = `For ${getTravelCitiesDayName(cities)}`;
this.finishDraw();
// eslint-disable-next-line class-methods-use-this
contentSignature(cities) {
return rowsSignature(cities);
}
async showCanvas() {
// special to travel forecast to draw the remainder of the canvas
await this.drawCanvas();
super.showCanvas();
buildRow(city) {
// cities whose forecast failed are dropped from the rendered list
if (city.error) return false;
const fillValues = {};
// fill forecast data
fillValues.city = city.name;
// get temperatures and convert if necessary
const { low, high } = city;
// convert to strings with no decimal
const lowString = Math.round(low).toString();
const highString = Math.round(high).toString();
fillValues.low = lowString;
fillValues.high = highString;
const { icon } = city;
fillValues.icon = { type: 'img', src: icon };
return this.fillTemplate('travel-row', fillValues);
}
// screen index change callback just runs the base count callback
screenIndexChange() {
this.baseCountChange(this.navBaseCount);
}
// base count change callback
baseCountChange(count) {
// get the travel lines element and cache measurements if needed
const travelLines = this.elem.querySelector('.travel-lines');
if (!travelLines) return;
// update cache if needed (when content changes or first run)
if (this.scrollCache.travelLines !== travelLines || this.scrollCache.displayHeight === 0) {
this.scrollCache.displayHeight = this.elem.querySelector('.main').offsetHeight;
this.scrollCache.contentHeight = travelLines.offsetHeight;
this.scrollCache.maxOffset = Math.max(0, this.scrollCache.contentHeight - this.scrollCache.displayHeight);
this.scrollCache.travelLines = travelLines;
// Set up hardware acceleration on the travel lines element
travelLines.style.willChange = 'transform';
travelLines.style.backfaceVisibility = 'hidden';
}
// calculate scroll offset and don't go past end
let offsetY = Math.min(this.scrollCache.maxOffset, (count - this.scrollTiming.initialCounts) * this.scrollTiming.pixelsPerCount);
// don't let offset go negative
if (offsetY < 0) offsetY = 0;
// use transform instead of scrollTo for hardware acceleration
travelLines.style.transform = `translateY(-${Math.round(offsetY)}px)`;
}
// necessary to get the lastest long canvas when scrolling
getLongCanvas() {
return this.longCanvas;
}
setTiming(list) {
const container = this.elem.querySelector('.main');
const timingConfig = calculateScrollTiming(list, container, {
staticDisplay: 5.0, // special static display time for travel forecast
});
// Apply the calculated timing
this.timing.baseDelay = timingConfig.baseDelay;
this.timing.delay = timingConfig.delay;
this.scrollTiming = timingConfig.scrollTiming;
this.calcNavTiming();
// the header carries the day the forecast is for
drawScreenContent() {
const dayName = getTravelCitiesDayName(this.data);
this.elem.querySelector('.header .title.dual .bottom').innerHTML = `For ${dayName}`;
}
}
// effectively returns early on the first found date
const getTravelCitiesDayName = (cities) => cities.reduce((dayName, city) => {
if (city && dayName === '') {
// returns early on the first found date
const getTravelCitiesDayName = (cities) => {
const firstCity = cities.find((city) => city && !city.error);
if (firstCity) {
// today or tomorrow
const day = DateTime.local().plus({ days: (city.today) ? 0 : 1 });
const day = DateTime.local().plus({ days: (firstCity.today) ? 0 : 1 });
// return the day
return day.toLocaleString({ weekday: 'long' });
}
return dayName;
}, '');
return '';
};
// register display, not active by default
registerDisplay(new TravelForecast(5, 'travel', false));
-15
View File
@@ -6,11 +6,6 @@ const DEFAULT_REQUEST_TIMEOUT = 15000; // For example, with 3 retries: 15s+1s+15
const safeJson = async (url, params) => {
try {
const result = await json(url, params);
// Return an object with both data and url if params.returnUrl is true
if (params?.returnUrl) {
return result;
}
// If caller didn't specify returnUrl, result is the raw API response
return result;
} catch {
// Error already logged in fetchAsync; return null to be "safe"
@@ -21,11 +16,6 @@ const safeJson = async (url, params) => {
const safeText = async (url, params) => {
try {
const result = await text(url, params);
// Return an object with both data and url if params.returnUrl is true
if (params?.returnUrl) {
return result;
}
// If caller didn't specify returnUrl, result is the raw API response
return result;
} catch {
// Error already logged in fetchAsync; return null to be "safe"
@@ -36,11 +26,6 @@ const safeText = async (url, params) => {
const safeBlob = async (url, params) => {
try {
const result = await blob(url, params);
// Return an object with both data and url if params.returnUrl is true
if (params?.returnUrl) {
return result;
}
// If caller didn't specify returnUrl, result is the raw API response
return result;
} catch {
// Error already logged in fetchAsync; return null to be "safe"
+4 -2
View File
@@ -506,7 +506,8 @@ export const enhanceObservationWithMapClick = async (observationData, options =
data: observationData,
wasImproved: false,
improvements: [],
missingFields: [...missingRequired, ...missingOptional],
missingRequired,
missingOptional,
};
};
@@ -653,7 +654,8 @@ export const enhanceObservationWithMapClick = async (observationData, options =
data: { ...mapClickProps, timestamp: observationData.timestamp },
wasImproved: true,
improvements,
missingFields: [...mapClickMissingRequired, ...mapClickMissingOptional],
missingRequired: mapClickMissingRequired,
missingOptional: mapClickMissingOptional,
};
};
@@ -59,6 +59,7 @@ const calculateScrollTiming = (list, container, options = {}) => {
scrollTiming: {
initialCounts,
pixelsPerCount,
maxOffset: scrollableHeight,
},
};
};
+29 -24
View File
@@ -10,11 +10,13 @@ import settings from './settings.mjs';
import elemForEach from './utils/elem-for-each.mjs';
import { debugFlag } from './utils/debug.mjs';
let drawStartedAt = null;
class WeatherDisplay {
constructor(navId, elemId, name, defaultEnabled) {
// navId is used in messaging and sort order
this.navId = navId;
this.elemId = undefined;
this.elemId = elemId;
this.data = undefined;
this.loadingStatus = STATUS.loading;
this.name = name ?? elemId;
@@ -36,9 +38,6 @@ class WeatherDisplay {
this.navBaseCount = 0;
this.screenIndex = -1; // special starting condition
// store elemId once
this.storeElemId(elemId);
if (this.isEnabled) {
this.setStatus(STATUS.loading);
} else {
@@ -127,12 +126,6 @@ class WeatherDisplay {
this.loadingStatus = state;
}
storeElemId(elemId) {
// only create it once
if (this.elemId) return;
this.elemId = elemId;
}
// get necessary data for this display
getData(weatherParameters, refresh) {
// refresh doesn't delete existing data, and is reused if the silent refresh fails
@@ -150,6 +143,7 @@ class WeatherDisplay {
this.setStatus(STATUS.loading);
} else {
this.setStatus(STATUS.disabled);
// returns false when disabled; displays that publish data to other modules should continue fetching anyway
return false;
}
@@ -173,10 +167,13 @@ class WeatherDisplay {
// clean up the first-run flag in screen index
if (this.screenIndex < 0) this.screenIndex = 0;
if (this.okToDrawCurrentDateTime) this.drawCurrentDateTime();
if (this.okToDrawCurrentConditions) postMessage({ type: 'current-weather-scroll', method: 'start' });
if (!this.okToDrawCurrentConditions) postMessage({ type: 'current-weather-scroll', method: 'non-display' });
if (this.okToDrawCurrentConditions === false) postMessage({ type: 'current-weather-scroll', method: 'hide' });
this.sendRenderStart();
if (this.okToDrawCurrentConditions) {
postMessage({ type: 'current-weather-scroll', method: 'start' });
} else {
postMessage({ type: 'current-weather-scroll', method: 'non-display' });
postMessage({ type: 'current-weather-scroll', method: 'hide' });
}
WeatherDisplay.sendRenderStart();
}
finishDraw() {
@@ -189,7 +186,7 @@ class WeatherDisplay {
this.dateTimeInterval = setInterval(() => this.active && this.drawCurrentDateTime(), 100);
}
}
this.sendRenderEnd();
WeatherDisplay.sendRenderEnd();
}
drawCurrentDateTime() {
@@ -233,7 +230,7 @@ class WeatherDisplay {
hideCanvas() {
this.resetNavBaseCount();
if (this.elem.classList.contains('show')) {
this.sendRenderStart();
WeatherDisplay.sendRenderStart();
}
this.elem.classList.remove('show');
// used to change backgrounds for widescreen
@@ -327,15 +324,22 @@ class WeatherDisplay {
// test for -1 (no screen displayed yet)
this.screenIndex = nextScreenIndex === -1 ? 0 : nextScreenIndex;
// call the appropriate screen index change method
// Optional hook. Defining this REPLACES the automatic drawCanvas() call on screen
// transitions - implementors are responsible for drawing (typically from showCanvas).
if (this.screenIndexChange) {
this.screenIndexChange(this.screenIndex);
this.screenIndexChange();
} else {
await this.drawCanvas();
}
this.showCanvas();
}
// Optional hook, called on every base count tick while this display is active.
// eslint-disable-next-line class-methods-use-this
baseCountChange() {
return false;
}
// take the three timing formats shown above and break them into arrays for consistent usage in navigation functions
// this.timing.fullDelay = [end of screen index 0 in base counts, end of screen index 1...]
// this.timing.screenIndexes = [screen index to use during this.timing.fullDelay[0], screen index to use during this.timing.fullDelay[1], ...]
@@ -522,22 +526,23 @@ class WeatherDisplay {
this.autoRefreshHandle = this.autoRefreshHandle ?? setInterval(() => this.getData(this.weatherParameters, true), refreshTime);
}
sendRenderStart() {
if (!this.drawStartedAt) {
this.drawStartedAt = Date.now();
// these hooks work with ws4channels to suppress grabbing a frame mid-change
static sendRenderStart() {
if (!drawStartedAt) {
drawStartedAt = Date.now();
}
document.dispatchEvent(new Event('ws4kp-render-start'));
}
sendRenderEnd() {
static sendRenderEnd() {
requestAnimationFrame(() => requestAnimationFrame(() => {
document.dispatchEvent(new CustomEvent('ws4kp-render-end', {
detail: {
startedAt: this.drawStartedAt,
startedAt: drawStartedAt,
endedAt: Date.now(),
},
}));
this.drawStartedAt = null;
drawStartedAt = null;
}));
}
}
-1
View File
@@ -55,7 +55,6 @@
// Row labels (Sunrise:, Sunset:)
&.row-label {
// color: c.$column-header-text; // screenshots show labels were white
text-align: right;
}
+3 -1
View File
@@ -11,7 +11,7 @@
&.main {
overflow-y: hidden;
height: p.$standard-height;
background-color: rgb(112, 35, 35);
background-color: c.$hazard-background;
width: p.$standard-width;
@@ -26,6 +26,8 @@
.hazard-lines {
min-height: 400px;
padding-top: 10px;
will-change: transform;
backface-visibility: hidden;
.hazard {
font-family: 'Star4000';
+7 -7
View File
@@ -134,27 +134,27 @@
}
&.l-2 {
left: calc(726px / 6 * 1);
left: calc(746px / 6 * 1);
}
&.l-3 {
left: calc(726px / 6 * 2);
left: calc(746px / 6 * 2);
}
&.l-4 {
left: calc(726px / 6 * 3);
left: calc(746px / 6 * 3);
}
&.l-5 {
left: calc(726px / 6 * 4);
left: calc(746px / 6 * 4);
}
&.l-6 {
left: calc(726px / 6 * 5);
left: calc(746px / 6 * 5);
}
&.l-7 {
left: calc(726px / 6 * 6);
left: calc(746px / 6 * 6);
}
}
@@ -176,7 +176,7 @@
top: 0px;
left: 50px;
img {
canvas {
width: 532px;
height: 285px;
+2
View File
@@ -44,6 +44,8 @@
.hourly-lines {
min-height: 338px;
padding-top: 10px;
will-change: transform;
backface-visibility: hidden;
background: repeating-linear-gradient(0deg, c.$gradient-main-background-2 0px,
c.$gradient-main-background-1 136px,
+26 -3
View File
@@ -9,6 +9,7 @@
&.available {
display: inline-block;
// #ToggleMedia is a pure play/stop toggle; icon switch is handled by adding/removing the .playing class
img.on {
display: none;
}
@@ -17,7 +18,6 @@
display: block;
}
// icon switch is handled by adding/removing the .playing class
&.playing {
img.on {
display: block;
@@ -27,17 +27,40 @@
display: none;
}
// full strength once something is actually playing
#ToggleMediaVolume,
.volume-slider {
opacity: 1;
}
}
}
#ToggleMedia,
#ToggleMediaVolume {
display: inline-block;
}
// #ToggleMediaVolume opens/closes the volume popup, independent of the play/pause toggle.
// it (and the slider it reveals) read as inactive until something is playing, but stay
// fully clickable/draggable - interacting with the slider while stopped starts playback.
#ToggleMediaVolume {
margin-left: 4px;
}
#ToggleMediaVolume,
.volume-slider {
opacity: 0.4;
transition: opacity 0.2s ease;
}
.volume-slider {
display: none;
position: absolute;
top: 0px;
transform: translateY(-100%);
width: 100%;
transform: translateY(-100%) translateX(100%);
width: 50%;
background-color: #000;
text-align: center;
z-index: 100;
+2
View File
@@ -44,6 +44,8 @@
.travel-lines {
min-height: 338px;
padding-top: 10px;
will-change: transform;
backface-visibility: hidden;
background: repeating-linear-gradient(0deg, c.$gradient-main-background-2 0px,
c.$gradient-main-background-1 136px,
+20 -1
View File
@@ -205,7 +205,7 @@
}
&.hazard {
background-color: rgb(112, 35, 35);
background-color: c.$hazard-background;
}
.scroll-container {
@@ -229,6 +229,8 @@
.fixed {
font-family: 'Star4000';
font-size: 32px;
overflow: hidden;
white-space: nowrap;
.scroll-area {
text-wrap: nowrap;
@@ -238,8 +240,25 @@
// left: calc((elem width) - p.$standard-width);
}
}
.reveal {
overflow: hidden;
width: 0;
animation:
typing 0.2s steps(21, end) forwards;
}
@keyframes typing {
to {
width: 100%
}
}
}
}
+3 -1
View File
@@ -16,4 +16,6 @@ $extended-low: #8080FF;
$wind-chill: #8080FF;
$heat-index: #e00;
$blue-box: #26235a;
$blue-box: #26235a;
$hazard-background: rgb(112, 35, 35);
+1 -1
View File
@@ -1 +1 @@
@font-face{font-family:"Star4000";src:url("../fonts/Star4000.woff") format("woff");font-display:swap}body{font-family:"Star4000";margin:0}@media(prefers-color-scheme: dark){body{background-color:#000;color:#fff}}@media(prefers-color-scheme: dark){body a{color:#add8e6}}body.kiosk{margin:0px;padding:0px;overflow:hidden;width:100vw;background-color:#000 !important}#divQuery{max-width:640px;padding:8px}#divQuery .buttons{display:inline-block;width:150px;text-align:right}#divQuery .buttons #imgGetGps{height:13px;vertical-align:middle}#divQuery .buttons button{font-size:21px;border:1px solid #a9a9a9}@media(prefers-color-scheme: dark){#divQuery .buttons button{background-color:#000;color:#fff}}#divQuery .buttons #btnGetGps img.dark{display:none}@media(prefers-color-scheme: dark){#divQuery .buttons #btnGetGps img.dark{display:inline-block}}@media(prefers-color-scheme: dark){#divQuery .buttons #btnGetGps img.light{display:none}}#divQuery .buttons #btnGetGps.active{background-color:#000}@media(prefers-color-scheme: dark){#divQuery .buttons #btnGetGps.active{background-color:#fff}}#divQuery .buttons #btnGetGps.active img{filter:invert(1)}#divQuery input,#divQuery button{font-family:"Star4000"}#divQuery #txtLocation{width:calc(100% - 170px);max-width:490px;font-size:21px;min-width:200px;display:inline-block;background-color:#fff;color:#000;border:2px inset gray}@media(prefers-color-scheme: dark){#divQuery #txtLocation{background-color:#000;color:#fff;border:2px inset gray}}.autocomplete-suggestions{background-color:#fff;border:1px solid #000;position:absolute;z-index:9999}@media(prefers-color-scheme: dark){.autocomplete-suggestions{background-color:#000}}.autocomplete-suggestions div{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:21px}.autocomplete-suggestions div.selected{background-color:blue;color:#fff}#divTwc{display:block;background-color:#000;color:#fff;width:100%;max-width:640px;margin:0}#divTwc.wide{max-width:854px}.content-wrapper{padding:8px}#divTwcMain{width:640px;height:480px;position:relative}.wide #divTwcMain{width:854px}.enhanced.portrait #divTwcMain{height:1137px}.kiosk #divTwc{max-width:unset}#divTwcLeft{display:none;text-align:right;flex-direction:column;vertical-align:middle}#divTwcLeft>div{flex:1;padding-right:12px;display:flex;flex-direction:column;justify-content:center}#divTwcRight{text-align:left;display:none;flex-direction:column;vertical-align:middle}#divTwcRight>div{flex:1;padding-left:12px;display:flex;flex-direction:column;justify-content:center}#divTwcBottom{display:flex;flex-direction:row;background-color:#000;color:#fff;width:640px}.wide #divTwcBottom{width:854px}@media(prefers-color-scheme: dark){#divTwcBottom{background-color:#303030}}#divTwcBottom>div{padding-left:6px;padding-right:6px}@media(max-width: 550px){#divTwcBottom>div{font-size:.9em}}@media(max-width: 500px){#divTwcBottom>div{font-size:.8em}}@media(max-width: 450px){#divTwcBottom>div{font-size:.7em}}@media(max-width: 400px){#divTwcBottom>div{font-size:.6em}}@media(max-width: 350px){#divTwcBottom>div{font-size:.5em}}#divTwcBottomLeft{flex:1;text-align:left}#divTwcBottomMiddle{flex:0;text-align:center}#divTwcBottomRight{flex:1;text-align:right}#divTwcNavContainer{display:none}#divTwcNav{width:100%;display:flex;flex-direction:row;background-color:#000;color:#fff;max-width:640px}#divTwcNav>div{padding-left:6px;padding-right:6px}#divTwcNavLeft{flex:1;text-align:left}#divTwcNavMiddle{flex:0;text-align:center}#divTwcNavRight{flex:1;text-align:right}#imgPause1x{visibility:hidden;position:absolute}.HideCursor{cursor:none !important}#txtScrollText{width:475px}@font-face{font-family:"Star4000 Extended";src:url("../fonts/Star4000 Extended.woff") format("woff");font-display:swap}@font-face{font-family:"Star4000 Large";src:url("../fonts/Star4000 Large.woff") format("woff");font-display:swap}@font-face{font-family:"Star4000 Small";src:url("../fonts/Star4000 Small.woff") format("woff");font-display:swap}#display{font-family:"Star4000";margin:0 0 0 0;width:100%}#container{position:relative;width:640px;height:480px;background-image:url(../images/backgrounds/1.png);transform-origin:0 0;background-repeat:no-repeat}.portrait.enhanced #container{width:640px;height:1137px;background-image:url(../images/backgrounds/1-portrait.png)}.wide #container{width:854px;background:url(../images/backgrounds/1-wide.png);background-repeat:no-repeat}#divTwc:fullscreen #container,.kiosk #divTwc #container{width:unset;height:unset}#loading{width:640px;height:480px;max-width:100%;text-shadow:4px 4px #000;display:flex;align-items:center;text-align:center;justify-content:center}.wide #loading{margin-left:107px}#loading .title{font-family:Star4000 Large;font-size:36px;color:#ff0;margin-bottom:0px}#loading .version{margin-bottom:35px}#loading .instructions{font-size:24px}.heading{font-weight:bold;margin-top:15px}#settings{margin-bottom:15px}#enabledDisplays,#settings{margin-bottom:15px}#enabledDisplays .loading,#enabledDisplays .retrying,#settings Line truncated
@font-face{font-family:"Star4000";src:url("../fonts/Star4000.woff") format("woff");font-display:swap}body{font-family:"Star4000";margin:0}@media(prefers-color-scheme: dark){body{background-color:#000;color:#fff}}@media(prefers-color-scheme: dark){body a{color:#add8e6}}body.kiosk{margin:0px;padding:0px;overflow:hidden;width:100vw;background-color:#000 !important}#divQuery{max-width:640px;padding:8px}#divQuery .buttons{display:inline-block;width:150px;text-align:right}#divQuery .buttons #imgGetGps{height:13px;vertical-align:middle}#divQuery .buttons button{font-size:21px;border:1px solid #a9a9a9}@media(prefers-color-scheme: dark){#divQuery .buttons button{background-color:#000;color:#fff}}#divQuery .buttons #btnGetGps img.dark{display:none}@media(prefers-color-scheme: dark){#divQuery .buttons #btnGetGps img.dark{display:inline-block}}@media(prefers-color-scheme: dark){#divQuery .buttons #btnGetGps img.light{display:none}}#divQuery .buttons #btnGetGps.active{background-color:#000}@media(prefers-color-scheme: dark){#divQuery .buttons #btnGetGps.active{background-color:#fff}}#divQuery .buttons #btnGetGps.active img{filter:invert(1)}#divQuery input,#divQuery button{font-family:"Star4000"}#divQuery #txtLocation{width:calc(100% - 170px);max-width:490px;font-size:21px;min-width:200px;display:inline-block;background-color:#fff;color:#000;border:2px inset gray}@media(prefers-color-scheme: dark){#divQuery #txtLocation{background-color:#000;color:#fff;border:2px inset gray}}.autocomplete-suggestions{background-color:#fff;border:1px solid #000;position:absolute;z-index:9999}@media(prefers-color-scheme: dark){.autocomplete-suggestions{background-color:#000}}.autocomplete-suggestions div{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:21px}.autocomplete-suggestions div.selected{background-color:blue;color:#fff}#divTwc{display:block;background-color:#000;color:#fff;width:100%;max-width:640px;margin:0}#divTwc.wide{max-width:854px}.content-wrapper{padding:8px}#divTwcMain{width:640px;height:480px;position:relative}.wide #divTwcMain{width:854px}.enhanced.portrait #divTwcMain{height:1137px}.kiosk #divTwc{max-width:unset}#divTwcLeft{display:none;text-align:right;flex-direction:column;vertical-align:middle}#divTwcLeft>div{flex:1;padding-right:12px;display:flex;flex-direction:column;justify-content:center}#divTwcRight{text-align:left;display:none;flex-direction:column;vertical-align:middle}#divTwcRight>div{flex:1;padding-left:12px;display:flex;flex-direction:column;justify-content:center}#divTwcBottom{display:flex;flex-direction:row;background-color:#000;color:#fff;width:640px}.wide #divTwcBottom{width:854px}@media(prefers-color-scheme: dark){#divTwcBottom{background-color:#303030}}#divTwcBottom>div{padding-left:6px;padding-right:6px}@media(max-width: 550px){#divTwcBottom>div{font-size:.9em}}@media(max-width: 500px){#divTwcBottom>div{font-size:.8em}}@media(max-width: 450px){#divTwcBottom>div{font-size:.7em}}@media(max-width: 400px){#divTwcBottom>div{font-size:.6em}}@media(max-width: 350px){#divTwcBottom>div{font-size:.5em}}#divTwcBottomLeft{flex:1;text-align:left}#divTwcBottomMiddle{flex:0;text-align:center}#divTwcBottomRight{flex:1;text-align:right}#divTwcNavContainer{display:none}#divTwcNav{width:100%;display:flex;flex-direction:row;background-color:#000;color:#fff;max-width:640px}#divTwcNav>div{padding-left:6px;padding-right:6px}#divTwcNavLeft{flex:1;text-align:left}#divTwcNavMiddle{flex:0;text-align:center}#divTwcNavRight{flex:1;text-align:right}#imgPause1x{visibility:hidden;position:absolute}.HideCursor{cursor:none !important}#txtScrollText{width:475px}@font-face{font-family:"Star4000 Extended";src:url("../fonts/Star4000 Extended.woff") format("woff");font-display:swap}@font-face{font-family:"Star4000 Large";src:url("../fonts/Star4000 Large.woff") format("woff");font-display:swap}@font-face{font-family:"Star4000 Small";src:url("../fonts/Star4000 Small.woff") format("woff");font-display:swap}#display{font-family:"Star4000";margin:0 0 0 0;width:100%}#container{position:relative;width:640px;height:480px;background-image:url(../images/backgrounds/1.png);transform-origin:0 0;background-repeat:no-repeat}.portrait.enhanced #container{width:640px;height:1137px;background-image:url(../images/backgrounds/1-portrait.png)}.wide #container{width:854px;background:url(../images/backgrounds/1-wide.png);background-repeat:no-repeat}#divTwc:fullscreen #container,.kiosk #divTwc #container{width:unset;height:unset}#loading{width:640px;height:480px;max-width:100%;text-shadow:4px 4px #000;display:flex;align-items:center;text-align:center;justify-content:center}.wide #loading{margin-left:107px}#loading .title{font-family:Star4000 Large;font-size:36px;color:#ff0;margin-bottom:0px}#loading .version{margin-bottom:35px}#loading .instructions{font-size:24px}.heading{font-weight:bold;margin-top:15px}#settings{margin-bottom:15px}#enabledDisplays,#settings{margin-bottom:15px}#enabledDisplays .loading,#enabledDisplays .retrying,#settings Line truncated
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["scss/_page.scss","scss/shared/_positions.scss","scss/shared/_utils.scss","scss/_weather-display.scss","scss/shared/_colors.scss","scss/_current-weather.scss","scss/_extended-forecast.scss","scss/_hourly.scss","scss/_hourly-graph.scss","scss/_travel.scss","scss/_latest-observations.scss","scss/_local-forecast.scss","scss/_progress.scss","scss/_radar.scss","scss/_regional-forecast.scss","scss/_almanac.scss","scss/_hazards.scss","scss/_media.scss","scss/_spc-outlook.scss","scss/shared/_scanlines.scss"],"names":[],"mappings":"AAIA,WACC,sBAAA,CACA,gDAAA,CACA,iBAAA,CAGD,KACC,sBA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CACA,oBAAA,CACA,iCAAA,CACA,6SAAA,Line truncated
{"version":3,"sources":["scss/_page.scss","scss/shared/_positions.scss","scss/shared/_utils.scss","scss/_weather-display.scss","scss/shared/_colors.scss","scss/_current-weather.scss","scss/_extended-forecast.scss","scss/_hourly.scss","scss/_hourly-graph.scss","scss/_travel.scss","scss/_latest-observations.scss","scss/_local-forecast.scss","scss/_progress.scss","scss/_radar.scss","scss/_regional-forecast.scss","scss/_almanac.scss","scss/_hazards.scss","scss/_media.scss","scss/_spc-outlook.scss","scss/shared/_scanlines.scss"],"names":[],"mappings":"AAIA,WACC,sBAAA,CACA,gDAAA,CACA,iBAAA,CAGD,KACC,sBAAA,CACA,QAAA,CAEA,mCAJD,KAKE,qBAAA,CACA,UAAA,CAAA,CAIA,mCADD,OAEE,aAAA,CAAA,CAIF,WACC,UAAA,CACA,WAAA,CACA,eAAA,CACA,WAAA,CAEA,gCAAA,CAIF,UACC,eCnCgB,CDoChB,WAAA,CAEA,mBACC,oBAAA,CACA,WAAA,CACA,gBAAA,CAEA,8BACC,WAAA,CACA,qBAAA,CAGD,0BACC,cAAA,CACA,wBAAA,CAEA,mCAJD,0BAKE,qBAAA,CACA,UAAA,CAAA,CAQA,uCACC,YAAA,CAEA,mCAHD,uCAIE,oBAAA,CAAA,CAKD,mCADD,wCAEE,YAAA,CAAA,CAKH,qCACC,qBAAA,CAEA,mCAHD,qCAIE,qBAAA,CAAA,CAGD,yCACC,gBAAA,CAMJ,iCAEC,sBAAA,CAGD,uBACC,wBAAA,CACA,eAAA,CACA,cAAA,CACA,eAAA,CACA,oBAAA,CAGA,qBAAA,CACA,UAAA,CACA,qBAAA,CAEA,mCAZD,uBAaE,qBAAA,CACA,UAAA,CACA,qBAAA,CAAA,CAOH,0BACC,qBAAA,CACA,qBAAA,CACA,iBAAA,CACA,YAAA,CAEA,mCAND,0BAOE,qBAAA,CAAA,CAGD,8BAEC,kBAAA,CACA,eAAA,CACA,sBAAA,CACA,cAAA,CAEA,uCACC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AA,CACA,6SAAA,CAEA,8DAAA,CACA,qGAAA,CAGD,8BACC,WAAA,CAGD,4DAEC,wBAAA,CACA,4BAAA,CACA,oBAAA,CACA,+BAAA,CACA,6SAAA,CAEA,8DAAA,CACA,qGAAA,CAGD,wEAEC,WAAA,CAGD,+BACC,wBAAA,CACA,oBAAA,CACA,+BAAA,CACA,gDAAA,CACA,qBAAA,CACA,WAAA,CAGD,iCACC,aAAA,CACA,qBAAA,CACA,oBAAA,CACA,+BAAA,CAGD,8EAEC,aAAA,CAGD,kCACC,aAAA,CAAA,CAIF,mCAEC,qFAEC,yBAAA,CACA,mBAAA,CAGD,wBACC,aAAA,CACA,wBAAA,CACA,oBAAA,CACA,iCAAA,CACA,6SAAA,Line truncated
+5 -6
View File
@@ -51,7 +51,6 @@
<script type="module" src="scripts/modules/currentweather.mjs"></script>
<script type="module" src="scripts/modules/almanac.mjs"></script>
<script type="module" src="scripts/modules/spc-outlook.mjs"></script>
<script type="module" src="scripts/modules/icons.mjs"></script>
<script type="module" src="scripts/modules/extendedforecast.mjs"></script>
<script type="module" src="scripts/modules/hourly-graph.mjs"></script>
<script type="module" src="scripts/modules/hourly.mjs"></script>
@@ -150,13 +149,13 @@
</div>
<div id="divTwcBottomRight">
<div id="ToggleMediaContainer">
<div id="ToggleMedia">
<img class="navButton off" src="images/nav/ic_volume_off_white_24dp_2x.png" title="Unmute" />
<img class="navButton on" src="images/nav/ic_volume_on_white_24dp_2x.png" title="Volume" />
<div id="ToggleMedia" title="Toggle music">
<img class="navButton off" src="images/nav/ic_music_off_white_24dp_2x.png" title="Play music" />
<img class="navButton on" src="images/nav/ic_music_on_white_24dp_2x.png" title="Pause music" />
</div>
<img id="ToggleMediaVolume" class="navButton" src="images/nav/ic_volume_on_white_24dp_2x.png" title="Volume" />
<div class="volume-slider">
<input type="range" min="1" max="100" value="75" /><br>
<img class="navButton" src="images/nav/ic_volume_off_white_24dp_2x.png" title="Mute" />
<input type="range" min="1" max="100" value="75" />
</div>
</div>
<div id="ToggleScanlines">
+47 -47
View File
@@ -6,52 +6,52 @@
<div class="cloud standard-only">Cloud %</div>
<div class="rain standard-only">Precip %</div>
</div>
<div class="top chart-container">
<div class="y-axis">
<div class="label l-1">75</div>
<div class="label l-2">65</div>
<div class="label l-3">55</div>
<div class="label l-4">45</div>
</div>
<div class="chart">
<img id="chart-area"></img>
</div>
<div class="x-axis">
<div class="label l-1">12a</div>
<div class="label l-2">6a</div>
<div class="label l-3">12p</div>
<div class="label l-4">6p</div>
<div class="label l-5">12a</div>
<div class="label l-6">6a</div>
<div class="label l-7">12p</div>
</div>
</div>
<div class="bottom chart-container portrait-only">
<div class="right">
<div class="legend portrait-only">
<div class="cloud">Cloud %</div>
<div class="rain">Precip %</div>
</div>
</div>
<div class="y-axis">
<div class="label l-1">100</div>
<div class="label l-2">75%</div>
<div class="label l-3">50%</div>
<div class="label l-4">25%</div>
<div class="label l-5">0%</div>
</div>
<div class="chart">
<img id="chart-area"></img>
</div>
<div class="x-axis">
<div class="label l-1">12a</div>
<div class="label l-2">6a</div>
<div class="label l-3">12p</div>
<div class="label l-4">6p</div>
<div class="label l-5">12a</div>
<div class="label l-6">6a</div>
<div class="label l-7">12p</div>
</div>
</div>
<div class="top chart-container">
<div class="y-axis">
<div class="label l-1">75</div>
<div class="label l-2">65</div>
<div class="label l-3">55</div>
<div class="label l-4">45</div>
</div>
<div class="chart">
<canvas></canvas>
</div>
<div class="x-axis">
<div class="label l-1">12a</div>
<div class="label l-2">6a</div>
<div class="label l-3">12p</div>
<div class="label l-4">6p</div>
<div class="label l-5">12a</div>
<div class="label l-6">6a</div>
<div class="label l-7">12p</div>
</div>
</div>
<div class="bottom chart-container portrait-only">
<div class="right">
<div class="legend portrait-only">
<div class="cloud">Cloud %</div>
<div class="rain">Precip %</div>
</div>
</div>
<div class="y-axis">
<div class="label l-1">100</div>
<div class="label l-2">75%</div>
<div class="label l-3">50%</div>
<div class="label l-4">25%</div>
<div class="label l-5">0%</div>
</div>
<div class="chart">
<canvas></canvas>
</div>
<div class="x-axis">
<div class="label l-1">12a</div>
<div class="label l-2">6a</div>
<div class="label l-3">12p</div>
<div class="label l-4">6p</div>
<div class="label l-5">12a</div>
<div class="label l-6">6a</div>
<div class="label l-7">12p</div>
</div>
</div>
</div>