/
GhostLogic
/
SudakOnline
Обзор
Документация
Войти
/
GhostLogic
/
SudakOnline
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
fix.php
313 строк
11 KB
GhostLogic
Загрузить файлы в «»
28 апр 2026, 18:11
Верифицирован
28 апр 2026, 18:11
3c10f40
Код
Авторство
О чём код?
<?php /** * Диагностика и исправление виджета погоды. * Заменяет Weather.js, Weather.css и принудительно включает отображение. * Запуск: php fix-weather-debug.php */ $root = __DIR__; // 1. Новый Weather.js с отладкой и принудительным включением $jsFile = $root . '/pwa/widgets/Weather/Weather.js'; $newJs = <<<'JS' let WidgetWeather = { isUpdating: false, lastUpdateTime: 0, updateInterval: 300000, // 5 минут load: () => { console.log('[Weather] Загрузка виджета'); const w = WidgetWeather; w.iconElem = document.querySelector(".weather-widget .weather-icon i"); w.tempElem = document.querySelector(".weather-widget .weather-temp"); w.descElem = document.querySelector(".weather-widget .weather-desc"); w.windElem = document.querySelector(".weather-widget .wind-speed"); w.locationElem = document.querySelector(".weather-widget .location-name"); w.timeStampElem = document.querySelector(".weather-widget .weather-timestamp"); // Принудительно включаем виджет (для теста) localStorage.setItem('setting.widgets-enabled', 'true'); localStorage.setItem('setting.widget-weather-enabled', 'true'); setTimeout(() => WidgetWeather.update(true), 1000); }, enabled(state = null) { // Всегда включено для тестирования if (state === null) return true; if (state) { localStorage.setItem('setting.widgets-enabled', 'true'); localStorage.setItem('setting.widget-weather-enabled', 'true'); } else { localStorage.setItem('setting.widget-weather-enabled', 'false'); } return state; }, update: async function (force = false) { const widget = document.querySelector(".weather-widget"); if (!widget) { console.error('[Weather] Виджет не найден в DOM'); return; } // Показываем виджет всегда (убрали проверку на раздел) widget.style.display = 'flex'; if (!force && (Date.now() - WidgetWeather.lastUpdateTime) < WidgetWeather.updateInterval) return; if (WidgetWeather.isUpdating) return; WidgetWeather.isUpdating = true; try { // Сначала показываем кэш, если есть const cachedData = WidgetWeather.getLocalCache(); if (cachedData && cachedData.success) { console.log('[Weather] Загружено из кэша'); WidgetWeather.applyWeatherData(cachedData); } else { WidgetWeather.showLoading(); } // Пытаемся обновить из сети if (navigator.onLine) { const weatherData = await WidgetWeather.fetchWeather(); if (weatherData && weatherData.success) { console.log('[Weather] Получены свежие данные', weatherData); WidgetWeather.applyWeatherData(weatherData); WidgetWeather.setLocalCache(weatherData); WidgetWeather.lastUpdateTime = Date.now(); } else if (!cachedData) { console.warn('[Weather] Нет данных из сети и кэша, показываем заглушку'); WidgetWeather.showOfflinePlaceholder(); } } else if (!cachedData) { WidgetWeather.showOfflinePlaceholder(); } } catch (err) { console.error('[Weather] Ошибка обновления:', err); if (!WidgetWeather.getLocalCache()) WidgetWeather.showOfflinePlaceholder(); } finally { WidgetWeather.isUpdating = false; } }, showLoading: () => { if (WidgetWeather.iconElem) { WidgetWeather.iconElem.className = 'fas fa-spinner fa-pulse'; WidgetWeather.iconElem.style.color = '#2c7da0'; } if (WidgetWeather.tempElem) WidgetWeather.tempElem.innerHTML = '--°'; if (WidgetWeather.descElem) WidgetWeather.descElem.innerHTML = 'Загрузка...'; if (WidgetWeather.windElem) WidgetWeather.windElem.innerHTML = '--'; if (WidgetWeather.locationElem) WidgetWeather.locationElem.innerHTML = 'Судак, Крым'; if (WidgetWeather.timeStampElem) WidgetWeather.timeStampElem.innerHTML = '...'; }, showOfflinePlaceholder: () => { if (WidgetWeather.iconElem) { WidgetWeather.iconElem.className = 'fas fa-exclamation-triangle'; WidgetWeather.iconElem.style.color = '#e67e22'; } if (WidgetWeather.tempElem) WidgetWeather.tempElem.innerHTML = 'Погода'; if (WidgetWeather.descElem) WidgetWeather.descElem.innerHTML = 'нет данных'; if (WidgetWeather.windElem) WidgetWeather.windElem.innerHTML = '--'; if (WidgetWeather.locationElem) WidgetWeather.locationElem.innerHTML = 'Судак, Крым'; if (WidgetWeather.timeStampElem) WidgetWeather.timeStampElem.innerHTML = ''; }, applyWeatherData: (data) => { if (!data.success || !data.data) { console.warn('[Weather] Нет данных в ответе', data); return; } const d = data.data; const temp = Math.round(d.temperature); const wind = d.wind_speed || 0; if (WidgetWeather.tempElem) WidgetWeather.tempElem.innerHTML = `${temp}°C`; if (WidgetWeather.windElem) WidgetWeather.windElem.innerHTML = wind; if (WidgetWeather.descElem) WidgetWeather.descElem.innerHTML = d.description; if (WidgetWeather.locationElem) WidgetWeather.locationElem.innerHTML = d.location || 'Судак, Крым'; if (WidgetWeather.iconElem) { WidgetWeather.iconElem.className = d.icon; WidgetWeather.iconElem.style.color = d.icon_color || '#2c7da0'; } const timestamp = d.timestamp || Date.now(); const timeObj = new Date(timestamp); const timeStr = `${timeObj.getHours().toString().padStart(2,'0')}:${timeObj.getMinutes().toString().padStart(2,'0')}`; if (WidgetWeather.timeStampElem) WidgetWeather.timeStampElem.innerHTML = timeStr; console.log('[Weather] Данные применены', temp, d.description); }, fetchWeather: async function () { if (!navigator.onLine) return null; try { const response = await Application.api.getWeather(); console.log('[Weather] Ответ API:', response); return response; } catch (err) { console.error('[Weather] Ошибка запроса к API:', err); return null; } }, setLocalCache: (data) => { try { const cacheData = { ...data, cached_at: Date.now() }; localStorage.setItem("setting.widget-weather-last-data", JSON.stringify(cacheData)); } catch (e) {} }, getLocalCache: () => { try { const cached = localStorage.getItem("setting.widget-weather-last-data"); return cached ? JSON.parse(cached) : null; } catch (e) { return null; } } }; // Гарантируем, что виджет загрузится после DOM if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => WidgetWeather.load()); } else { WidgetWeather.load(); } JS; file_put_contents($jsFile, $newJs); echo "✅ pwa/widgets/Weather/Weather.js обновлён (с отладкой)\n"; // 2. Обновляем CSS, чтобы виджет всегда отображался и был заметен $cssFile = $root . '/pwa/widgets/Weather/Weather.css'; $debugCss = <<<'CSS' .weather-widget { display: flex !important; flex-direction: column; background: #ffffff; border-radius: 40px; padding: 8px 16px; margin: 6px 10px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); color: #1e293b; } .weather-line { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; row-gap: 4px; } .weather-icon { font-size: 1.6rem; width: 34px; text-align: center; color: #2c7da0; line-height: 1; } .weather-temp { font-size: 1.3rem; font-weight: 700; color: #1e293b; white-space: nowrap; } .weather-desc { font-size: 0.8rem; background: #eef2ff; padding: 4px 12px; border-radius: 30px; color: #2c7da0; white-space: nowrap; } .weather-wind { font-size: 0.75rem; color: #475569; white-space: nowrap; } .weather-wind i { margin-right: 4px; color: #2c7da0; } .weather-location { font-size: 0.7rem; color: #64748b; white-space: nowrap; } .weather-location i { margin-right: 4px; color: #2c7da0; } .weather-timestamp { font-size: 0.6rem; color: #94a3b8; margin-left: auto; white-space: nowrap; } @media (max-width: 550px) { .weather-widget { padding: 6px 12px; } .weather-line { gap: 8px; } .weather-icon { font-size: 1.3rem; width: 28px; } .weather-temp { font-size: 1.1rem; } .weather-desc { font-size: 0.7rem; padding: 2px 8px; } .weather-wind, .weather-location { font-size: 0.65rem; } } body.dark-mode .weather-widget { background: #1e293b; } body.dark-mode .weather-temp { color: #f1f5f9; } body.dark-mode .weather-desc { background: #2d3a4b; color: #7aa2f7; } body.dark-mode .weather-wind { color: #cbd5e1; } body.dark-mode .weather-location { color: #94a3b8; } body.dark-mode .weather-wind i, body.dark-mode .weather-location i { color: #7aa2f7; } body.dark-mode .weather-timestamp { color: #64748b; } CSS; file_put_contents($cssFile, $debugCss); echo "✅ pwa/widgets/Weather/Weather.css обновлён (принудительное отображение)\n"; echo "\n🎉 Скрипт завершён.\n"; echo "Теперь:\n"; echo "1. Откройте PWA в браузере.\n"; echo "2. Откройте консоль разработчика (F12) и посмотрите сообщения [Weather].\n"; echo "3. Виджет должен отображаться. Если нет — проверьте, есть ли в консоли ошибки.\n"; echo "4. Если API не отвечает, виджет покажет кэшированные данные или заглушку.\n"; echo "5. После проверки можно вернуться к обычной версии, убрав принудительное включение.\n";