From 98182c179f12586ab532e684ec57f2c1d4f039ca Mon Sep 17 00:00:00 2001 From: Nyan404 Date: Sun, 18 Oct 2026 20:02:32 +0300 Subject: [PATCH] Add ULLI weather easter egg to falling background particles --- AGENTS.md | 2 + MEMORY.md | 4 ++ app/belki/weather.py | 96 ++++++++++++++++++++++++++++++ app/main.py | 7 +++ project_mind_map.md | 7 +++ structure_and_data.md | 7 +++ tests/test_weather.py | 131 +++++++++++++++++++++++++++++++++++++++++ web/admin.html | 10 +--- web/calculator.html | 15 +---- web/weather-effect.css | 68 +++++++++++++++++++++ web/weather-effect.js | 73 +++++++++++++++++++++++ 11 files changed, 399 insertions(+), 21 deletions(-) create mode 100644 app/belki/weather.py create mode 100644 tests/test_weather.py create mode 100644 web/weather-effect.css create mode 100644 web/weather-effect.js diff --git a/AGENTS.md b/AGENTS.md index 12759e0..9c5a0ec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,6 +18,7 @@ - For web UI work, use the project-local `.codex/skills/frontend-craft`, `.codex/skills/frontend-design`, and `.codex/skills/ui-ux-pro-max` instructions: establish a deliberate visual direction, preserve accessibility and interaction quality, then inspect the rendered result. ## Validation +- 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. - 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 k3s changes, validate YAML and current cluster inventory first; keep `KUBE_CONFIG_B64` masked/protected in GitLab. @@ -26,6 +27,7 @@ - Public report lookup is `GET /api/reports?character_id=`; it searches saved report participant IDs, returns at most 100 newest rows without `actor_id`, and is covered by `tests/test_report_lookup.py`. VK `/мои-отчёты` uses the callback sender ID and the same history store; validate with `python -m unittest tests.test_report_lookup tests.test_history tests.test_vk_bot -q`. ## Notes +- `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. - 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 5eb647d..12ffd9f 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -122,3 +122,7 @@ Inspection results persist the base score for the number of inspections and each # 2026-10-13: persistent cat-name changes `IdentityDirectory.rename_existing()` is the only write path for the user-facing rename feature. It requires an existing character ID, updates `identities` and denormalized `profiles` names in PostgreSQL/SQLite, removes the stale old-name index entry, and refreshes cached profiles. The VK dialog starts from the `Изменить имя кота` menu button and asks for ID then a new name. The web `/belki` `Имя кота` tab looks up the current name and submits `/api/rename-identity`; `/api/resolve-identity` remains stateless for report form completion. + +## ULLI background weather — 2026-10-18 + +Calculator/admin share `web/weather-effect.js` and `.css`, served through `/api/weather/effect.*` so existing gateway routing works. `app/belki/weather.py` reads only the fixed public ULLI raw METAR endpoint: observed wind/gusts control speed/drift, RA/DZ and SN/SG select rain/snow/mixed particles, intensity controls density. Trends/remarks/vicinity do not change observed weather. The cache is process-local (5 min success, 1 min failure), timeout 3 s, payload cap 64 KiB; observations expire after 2 h. Failure restores leaves. Browser polling is every 5 min, hidden tabs pause, reduced motion keeps at most seven faint static particles. No dependencies or storage changes. Remote test-zone MCP was unavailable; local fixtures and browser checks were used. On this Mac, Python HTTPS required `SSL_CERT_FILE=/etc/ssl/cert.pem`; never bypass TLS verification. Production is unverified until a separately requested push/deployment. diff --git a/app/belki/weather.py b/app/belki/weather.py new file mode 100644 index 0000000..efc7a36 --- /dev/null +++ b/app/belki/weather.py @@ -0,0 +1,96 @@ +"""Small, read-only ULLI weather effect; independent of calculation/storage.""" +from __future__ import annotations + +import json +import re +import threading +import time +from datetime import datetime, timezone +from http.client import HTTPException +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} +_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)+") + + +def parse_metar(raw: str) -> dict: + """Read observed wind/precipitation only, ignoring trends, vicinity and remarks.""" + result = dict(FALLBACK) + rain = snow = False + for token in raw.upper().split(): + if token in {"RMK", "TEMPO", "BECMG", "NOSIG"} or re.fullmatch(r"(?:FM|TL|AT)\d{4}", token): + break + wind = _WIND.fullmatch(token) + if wind: + speed = max(int(wind[1]), int(wind[2] or 0)) + result["wind_mps"] = round(min(60, speed * {"KT": 0.514444, "MPS": 1, "KMH": 1 / 3.6}[wind[3]]), 2) + weather = _WEATHER.fullmatch(token) + if not weather: + continue + has_rain = "RA" in token or "DZ" in token + has_snow = "SN" in token or "SG" in token + if not (has_rain or has_snow): + continue + rain |= has_rain + snow |= has_snow + level = 1 if weather[1] == "-" else 3 if weather[1] == "+" else 2 + # Showers and blowing snow are visibly fuller, but -SHSN stays light. + 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" + return result + + +class WeatherCache: + """One bounded upstream request per process/5 min; failures retry after 1 min. + + Concurrent visitors get the quiet fallback instead of waiting on the lock. + Stale or invalid observations never keep a storm running on the page. + """ + + def __init__(self): + self._lock = threading.Lock() + self._expires = 0.0 + self._value = dict(FALLBACK) + + def get(self) -> dict: + if time.monotonic() < self._expires: + return dict(self._value) + if not self._lock.acquire(blocking=False): + return dict(FALLBACK) + try: + if time.monotonic() < self._expires: + return dict(self._value) + value = dict(FALLBACK) + ttl = 60 + try: + request = Request(METAR_URL, headers={"Accept": "application/json"}) + with urlopen(request, timeout=3) as response: + body = response.read(65_537) + if len(body) > 65_536: + raise ValueError("oversized METAR") + payload = json.loads(body) + item = payload["item"] + if payload.get("found") is not True or item.get("station_id") != "ULLI": + raise ValueError("missing ULLI") + observed = datetime.fromisoformat(item["observation_time"].replace("Z", "+00:00")) + age = (datetime.now(timezone.utc) - observed).total_seconds() + raw = item["raw_metar"] + if not -600 <= age <= 7200 or not isinstance(raw, str) or not raw.strip(): + raise ValueError("stale or invalid METAR") + value = parse_metar(raw) + ttl = min(300, 7200 - max(0, age)) + except (OSError, HTTPException, ValueError, KeyError, TypeError, AttributeError): + pass # Decoration must not expose upstream errors or break the form. + self._value = value + self._expires = time.monotonic() + ttl + return dict(value) + finally: + self._lock.release() + + +weather_cache = WeatherCache() diff --git a/app/main.py b/app/main.py index fdc6426..0adf540 100644 --- a/app/main.py +++ b/app/main.py @@ -24,6 +24,7 @@ from .belki.image_host import ImageHostError, ImageStoreClient from .belki.xlsx_export import build_xlsx from .sudoku import SudokuError, SudokuStore from .belki.vk_scheduler import VkConversationStore +from .belki.weather import weather_cache ROOT = Path(__file__).resolve().parents[1] @@ -377,6 +378,12 @@ class Handler(BaseHTTPRequestHandler): if path in ("/health", "/api/health"): self._json(200, {"status": "ok"}) return + if path == "/api/weather/ulli": + self._json(200, weather_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 if path in ("/", "/belki", "/belki/", "/calculator.html"): self._file(WEB_ROOT / "calculator.html") return diff --git a/project_mind_map.md b/project_mind_map.md index e62f8e7..4d835c8 100644 --- a/project_mind_map.md +++ b/project_mind_map.md @@ -88,6 +88,11 @@ mindmap bucket-scoped GetObject PutObject GetBucketLocation account public proxy /api/images/id Integrations + Pulkovo ULLI raw METAR + weather.py bounded process cache + /api/weather/ulli decoration settings + shared weather-effect.js and CSS + wind leaves rain snow mixed VK API Optional Google Sheets export (HTTPS only) Deployment @@ -134,6 +139,8 @@ flowchart LR Gateway -->|exact route| BotHTTP[belki-bot :8081] BotHTTP --> Bot[BelkiDialog] Web --> Domain[Расчётное ядро] + Web -->|fixed URL, 5-minute cache| Weather[weather.nyan404.ru ULLI METAR] + Browser -->|/api/weather/ulli| Web Bot --> Domain Web --> Store[(PostgreSQL or SQLite)] Bot --> Store diff --git a/structure_and_data.md b/structure_and_data.md index 2db2928..4cd0c93 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -1,5 +1,12 @@ # Structure and Data +## ULLI weather easter egg — 2026-10-18 + +- `app/belki/weather.py` fetches the fixed `https://weather.nyan404.ru/api/v1/metar/raw/ulli` endpoint and extracts observed wind (MPS/KT/KMH, including gusts), rain/drizzle, snow and mixed precipitation. Trend, remark and vicinity groups are ignored. Light, moderate, heavy/shower/blowing-snow effects change particle density; wind changes speed and drift. +- `/api/weather/ulli` returns only `{mode, intensity, wind_mps}`. A 5-minute in-memory cache, nonblocking refresh lock, 3-second upstream timeout, 64 KiB response cap and 1-minute failure cache bound the work. Missing, invalid, future (>10 min) or stale (>2 h) observations restore leaves. No database, credentials or new dependencies are involved. +- `web/weather-effect.js` and `.css` are shared by calculator/admin and served through explicit `/api/weather/effect.js` and `.css` routes. This keeps them behind the existing gateway `/api/` proxy without a gateway/base-image change. Browser refreshes every 5 minutes, pauses animation/polling in hidden tabs, and respects reduced motion. Existing seven-leaf markup remains the no-JS fallback. +- Validation used an isolated local server because no remote test-zone MCP was exposed. Weather/parser/cache/HTTP tests, calculator/admin checks and browser fixtures cover desktop (1280 px), mobile (390 px), rain/snow/mixed/leaves, wind acceleration, reduced motion and failed API fallback. Screenshots/scripts and temporary SQLite data live under `/tmp`, outside Git; stop the test server/browser after use. macOS Python needed `SSL_CERT_FILE=/etc/ssl/cert.pem` for the live weather smoke check; TLS verification stays enabled. No push or deployment. + ## Repository Layout - [`.gitlab-ci.yml`](./.gitlab-ci.yml): existing single-stage GitLab pipeline targeting the Belki image. - [`Dockerfile`](./Dockerfile): Python 3.12 runtime image for the calculator web service and shared static assets. diff --git a/tests/test_weather.py b/tests/test_weather.py new file mode 100644 index 0000000..48b43aa --- /dev/null +++ b/tests/test_weather.py @@ -0,0 +1,131 @@ +import http.client +import json +import threading +import unittest +from datetime import datetime, timedelta, timezone +from http.client import IncompleteRead +from unittest.mock import MagicMock, patch + +from app.belki.weather import FALLBACK, WeatherCache, parse_metar +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), + "+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), + "-RA BECMG +SN": ("rain", 1), + "CAVOK RMK SN RA": ("leaves", 1), + } + for weather, expected in cases.items(): + with self.subTest(weather=weather): + result = parse_metar(f"METAR ULLI 181630Z 34003MPS {weather}") + self.assertEqual((result["mode"], result["intensity"]), expected) + + def test_wind_units_gusts_and_calm(self): + for token, expected in [("34003MPS", 3), ("VRB05G15MPS", 15), ("27010G20KT", 10.29), + ("12036KMH", 10), ("00000KT", 0), ("/////KT", 0), ("270199KT", 60)]: + with self.subTest(token=token): + self.assertAlmostEqual(parse_metar(f"ULLI {token} CAVOK TEMPO 27050MPS")["wind_mps"], expected, places=2) + + +class WeatherCacheTests(unittest.TestCase): + def payload(self, age=0): + return {"found": True, "item": {"station_id": "ULLI", "raw_metar": "METAR ULLI 181630Z 27010G15MPS +SHSN", + "observation_time": (datetime.now(timezone.utc) - timedelta(seconds=age)).isoformat()}} + + def opener(self, payload): + response = MagicMock() + response.__enter__.return_value.read.return_value = json.dumps(payload).encode() + return response + + def test_caches_result_and_bounds_upstream_request(self): + cache = WeatherCache() + with patch("app.belki.weather.urlopen", return_value=self.opener(self.payload())) as opened: + first = cache.get() + self.assertEqual(first, {"mode": "snow", "intensity": 3, "wind_mps": 15}) + first["mode"] = "rain" + self.assertEqual(cache.get()["mode"], "snow") + opened.assert_called_once() + self.assertEqual(opened.call_args.kwargs["timeout"], 3) + self.assertEqual(opened.return_value.__enter__.return_value.read.call_args.args, (65_537,)) + + def test_invalid_stale_future_and_absent_reports_fall_back(self): + invalid = [self.payload(7201), self.payload(-601), {"found": False, "item": None}, [], + {"found": True, "item": {"station_id": "UUDD"}}] + for payload in invalid: + with self.subTest(payload=payload), patch("app.belki.weather.urlopen", return_value=self.opener(payload)) as opened: + cache = WeatherCache() + self.assertEqual(cache.get(), FALLBACK) + self.assertEqual(cache.get(), FALLBACK) + opened.assert_called_once() + + def test_network_error_resets_previous_weather_and_is_cached(self): + cache = WeatherCache() + with patch("app.belki.weather.urlopen", return_value=self.opener(self.payload())): + self.assertEqual(cache.get()["mode"], "snow") + cache._expires = 0 + with patch("app.belki.weather.urlopen", side_effect=TimeoutError) as opened: + self.assertEqual(cache.get(), FALLBACK) + self.assertEqual(cache.get(), FALLBACK) + opened.assert_called_once() + + def test_concurrent_cold_reader_does_not_wait(self): + cache = WeatherCache() + cache._lock.acquire() + try: + with patch("app.belki.weather.urlopen") as opened: + self.assertEqual(cache.get(), FALLBACK) + opened.assert_not_called() + finally: + cache._lock.release() + + + def test_bounded_malformed_and_interrupted_responses_fall_back(self): + for body in (b"x" * 65_537, b"not json", b"null"): + response = MagicMock() + response.__enter__.return_value.read.return_value = body + with self.subTest(size=len(body)), patch("app.belki.weather.urlopen", return_value=response): + self.assertEqual(WeatherCache().get(), FALLBACK) + with patch("app.belki.weather.urlopen", side_effect=IncompleteRead(b"partial")): + self.assertEqual(WeatherCache().get(), FALLBACK) + + def test_success_and_failure_refresh_intervals(self): + cache = WeatherCache() + with patch("app.belki.weather.time.monotonic", return_value=100), patch("app.belki.weather.urlopen", return_value=self.opener(self.payload())): + cache.get() + self.assertEqual(cache._expires, 400) + with patch("app.belki.weather.time.monotonic", return_value=401), patch("app.belki.weather.urlopen", side_effect=TimeoutError): + self.assertEqual(cache.get(), FALLBACK) + self.assertEqual(cache._expires, 461) + + +class WeatherHttpTests(unittest.TestCase): + def test_public_weather_and_shared_assets(self): + server = BelkiHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + connection = http.client.HTTPConnection(*server.server_address, timeout=5) + try: + with patch("app.main.weather_cache.get", return_value=FALLBACK): + connection.request("GET", "/api/weather/ulli") + response = connection.getresponse() + self.assertEqual(response.status, 200) + self.assertEqual(json.loads(response.read()), FALLBACK) + for path, mime in [("effect.js", "javascript"), ("effect.css", "text/css")]: + connection.request("GET", f"/api/weather/{path}") + response = connection.getresponse() + self.assertEqual(response.status, 200) + self.assertIn(mime, response.getheader("Content-Type")) + self.assertTrue(response.read()) + finally: + connection.close() + server.shutdown() + server.server_close() + thread.join() diff --git a/web/admin.html b/web/admin.html index 27af6d3..47b928b 100644 --- a/web/admin.html +++ b/web/admin.html @@ -10,15 +10,7 @@ * { box-sizing: border-box; } body { margin: 0; background: #f5efe3; color: var(--ink); } body::before { content:""; position:fixed; inset:0; pointer-events:none; z-index:0; opacity:.42; background: radial-gradient(circle at 12% 8%, #fff8e7 0 0.7rem, transparent 13rem), radial-gradient(circle at 88% 24%, #ead8bd 0 0.45rem, transparent 15rem); } - .leaf-field { position:fixed; inset:0; overflow:hidden; pointer-events:none; z-index:1; } - .leaf { position:absolute; top:-3rem; width:1.1rem; height:1.65rem; border-radius:100% 0 100% 0; background:var(--accent); box-shadow:inset .18rem -.12rem 0 #8e431d; opacity:.62; transform:rotate(35deg); animation:leaf-fall 15s linear infinite; } - .leaf:nth-child(2n) { background:var(--gold); width:.82rem; height:1.3rem; animation-duration:19s; } - .leaf:nth-child(3n) { background:#a84e22; width:1.35rem; height:1.85rem; animation-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; } - @keyframes leaf-fall { 0% { transform:translate3d(0,-4rem,0) rotate(20deg); } 45% { transform:translate3d(3.5rem,48vh,0) rotate(170deg); } 100% { transform:translate3d(-4rem,112vh,0) rotate(330deg); } } main, dialog { position:relative; z-index:2; } - @media (prefers-reduced-motion: reduce) { .leaf { animation: none; top: 8vh; opacity: .16; } } main { width: min(1440px, calc(100% - 48px)); margin: 0 auto; padding: 42px 0 64px; } h1 { margin: 0; font: 500 clamp(2rem, 4vw, 3.25rem)/1 Georgia, "Times New Roman", serif; letter-spacing: -.035em; } h2 { margin: 0 0 8px; font: 500 2rem/1.1 Georgia, "Times New Roman", serif; } @@ -109,6 +101,8 @@ .gallery-footer button { min-height: 34px; padding: 5px 10px; } @media (max-width: 720px) { main { width: calc(100% - 28px); padding-top: 28px; } .topbar { display: block; } .record-count { display: block; margin-top: 18px; } .controls { display: grid; grid-template-columns: 1fr 1fr; } .control-group:first-child, .controls > button, .controls > .export-link { grid-column: 1 / -1; } input { min-width: 0; width: 100%; } .auth-form { display: grid; } .application-layout { grid-template-columns:1fr; }.application-list { border-right:0; border-bottom:1px solid var(--line); }.application-detail dl { grid-template-columns:1fr; gap:4px; }.application-detail dd { margin-bottom:14px; } .weekday-field { grid-column: 1 / -1; min-width: 0; } .weekday-options { gap: 4px; } } + + diff --git a/web/calculator.html b/web/calculator.html index 1eebfea..ee28964 100644 --- a/web/calculator.html +++ b/web/calculator.html @@ -9,18 +9,6 @@ :root { color-scheme: light; font-family: "Trebuchet MS", ui-sans-serif, sans-serif; --ink:#2d2924; --muted:#675c50; --paper:#fffdf7; --ground:#f5efe3; --line:#ded3c2; --accent:#b56824; --gold:#d89a28; --leaf:#c96f25; --focus:#a9541d; --error:#8e3630; } * { box-sizing: border-box; } html, body { max-width: 100%; } body { margin: 0; background: var(--ground); color: var(--ink); } body::before { content:""; position:fixed; inset:0; pointer-events:none; z-index:-1; opacity:.42; background: radial-gradient(circle at 12% 8%, #fff8e7 0 0.7rem, transparent 13rem), radial-gradient(circle at 88% 24%, #ead8bd 0 0.45rem, transparent 15rem); } - .leaf-field { position:fixed; inset:0; overflow:hidden; pointer-events:none; z-index:0; } - .leaf { position:absolute; top:-3rem; width:1.1rem; height:1.65rem; border-radius:100% 0 100% 0; background:var(--leaf); box-shadow:inset .18rem -.12rem 0 #8e431d; opacity:.74; transform:rotate(35deg); animation:leaf-fall 15s linear infinite; } - .leaf:nth-child(2n) { background:#e0a02f; width:.82rem; height:1.3rem; animation-duration:19s; } - .leaf:nth-child(3n) { background:#a84e22; width:1.35rem; height:1.85rem; animation-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; } - @keyframes leaf-fall { 0% { transform:translate3d(0,-4rem,0) rotate(20deg); } 45% { transform:translate3d(3.5rem,48vh,0) rotate(170deg); } 100% { transform:translate3d(-4rem,112vh,0) rotate(330deg); } } main { position:relative; z-index:1; width: min(1060px, calc(100% - 32px)); margin: 48px auto 72px; } h1 { margin: 0 0 6px; font: 500 clamp(2.25rem, 5vw, 4rem)/1 Georgia, "Times New Roman", serif; letter-spacing: -.045em; } h2 { font: 500 1.55rem/1.15 Georgia, "Times New Roman", serif; } .muted { color: var(--muted); line-height: 1.55; } @@ -96,8 +84,9 @@ input, select, textarea { font-size: 16px; } .site-footer { margin-top: 32px; } } - @media (prefers-reduced-motion: reduce) { .leaf { animation: none; top: 8vh; opacity: .18; } } + + diff --git a/web/weather-effect.css b/web/weather-effect.css new file mode 100644 index 0000000..f47c3e1 --- /dev/null +++ b/web/weather-effect.css @@ -0,0 +1,68 @@ +/* Shared by calculator and admin. Keep all particles below interactive content. */ +.leaf-field { + --rain: #69849a; + --snow: #fffefa; + --snow-edge: #aab9c5; + position: fixed; + inset: 0; + overflow: hidden; + pointer-events: none; + z-index: 0; +} +.leaf { + 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; +} +.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"] { + 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"] { + 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); } +} +@keyframes snow-fall { + 0% { transform: translate3d(0, -4rem, 0); } + 50% { transform: translate3d(calc(2rem + var(--drift, 0vw) * .5), 50vh, 0); } + 100% { transform: translate3d(var(--drift, 0vw), 112vh, 0); } +} +@keyframes rain-fall { + 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))); } +} +@media (prefers-reduced-motion: reduce) { + .leaf-field .leaf { animation: none; top: 8vh; opacity: .16; } + .leaf:nth-child(n+8) { display: none; } +} diff --git a/web/weather-effect.js b/web/weather-effect.js new file mode 100644 index 0000000..666b6c4 --- /dev/null +++ b/web/weather-effect.js @@ -0,0 +1,73 @@ +/* A little Pulkovo weather in the existing autumn background. */ +(() => { + 'use strict'; + const field = document.querySelector('.leaf-field'); + if (!field) return; + const refreshMs = 5 * 60 * 1000; + let timer; + let controller; + let nextRefresh = 0; + let lastSignature = ''; + + function render(weather) { + const mode = ['leaves', 'rain', 'snow', 'mixed'].includes(weather.mode) ? weather.mode : 'leaves'; + 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); + 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`); + const particles = document.createDocumentFragment(); + 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.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}%`; + particle.style.setProperty('--duration', `${seconds.toFixed(2)}s`); + particle.style.animationDelay = `${(-Math.random() * seconds).toFixed(2)}s`; + particle.style.setProperty('--size', (0.65 + Math.random() * 0.65).toFixed(2)); + particles.append(particle); + } + 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); + } + } + + document.addEventListener('visibilitychange', () => { + field.classList.toggle('weather-paused', document.hidden); + if (document.hidden) { + clearTimeout(timer); + controller?.abort(); + } else { + refresh(); + } + }); + refresh(); +})();