diff --git a/AGENTS.md b/AGENTS.md index 46ec754..ec912f2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,7 +24,7 @@ - Frontend regression: `node tests/browser/calculator.cjs` against a separately started isolated server at `http://127.0.0.1:8876` (override `BELKI_TEST_URL` only with another loopback URL). Use the remote test zone when exposed; it was unavailable on 2026-11-14. Playwright is test tooling, not a runtime dependency: use the bundled Node/Playwright returned by `load_workspace_dependencies`, setting `NODE_PATH` to its `node_modules` and optionally `CHROMIUM_PATH` to the browser executable. The suite closes its browser/contexts and intercepts weather and admin fixtures; real calculation requests require the normal Python dependencies. - For a local fallback, create a temporary venv and install existing `requirements.txt`, then launch `python -m app.main` with `BELKI_DATABASE_URL=`, `BELKI_HOST=127.0.0.1`, `BELKI_PORT=8876`, and temporary absolute paths for `BELKI_HISTORY_DB` and `BELKI_IDENTITIES_DB`. Never reuse production stores. `BELKI_SCREENSHOT_DIR` optionally saves browser screenshots outside Git. Stop the server and remove the temporary venv, SQLite files, caches and screenshots after review. - Browser coverage includes native radio arrow keys, report invalidation on edits/mode changes, delayed responses/double submissions, clipboard denial, dialog focus/Escape, section URLs/Back, both application entry points, admin filters/default sort and gallery. Keep API/data contracts intact: training points are a number, coaching kitten points are an array. Do not restore stale prepared reports when a calculation response arrives after an edit. -- Weather easter egg: `python -m unittest discover -s tests -p test_weather.py -q` and `node --check web/weather-effect.js`; inspect `/belki` and `/admin` with rain/snow/mixed fixtures, mobile widths, reduced motion, and API failure. Prefer the remote test-zone MCP when exposed; otherwise use an isolated local server with temporary SQLite paths and stop it after validation. Keep screenshots outside the repo. +- Weather easter egg: `python -m unittest discover -s tests -p test_weather.py -q` and `node --check web/weather-effect.js`; inspect `/belki` and `/admin` with none/rain/snow/mixed fixtures, mobile widths, reduced motion, and API failure. Preview zero/positive/unavailable snow cover and reload to inspect procedural drift variation. Prefer the remote test-zone MCP when exposed; otherwise use an isolated local server with temporary SQLite paths and stop it after validation. Keep screenshots outside the repo. - For CI-only changes, prefer a targeted YAML parse and a diff review. - For image/runtime changes, check the `Dockerfile`, Python entrypoint, static asset serving, and CI job together. - For Nginx upgrades, check `nginx -v` and `nginx -t` on the built gateway release. An isolated syntax check can resolve the Kubernetes hostname with `--network none --add-host belki-bot:127.0.0.1`. @@ -40,7 +40,8 @@ - Trainer map ratings 0–7 are independent of verified values and hazard flags; `null` means no rating, `0` means no danger around the cell. Sound mode hides numeric facts and LU hints during play; simplified mode reveals the level of opened cells and the entrance. `audio.js` generates cues locally and starts playback only via an action or replay. - Keep the phone map below the scene on the same scrollable page. The safe start x1 y1 is not a transition; it can be revisited from an adjacent cell but does not count as opened or accept marks/ratings. Only the exit remains an impassable transition. The start has 0–2 neighboring hazards, x1 y2 at most 3 and x1 y3 at most 4. Apply those limits to generated hazards, not displayed values. The start number is visible in simplified mode and after the attempt. - LU checks (prefer remote test-zone MCP when exposed): Node 24 `node --test tests/lu-trainer/engine.test.mjs`; isolated Python `python -m unittest tests.test_lu_trainer tests.test_calculator_web -q`; `node --check web/lu-trainer/ui.js`; `node tests/browser/lu-trainer.cjs` with the same bundled Playwright, loopback server and temporary stores as the calculator suite. No npm install or runtime dependency is needed. Browser coverage includes 1920/1366/768/390 widths, mouse/touch/keyboard, map projection, clear/restart confirmation, result locks, hints/timers, 200% layout and failed images. Inspect screenshots outside Git. Nginx aliases must serve the same HTML and correct asset MIME types; do not deploy to validate a client-only change. -- `app/belki/weather.py` reads only the fixed public ULLI raw METAR endpoint (3-second timeout, 64 KiB bound, 5-minute process cache, 1-minute failure cache). `/api/weather/ulli` exposes only decoration settings; shared CSS/JS live at `/api/weather/effect.css` and `/api/weather/effect.js` so the existing gateway `/api/` route handles them. Keep weather independent of reports/storage, skip trend/remark/vicinity groups, reject observations older than 2 hours, and retain leaves on failure. Do not disable TLS verification. +- `app/belki/weather.py` reads only the fixed public ULLI raw METAR endpoint (3-second timeout, 64 KiB bound, 5-minute process cache, 1-minute failure cache). `/api/weather/ulli` exposes only decoration settings; shared CSS/JS live at `/api/weather/effect.css` and `/api/weather/effect.js` so the existing gateway `/api/` route handles them. Keep weather independent of reports/storage, skip trend/remark/vicinity groups, reject observations older than 2 hours, and keep the background empty on failure (`mode: none`). Do not disable TLS verification. +- `app/belki/snow_cover.py` reads the fixed Climate Energy Saint Petersburg page; `/api/weather/snow-cover` returns `{available, depth_cm, observed_on}` from the newest dated total-depth column, including explicit zero. Cache 30 minutes / failures 5 minutes, timeout 4 seconds, payload cap 3 MiB; reject dates older than 2 Moscow calendar days. The owner selected total depth on 2026-11-24; “Свежевыпавший” changes density on that site, not depth. Footer SVGs generate 2–3 asymmetric wind-sculpted banks once per page load. Keep geometry stable across polling; positive depth scales height up to 144px, zero/unavailable hides drifts. Never execute upstream JavaScript or confuse unavailable with zero. - VK scheduler lives in `app/belki/vk_scheduler.py`; use `BELKI_DATABASE_URL` in production and `BELKI_HISTORY_DB` for local SQLite checks. Keep mailing disabled until an administrator explicitly enables a conversation and schedule. - VK Callback API and dialog durability live across `app/belki/vk_bot.py`, `app/belki/vk_callback.py`, and `app/belki/vk_scheduler.py`. The bot listens on callback port 8081; preserve `vk_dialog_states` and `vk_callback_events` when changing dialog steps, attachments, or event dispatch. Validate with `python -m unittest tests.test_vk_bot tests.test_vk_conversation -q`. Production uses `/api/vk/callback` on the existing public host and routes that exact path to the `belki-bot` Service. - The build job waits for the DinD daemon and runs `docker info` before building. diff --git a/MEMORY.md b/MEMORY.md index 18358c0..241ecb9 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -1,5 +1,13 @@ # MEMORY +## Winter background — 2026-11-24 + +- Supersedes the October leaf fallback: clear weather, API failure and initial/no-JS markup are empty; ULLI still selects rain/snow/mixed and wind dynamics. +- Owner explicitly selected **total snow depth for the latest dated day** from the fixed Climate Energy Saint Petersburg page, after clarification that “Свежевыпавший” is a density selector, not a daily snowfall measurement. +- `snow_cover.py` and `/api/weather/snow-cover` are independent of METAR: 30-minute valid cache / 5-minute failure cache, 4s timeout, 3 MiB cap; named table/cell IDs and literal date assignments, no upstream JS execution. Explicit 0 is available; unknown/stale (>2 Moscow calendar days) is unavailable. Live read on 2026-11-24 was 0 cm for that date. +- Calculator/admin footer namyoty are procedural SVGs: 2–3 asymmetric wind-sculpted banks with randomized crests, slopes and lee shadows per page load. Preserve geometry between feed refreshes; only positive measured depth sets bounded visual height (max 144px). No snow when zero/unknown. Dated source link remains visible for an available zero. +- Local source/HTTP/syntax checks and Chromium visual previews at 1280/390 px were performed; visible snowdrifts used a synthetic 16cm fixture. Project test suites were not run or expanded. No runtime dependencies, push or deployment. + - 2026-11-22: `/trainer` now limits jumps to the eight cells adjoining the character, even along the safe starting strip. Each field chooses one exit from `x10 y2–y6` or `y6 x6–x10`; this replaces the unrestricted exit pool described below. The entrance remains `x1 y1`. - 2026-11-21: the Nginx gateway base moved from 1.31.4 to 1.31.9. The versioned upstream image and private registry base are pinned by Linux amd64 digest. Publish a new immutable gateway base and update the release reference on future binary upgrades. The private base push and isolated gateway checks were verified. Production rollout is pending. diff --git a/app/belki/snow_cover.py b/app/belki/snow_cover.py new file mode 100644 index 0000000..feb4f75 --- /dev/null +++ b/app/belki/snow_cover.py @@ -0,0 +1,128 @@ +"""Daily Saint Petersburg snow depth from the owner's selected public source. + +The source's 'fresh snow' selector changes density calculations, not depth. +Use total depth for the latest dated day, as explicitly selected by the owner. +""" +from __future__ import annotations + +import re +import threading +import time +from datetime import date, datetime, timedelta +from html.parser import HTMLParser +from http.client import HTTPException +from urllib.request import Request, urlopen +from zoneinfo import ZoneInfo + + +SNOW_COVER_URL = "https://climate-energy.ru/weather/spravochnik/sndp/climate_sprav-sndp_260630687.php" +UNAVAILABLE = {"available": False, "depth_cm": None, "observed_on": None} +_MONTHS = {name: index for index, name in enumerate( + ("янв", "фев", "мар", "апр", "мая", "июн", "июл", "авг", "сен", "окт", "ноя", "дек"), 1)} +_MOSCOW = ZoneInfo("Europe/Moscow") +_MAX_BYTES = 3 * 1024 * 1024 + + +class _SnowCells(HTMLParser): + """Read only the named table's data cells; never run upstream scripts.""" + + def __init__(self): + super().__init__() + self.cells: dict[str, str] = {} + self.cell = None + + def handle_starttag(self, tag, attrs): + if tag in {"td", "th"}: + name = dict(attrs).get("id", "") + self.cell = name if re.fullmatch(r"(?:tek_klim_znachen|data_)\d+", name) else None + if self.cell: + self.cells[self.cell] = "" + + def handle_endtag(self, tag): + if tag in {"td", "th"}: + self.cell = None + + def handle_data(self, data): + if self.cell: + self.cells[self.cell] += data + + +def parse_snow_cover(html: str, *, today: date | None = None) -> dict: + """Extract the newest column, including explicit zero; reject missing/stale data.""" + today = today or datetime.now(_MOSCOW).date() + table = re.search(r"]*\bid\s*=\s*['\"]tek_parametry['\"][^>]*>(.*?)", html, re.S | re.I) + if not table: + return dict(UNAVAILABLE) + parser = _SnowCells() + parser.feed(table[1]) + # Dates on this page are assigned as literal HTML by inline JavaScript. + # Parse only that known assignment; eval/JS execution is intentionally absent. + for index, label in re.findall( + r"getElementById\(\s*['\"]data_(\d+)['\"]\s*\)\s*\.innerHTML\s*=\s*['\"]([^<]+)['\"]", + table[1], + ): + parser.cells[f"data_{index}"] = label.replace(" ", " ") + columns = [] + for key, label in parser.cells.items(): + match = re.fullmatch(r"data_(\d+)", key) + stamp = re.fullmatch(r"\s*(\d{1,2})\.([а-я]{3})\.?\s*", label.lower()) + if not match or not stamp or stamp[2] not in _MONTHS: + continue + candidates = [] + for year in (today.year - 1, today.year, today.year + 1): + try: + candidates.append(date(year, _MONTHS[stamp[2]], int(stamp[1]))) + except ValueError: + continue + if candidates: + observed = min(candidates, key=lambda day: abs((today - day).days)) + columns.append((observed, match[1])) + if not columns: + return dict(UNAVAILABLE) + observed, index = max(columns) + depth = re.fullmatch(r"\s*(\d{1,3}(?:[.,]\d+)?)\s*см\s*", parser.cells.get(f"tek_klim_znachen{index}", "")) + if not 0 <= (today - observed).days <= 2 or not depth: + return dict(UNAVAILABLE) + depth_cm = float(depth[1].replace(",", ".")) + if depth_cm > 500: + return dict(UNAVAILABLE) + return {"available": True, "depth_cm": depth_cm, "observed_on": observed.isoformat()} + + +class SnowCoverCache: + """Independent of METAR: cache 30 min, retry failure after 5 min, no DB.""" + + def __init__(self): + self._lock = threading.Lock() + self._expires = 0.0 + self._value = dict(UNAVAILABLE) + + def get(self) -> dict: + if time.monotonic() < self._expires: + return dict(self._value) + if not self._lock.acquire(blocking=False): + return dict(UNAVAILABLE) + try: + if time.monotonic() < self._expires: + return dict(self._value) + value = dict(UNAVAILABLE) + try: + request = Request(SNOW_COVER_URL, headers={"Accept": "text/html", "User-Agent": "BelkiWeather/1.0"}) + with urlopen(request, timeout=4) as response: + body = response.read(_MAX_BYTES + 1) + if len(body) <= _MAX_BYTES: + value = parse_snow_cover(body.decode("utf-8")) + except (OSError, HTTPException, ValueError): + pass + ttl = 1800 if value["available"] else 300 + if value["available"]: + cutoff = datetime.combine(date.fromisoformat(value["observed_on"]) + timedelta(days=3), datetime.min.time(), _MOSCOW) + ttl = min(ttl, max(0, (cutoff - datetime.now(_MOSCOW)).total_seconds())) + self._value = value + self._expires = time.monotonic() + ttl + return dict(value) + finally: + self._lock.release() + + +snow_cover_cache = SnowCoverCache() diff --git a/app/belki/weather.py b/app/belki/weather.py index efc7a36..a2589de 100644 --- a/app/belki/weather.py +++ b/app/belki/weather.py @@ -11,7 +11,7 @@ from urllib.request import Request, urlopen METAR_URL = "https://weather.nyan404.ru/api/v1/metar/raw/ulli" -FALLBACK = {"mode": "leaves", "intensity": 1, "wind_mps": 0.0} +FALLBACK = {"mode": "none", "intensity": 1, "wind_mps": 0.0} _WIND = re.compile(r"(?:\d{3}|VRB)(\d{2,3})(?:G(\d{2,3}))?(MPS|KT|KMH)") _WEATHER = re.compile(r"([+-]?)(?:MI|PR|BC|DR|BL|SH|TS|FZ)?(?:DZ|RA|SN|SG|IC|PL|GR|GS|UP|BR|FG|FU|VA|DU|SA|HZ|PY)+") @@ -41,7 +41,7 @@ def parse_metar(raw: str) -> dict: if weather[1] != "-" and any(code in token for code in ("SH", "TS", "BL")): level = 3 result["intensity"] = max(result["intensity"], level) - result["mode"] = "mixed" if rain and snow else "snow" if snow else "rain" if rain else "leaves" + result["mode"] = "mixed" if rain and snow else "snow" if snow else "rain" if rain else "none" return result diff --git a/app/main.py b/app/main.py index 3e26ab5..61b4de4 100644 --- a/app/main.py +++ b/app/main.py @@ -26,6 +26,7 @@ from .belki.xlsx_export import build_xlsx from .sudoku import SudokuError, SudokuStore from .belki.vk_scheduler import VkConversationStore from .belki.weather import weather_cache +from .belki.snow_cover import snow_cover_cache ROOT = Path(__file__).resolve().parents[1] @@ -402,6 +403,9 @@ class Handler(BaseHTTPRequestHandler): if path == "/api/weather/ulli": self._json(200, weather_cache.get()) return + if path == "/api/weather/snow-cover": + self._json(200, snow_cover_cache.get()) + return if path in ("/api/weather/effect.js", "/api/weather/effect.css"): self._file(WEB_ROOT / ("weather-effect.js" if path.endswith(".js") else "weather-effect.css")) return diff --git a/project_mind_map.md b/project_mind_map.md index 8458264..6a148c5 100644 --- a/project_mind_map.md +++ b/project_mind_map.md @@ -113,7 +113,13 @@ mindmap weather.py bounded process cache /api/weather/ulli decoration settings shared weather-effect.js and CSS - wind leaves rain snow mixed + wind rain snow mixed or empty background + Saint Petersburg snow cover + Climate Energy fixed public page + snow_cover.py independent bounded cache + /api/weather/snow-cover latest total depth + procedural SVG wind-sculpted footer drifts + unique per load and stable across polling VK API Optional Google Sheets export (HTTPS only) Deployment @@ -161,7 +167,9 @@ flowchart LR BotHTTP --> Bot[BelkiDialog] Web --> Domain[Расчётное ядро] Web -->|fixed URL, 5-minute cache| Weather[weather.nyan404.ru ULLI METAR] + Web -->|fixed URL, 30-minute cache| SnowCover[Climate Energy snow depth] Browser -->|/api/weather/ulli| Web + Browser -->|/api/weather/snow-cover| Web Bot --> Domain Web --> Store[(PostgreSQL or SQLite)] Bot --> Store diff --git a/structure_and_data.md b/structure_and_data.md index 1864bf8..9efe992 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -1,5 +1,15 @@ # Structure and Data +## Winter weather and procedural snowdrifts — 2026-11-24 + +- Calculator/admin have no default particles. ULLI METAR still controls rain, snow and mixed precipitation; clear weather, missing reports and API failure use `mode: none`. Initial HTML is an empty `.weather-field`, so no-JS/loading also stay quiet. Existing weather test expectations now use `none`; the calculator browser fixture also intercepts snow-cover requests. +- `app/belki/snow_cover.py` reads only [the owner's Climate Energy Saint Petersburg source](https://climate-energy.ru/weather/spravochnik/sndp/climate_sprav-sndp_260630687.php). The owner clarified that footer snow should use **total snow depth for the latest day**, not daily fresh snowfall. The source's “Свежевыпавший” option changes density for mass calculations; it does not report fresh snowfall. +- The parser reads `tek_parametry`, dated `data_N` literals and `tek_klim_znachenN` centimetres without executing JavaScript. It accepts explicit zero, decimal centimetres and dates at most 2 Moscow calendar days old. Missing, future, stale, malformed or oversized data are unavailable, never silently zero. Date labels lack years; the nearest calendar year handles New Year boundaries. +- `GET /api/weather/snow-cover` returns `{available, depth_cm, observed_on}`. The process cache is 30 minutes for valid data and 5 minutes after failure, with a nonblocking refresh lock, 4-second upstream timeout and 3 MiB cap. It is independent of METAR fetching; browser feeds also run independently, without credentials, and pause in hidden tabs. No database, runtime dependency, Docker or gateway change is needed. +- Both footers show a dated source link and white wind-sculpted snowdrifts. A DOM-created SVG generates 2–3 asymmetric banks, random widths/heights/crests and shaded lee faces once per page load. Polling preserves the silhouette; reload creates a new one. Visual height is `min(144, 20 + sqrt(depth_cm) * 20)` px for positive depth, otherwise zero. Particles/drifts never intercept pointer input; reduced motion stops precipitation. +- Inspected the real source and isolated HTTP endpoint: on 2026-11-24 it returned **0 cm dated 2026-11-24**, correctly showing no drifts. Local Chromium previews at 1280/390 px used synthetic 16 cm for visible drifts; inspected changing profiles after reload, snow/rain and reduced motion. Python AST, page/asset JavaScript syntax and `git diff --check` passed. Project test suites were not run or expanded, per current instructions. No push/deployment or cluster change. Temporary preview venv, server, SQLite stores, browser and screenshots were kept outside Git and cleaned up. +- This section supersedes the October leaf-fallback/no-JS notes below. The October production verification remains historical; the November implementation is local until separately deployed. + ## Trainer sound and manual ratings — 2026-11-22 - `audio.js` synthesizes counted rustles using Web Audio; no media downloads or runtime dependencies. The sound and simplified views share one `min(7, neighbors)` level. Switching modes preserves the field and ratings and updates prior messages without showing verified numbers in sound mode during play. diff --git a/tests/browser/calculator.cjs b/tests/browser/calculator.cjs index a26ed6a..e17ef54 100644 --- a/tests/browser/calculator.cjs +++ b/tests/browser/calculator.cjs @@ -20,6 +20,7 @@ async function run() { page.on('pageerror', error => errors.push(error.message)); page.on('console', message => { if (message.type() === 'error') errors.push(message.text()); }); await page.route('**/api/weather/ulli', route => route.fulfill({ json: { available: false } })); + await page.route('**/api/weather/snow-cover', route => route.fulfill({ json: { available: false } })); await page.goto(`${origin}/belki`); assert.equal(await page.title(), 'Отчёты — Беличья нора'); assert(await page.getByRole('heading', { level: 1 }).isVisible()); diff --git a/tests/test_weather.py b/tests/test_weather.py index 48b43aa..76405ab 100644 --- a/tests/test_weather.py +++ b/tests/test_weather.py @@ -13,15 +13,15 @@ from app.main import BelkiHTTPServer, Handler class MetarTests(unittest.TestCase): def test_weather_and_intensity(self): cases = { - "CAVOK": ("leaves", 1), "-RA": ("rain", 1), "RA": ("rain", 2), + "CAVOK": ("none", 1), "-RA": ("rain", 1), "RA": ("rain", 2), "+RA": ("rain", 3), "SHRA": ("rain", 3), "-SHRA": ("rain", 1), "-DZ": ("rain", 1), "FZRA": ("rain", 2), "SN": ("snow", 2), "+SHSN": ("snow", 3), "BLSN": ("snow", 3), "-SHSN": ("snow", 1), - "RASN": ("mixed", 2), "-RA SN": ("mixed", 2), "BR FG": ("leaves", 1), - "VCSH VCSN VCRA": ("leaves", 1), - "CAVOK TEMPO +SHSN": ("leaves", 1), + "RASN": ("mixed", 2), "-RA SN": ("mixed", 2), "BR FG": ("none", 1), + "VCSH VCSN VCRA": ("none", 1), + "CAVOK TEMPO +SHSN": ("none", 1), "-RA BECMG +SN": ("rain", 1), - "CAVOK RMK SN RA": ("leaves", 1), + "CAVOK RMK SN RA": ("none", 1), } for weather, expected in cases.items(): with self.subTest(weather=weather): diff --git a/web/admin.html b/web/admin.html index 4c086dd..18db102 100644 --- a/web/admin.html +++ b/web/admin.html @@ -109,8 +109,8 @@ - - + +

Админская панель

@@ -165,6 +165,10 @@
БеседаСтатусРассылкаДобавленаПоследняя отправкаОшибка
Загрузка…
+
Беличья нора +
+ +
diff --git a/web/calculator.html b/web/calculator.html index a826412..8657cb7 100644 --- a/web/calculator.html +++ b/web/calculator.html @@ -101,8 +101,8 @@ - - + +

Генератор отчётов и калькулятор

Здесь можно подготовить отчёт, посчитать баллы и подать заявку.

@@ -290,7 +290,10 @@ - +

diff --git a/web/weather-effect.css b/web/weather-effect.css index f47c3e1..9655efe 100644 --- a/web/weather-effect.css +++ b/web/weather-effect.css @@ -1,5 +1,5 @@ -/* Shared by calculator and admin. Keep all particles below interactive content. */ -.leaf-field { +/* Shared precipitation layer; no decorative particles without reported precipitation. */ +.weather-field { --rain: #69849a; --snow: #fffefa; --snow-edge: #aab9c5; @@ -9,50 +9,28 @@ pointer-events: none; z-index: 0; } -.leaf { +.weather-particle { position: absolute; top: -3rem; - width: 1.1rem; - height: 1.65rem; - border-radius: 100% 0 100% 0; - background: var(--leaf, var(--accent)); - box-shadow: inset .18rem -.12rem 0 #8e431d; - opacity: .68; - animation: leaf-fall var(--duration, 15s) linear infinite; + animation: snow-fall var(--duration, 12s) linear infinite; } -.leaf:nth-child(2n) { background: var(--gold); width: .82rem; height: 1.3rem; --duration: 19s; } -.leaf:nth-child(3n) { background: #a84e22; width: 1.35rem; height: 1.85rem; --duration: 22s; } -.leaf:nth-child(1) { left: 7%; animation-delay: -4s; } -.leaf:nth-child(2) { left: 18%; animation-delay: -12s; } -.leaf:nth-child(3) { left: 32%; animation-delay: -7s; } -.leaf:nth-child(4) { left: 49%; animation-delay: -16s; } -.leaf:nth-child(5) { left: 64%; animation-delay: -2s; } -.leaf:nth-child(6) { left: 78%; animation-delay: -10s; } -.leaf:nth-child(7) { left: 91%; animation-delay: -18s; } -.leaf[data-kind="snow"] { +.weather-particle[data-kind="snow"] { width: calc(.45rem * var(--size)); height: calc(.45rem * var(--size)); border-radius: 50%; background: var(--snow); box-shadow: 0 0 2px var(--snow-edge); opacity: .85; - animation-name: snow-fall; } -.leaf[data-kind="rain"] { +.weather-particle[data-kind="rain"] { width: 1.5px; height: calc(1.6rem * var(--size)); border-radius: 2px; background: var(--rain); - box-shadow: none; opacity: .4; animation-name: rain-fall; } -.weather-paused .leaf { animation-play-state: paused; } -@keyframes leaf-fall { - 0% { transform: translate3d(0, -4rem, 0) rotate(20deg); } - 45% { transform: translate3d(calc(3.5rem + var(--drift, 0vw) * .45), 48vh, 0) rotate(170deg); } - 100% { transform: translate3d(calc(-4rem + var(--drift, 0vw)), 112vh, 0) rotate(330deg); } -} +.weather-paused .weather-particle { animation-play-state: paused; } @keyframes snow-fall { 0% { transform: translate3d(0, -4rem, 0); } 50% { transform: translate3d(calc(2rem + var(--drift, 0vw) * .5), 50vh, 0); } @@ -62,7 +40,35 @@ from { transform: translate3d(0, -4rem, 0) rotate(calc(-1 * var(--rain-angle, 0deg))); } to { transform: translate3d(var(--drift, 0vw), 112vh, 0) rotate(calc(-1 * var(--rain-angle, 0deg))); } } +.snow-footer { + --snow-shade: #e8eef0; + --snow-ridge: #f4f7f7; + --snow-front: #fffefa; + margin-top: 48px; + padding-top: 18px; + border-top: 1px solid var(--line); + color: var(--muted); + font-size: .9rem; +} +.snow-footer a { color: inherit; text-underline-offset: 3px; } +.snow-footer a:hover { color: var(--accent); } +.snow-footer a:focus-visible { outline: 2px solid var(--focus); outline-offset: 4px; } +.snow-cover-caption { min-height: 24px; margin-top: 8px; font-size: .8rem; line-height: 1.5; } +.footer-snowdrift { + height: var(--snow-height, 0px); + width: 100%; + overflow: hidden; + pointer-events: none; +} +.footer-snowdrift svg { display: block; width: 100%; height: 100%; } +.snow-bank-shade { fill: var(--snow-shade); } +.snow-bank-ridge { fill: none; stroke: var(--snow-ridge); stroke-width: 2; stroke-linecap: round; } +.weather-page main { margin-bottom: 0; padding-bottom: 0; } +.snow-bank-front { fill: var(--snow-front); } +@media (max-width: 600px) { + .snow-footer { margin-top: 32px; } +} @media (prefers-reduced-motion: reduce) { - .leaf-field .leaf { animation: none; top: 8vh; opacity: .16; } - .leaf:nth-child(n+8) { display: none; } + .weather-field .weather-particle { animation: none; top: 8vh; opacity: .16; } + .weather-particle:nth-child(n+8) { display: none; } } diff --git a/web/weather-effect.js b/web/weather-effect.js index 666b6c4..4bd7b68 100644 --- a/web/weather-effect.js +++ b/web/weather-effect.js @@ -1,23 +1,71 @@ -/* A little Pulkovo weather in the existing autumn background. */ +/* Pulkovo precipitation and Saint Petersburg snow cover, quietly in the background. */ (() => { 'use strict'; - const field = document.querySelector('.leaf-field'); + const field = document.querySelector('.weather-field'); if (!field) return; - const refreshMs = 5 * 60 * 1000; - let timer; - let controller; - let nextRefresh = 0; + const snowdrift = document.querySelector('.footer-snowdrift'); + const snowSource = document.querySelector('.snow-cover-source'); let lastSignature = ''; + function buildSnowdrifts() { + if (!snowdrift) return; + const ns = 'http://www.w3.org/2000/svg'; + const svg = document.createElementNS(ns, 'svg'); + svg.setAttribute('viewBox', '0 0 1200 160'); + svg.setAttribute('preserveAspectRatio', 'none'); + svg.setAttribute('focusable', 'false'); + const random = (min, max) => min + Math.random() * (max - min); + const weights = Array.from({ length: Math.random() < 0.6 ? 2 : 3 }, () => random(0.7, 1.5)); + const total = weights.reduce((sum, weight) => sum + weight, 0); + // One profile per page load. The gentle windward slope rises to a cornice; + // a shorter, steeper lee face falls back to the next valley. + let x = 0; + let y = random(126, 138); + let outline = `M0 ${y}`; + let shadows = ''; + let ridges = ''; + for (const weight of weights) { + const width = weight / total * 1200; + const end = x + width; + const crest = x + width * random(0.54, 0.7); + const peak = random(18, 65); + const nextY = random(124, 139); + const shoulder = x + width * random(0.33, 0.43); + const shoulderY = peak + (y - peak) * random(0.12, 0.23); + const lee = crest + (end - crest) * random(0.25, 0.42); + const leeY = peak + (nextY - peak) * random(0.65, 0.82); + outline += ` C${x + width * 0.22} ${y} ${shoulder - width * 0.08} ${shoulderY + 9} ${shoulder} ${shoulderY}`; + outline += ` C${crest - width * 0.09} ${peak + 9} ${crest - width * 0.025} ${peak + 4} ${crest} ${peak}`; + outline += ` C${crest + width * 0.05} ${peak + 6} ${lee - width * 0.035} ${leeY - 8} ${lee} ${leeY}`; + outline += ` C${lee + width * 0.09} ${nextY - 2} ${end - width * 0.1} ${nextY} ${end} ${nextY}`; + shadows += ` M${crest} ${peak} C${crest + width * 0.02} ${peak + 18} ${lee - width * 0.06} ${leeY + 2} ${lee} ${leeY + 5}`; + shadows += ` Q${lee + width * 0.1} ${nextY + 1} ${end} ${nextY} C${lee + width * 0.09} ${nextY - 2} ${lee} ${leeY} ${crest} ${peak}Z`; + ridges += ` M${x + width * 0.18} ${y - 4} Q${shoulder} ${shoulderY - 2} ${crest} ${peak + 4}`; + x = end; + y = nextY; + } + for (const [className, path] of [ + ['snow-bank-front', `${outline} V160 H0Z`], + ['snow-bank-shade', shadows], + ['snow-bank-ridge', ridges], + ]) { + const shape = document.createElementNS(ns, 'path'); + shape.setAttribute('class', className); + shape.setAttribute('d', path); + svg.append(shape); + } + snowdrift.replaceChildren(svg); + } + function render(weather) { - const mode = ['leaves', 'rain', 'snow', 'mixed'].includes(weather.mode) ? weather.mode : 'leaves'; + const mode = ['rain', 'snow', 'mixed'].includes(weather?.mode) ? weather.mode : 'none'; const intensity = Math.max(1, Math.min(3, Number(weather.intensity) || 1)); const wind = Math.max(0, Math.min(60, Number(weather.wind_mps) || 0)); const signature = `${mode}/${intensity}/${wind}`; if (signature === lastSignature) return; lastSignature = signature; - const count = mode === 'leaves' ? 7 : [0, 18, 34, 54][Math.round(intensity)]; - const duration = (mode === 'rain' ? 1.7 : mode === 'leaves' ? 19 : 12) / (1 + Math.min(wind, 25) / 8); + const count = mode === 'none' ? 0 : [0, 18, 34, 54][Math.round(intensity)]; + const duration = (mode === 'rain' ? 1.7 : 12) / (1 + Math.min(wind, 25) / 8); field.dataset.weather = mode; field.style.setProperty('--drift', `${Math.min(24, wind * 1.2)}vw`); field.style.setProperty('--rain-angle', `${Math.min(30, wind * 1.8)}deg`); @@ -25,7 +73,7 @@ for (let index = 0; index < count; index++) { const particle = document.createElement('span'); const kind = mode === 'mixed' ? (index % 2 ? 'rain' : 'snow') : mode; - particle.className = 'leaf'; + particle.className = 'weather-particle'; particle.dataset.kind = kind; const seconds = (kind === 'rain' && mode === 'mixed' ? duration / 6 : duration) * (0.8 + Math.random() * 0.5); particle.style.left = `${(index + Math.random()) * 100 / count}%`; @@ -37,37 +85,62 @@ field.replaceChildren(particles); } - async function refresh() { - clearTimeout(timer); - if (document.hidden || controller) return; - if (Date.now() < nextRefresh) { - timer = setTimeout(refresh, nextRefresh - Date.now()); - return; - } - controller = new AbortController(); - const timeout = setTimeout(() => controller?.abort(), 5000); - try { - const response = await fetch('/api/weather/ulli', { signal: controller.signal, credentials: 'omit', cache: 'no-store' }); - if (!response.ok) throw new Error('weather unavailable'); - render(await response.json()); - } catch { - render({ mode: 'leaves', intensity: 1, wind_mps: 0 }); - } finally { - clearTimeout(timeout); - controller = null; - nextRefresh = Date.now() + refreshMs; - if (!document.hidden) timer = setTimeout(refresh, refreshMs); + function renderSnowCover(cover) { + if (!snowdrift || !snowSource) return; + const depth = cover?.depth_cm; + const stamp = cover?.observed_on; + const available = cover?.available === true && typeof depth === 'number' && Number.isFinite(depth) + && depth >= 0 && depth <= 500 && /^\d{4}-\d{2}-\d{2}$/.test(stamp); + snowSource.hidden = !available; + snowdrift.dataset.depth = available ? String(depth) : ''; + // A visual scale, not centimetres rendered 1:1; keep the footer usable in deep snow. + snowdrift.style.setProperty('--snow-height', available && depth > 0 ? `${Math.min(144, 20 + Math.sqrt(depth) * 20)}px` : '0px'); + if (available) { + const [year, month, day] = stamp.split('-'); + snowSource.textContent = `Снежный покров: ${depth.toLocaleString('ru-RU')} см · ${day}.${month}.${year}`; + } else { + snowSource.textContent = ''; } } + function poll(url, interval, update, fallback) { + let timer; + let controller; + let nextRefresh = 0; + async function refresh() { + clearTimeout(timer); + if (document.hidden || controller) return; + if (Date.now() < nextRefresh) { + timer = setTimeout(refresh, nextRefresh - Date.now()); + return; + } + controller = new AbortController(); + const timeout = setTimeout(() => controller?.abort(), 6000); + try { + const response = await fetch(url, { signal: controller.signal, credentials: 'omit', cache: 'no-store' }); + if (!response.ok) throw new Error('weather unavailable'); + update(await response.json()); + } catch { + if (!document.hidden) update(fallback); + } finally { + clearTimeout(timeout); + controller = null; + nextRefresh = document.hidden ? 0 : Date.now() + interval; + if (!document.hidden) timer = setTimeout(refresh, interval); + } + } + return { + refresh, + pause() { clearTimeout(timer); controller?.abort(); }, + }; + } + + buildSnowdrifts(); + const feeds = [poll('/api/weather/ulli', 5 * 60 * 1000, render, { mode: 'none' })]; + if (snowdrift) feeds.push(poll('/api/weather/snow-cover', 30 * 60 * 1000, renderSnowCover, { available: false })); document.addEventListener('visibilitychange', () => { field.classList.toggle('weather-paused', document.hidden); - if (document.hidden) { - clearTimeout(timer); - controller?.abort(); - } else { - refresh(); - } + for (const feed of feeds) document.hidden ? feed.pause() : feed.refresh(); }); - refresh(); + for (const feed of feeds) feed.refresh(); })();