| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- (() => {
- const modal = document.querySelector('#weatherModal');
- const status = document.querySelector('#weatherStatus');
- const content = document.querySelector('#weatherContent');
- const refresh = document.querySelector('#weatherRefresh');
- let loadedAt = 0;
- let pending = false;
- const url = 'https://api.open-meteo.com/v1/forecast?' + new URLSearchParams({
- latitude: '54.2093', longitude: '79.7477',
- current: 'temperature_2m,apparent_temperature,is_day,precipitation,weather_code',
- daily: 'temperature_2m_max,temperature_2m_min,weather_code,sunrise,sunset',
- forecast_days: '3', timezone: 'Europe/Moscow'
- });
- const degrees = value => Number.isFinite(value) ? Math.round(value) + '°' : '—';
- function sky(code, day = 1) {
- if (code === 0) return [day ? '☀' : '☾', 'Ясно'];
- if ([1, 2].includes(code)) return ['⛅', 'Переменная облачность'];
- if (code === 3) return ['☁', 'Пасмурно'];
- if ([45, 48].includes(code)) return ['≋', 'Туман'];
- if ([51, 53, 55, 56, 57].includes(code)) return ['☂', 'Морось'];
- if ([61, 63, 65, 66, 67, 80, 81, 82].includes(code)) return ['☂', 'Дождь'];
- if ([71, 73, 75, 77, 85, 86].includes(code)) return ['❄', 'Снег'];
- if ([95, 96, 99].includes(code)) return ['ϟ', 'Гроза'];
- return ['◇', 'Нет данных'];
- }
- function clock(value) { return typeof value === 'string' && value.includes('T') ? value.split('T')[1].slice(0, 5) : '—'; }
- function render(data) {
- const current = data.current;
- const daily = data.daily;
- if (!current || !Number.isFinite(current.temperature_2m) || !daily || !Array.isArray(daily.time)) throw new Error('Incomplete forecast');
- const [icon, label] = sky(current.weather_code, current.is_day);
- const card = document.createElement('div');
- card.className = 'weather-current';
- const symbol = document.createElement('span');
- symbol.className = 'weather-icon';
- symbol.textContent = icon;
- symbol.setAttribute('aria-hidden', 'true');
- const summary = document.createElement('div');
- const temperature = document.createElement('strong');
- temperature.textContent = degrees(current.temperature_2m);
- const description = document.createElement('p');
- description.textContent = label + ' · ощущается как ' + degrees(current.apparent_temperature);
- summary.append(temperature, description);
- card.append(symbol, summary);
- const details = document.createElement('p');
- details.className = 'weather-details';
- details.textContent = 'Осадки: ' + (Number.isFinite(current.precipitation) ? current.precipitation + ' мм' : '—') + ' · Восход ' + clock(daily.sunrise?.[0]) + ' · Закат ' + clock(daily.sunset?.[0]);
- const forecast = document.createElement('div');
- forecast.className = 'weather-forecast';
- daily.time.slice(0, 3).forEach((date, index) => {
- const day = document.createElement('div');
- const title = document.createElement('span');
- title.textContent = index === 0 ? 'Сегодня' : index === 1 ? 'Завтра' : new Date(date + 'T12:00:00Z').toLocaleDateString('ru-RU', { day: 'numeric', month: 'short', timeZone: 'UTC' });
- const weather = document.createElement('span');
- const [symbol, label] = sky(daily.weather_code?.[index]);
- weather.textContent = symbol;
- weather.setAttribute('aria-label', label);
- weather.title = label;
- const range = document.createElement('strong');
- range.textContent = degrees(daily.temperature_2m_max?.[index]) + ' / ' + degrees(daily.temperature_2m_min?.[index]);
- day.append(title, weather, range);
- forecast.append(day);
- });
- content.replaceChildren(card, details, forecast);
- content.hidden = false;
- status.textContent = 'Данные на ' + clock(current.time) + ' МСК';
- }
- async function load(force = false) {
- if (pending || (!force && Date.now() - loadedAt < 600000)) return;
- pending = true;
- refresh.disabled = true;
- status.textContent = 'Загрузка прогноза…';
- const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), 12000);
- try {
- const response = await fetch(url, { signal: controller.signal });
- if (!response.ok) throw new Error('Weather unavailable');
- render(await response.json());
- loadedAt = Date.now();
- } catch {
- status.textContent = loadedAt ? 'Не удалось обновить. Показан предыдущий прогноз — попробуйте ещё раз.' : 'Погода сейчас недоступна. Проверьте интернет и нажмите «Обновить».';
- } finally {
- clearTimeout(timeout);
- pending = false;
- refresh.disabled = false;
- }
- }
- document.querySelector('#weatherButton').addEventListener('click', () => {
- modal.showModal();
- load();
- });
- refresh.addEventListener('click', () => load(true));
- })();
|