From 2fa17e344630119942d37eb2a33427ce4e6965ed Mon Sep 17 00:00:00 2001 From: lowicz Date: Wed, 2 Dec 2026 15:05:04 +0100 Subject: [PATCH 1/8] feat(accent): opt-in seasonal decorations - a winter pack and logo doodles ONCALL_ACCENT lists the decoration packs a deployment allows; empty, the default, draws nothing. The API answers in /api/v1/config with what to draw on today's Warsaw date, so the setting is written once and left and the interface keeps no calendar of its own. - winter, 6 December to 6 January unless ONCALL_ACCENT_FROM and ONCALL_ACCENT_UNTIL (MM-DD, both or neither) name another season: a hat on the logo mark, snow inside the "Teraz" strip and a garland of lights under it, a winter night on the sign-in screen, and a sleigh ahead of the generator's progress bar. - doodles: one small drawing on the logo mark on seven days of the year (New Year's Eve and Day, Fat Thursday, 14 February, Easter Sunday and Monday, 1 April). Every drawing lives in one lazily loaded chunk that only a deployment with the setting downloads. It is styled on a screen only, so printouts, exports and e-mails stay plain; nothing moves under prefers-reduced-motion; a share-link session is never decorated; and each person can turn the decorations off for their own browser in the account menu. The garland and the strip snow belong to the desktop strip: a phone shows the hat or the doodle only. --- .env.example | 11 + DESIGN.md | 32 ++- backend/contracts/openapi.json | 16 ++ backend/src/oncall/accent.py | 77 +++++++ backend/src/oncall/config.py | 58 +++++- backend/src/oncall/presentation/system.py | 6 + backend/src/oncall/routes/system.py | 3 + backend/tests/contract/test_http_contract.py | 1 + backend/tests/test_accent.py | 153 ++++++++++++++ backend/tests/test_config.py | 56 +++++ docker-compose.yml | 3 + docs/en/uzytkownik/pierwsze-kroki.md | 5 + docs/en/wdrozenie/uruchomienie.md | 35 ++++ docs/uzytkownik/pierwsze-kroki.md | 5 + docs/wdrozenie/uruchomienie.md | 35 ++++ frontend/src/accent.test.tsx | 65 ++++++ frontend/src/accent.ts | 60 ++++++ frontend/src/api.ts | 7 + frontend/src/components/AppShell.test.tsx | 79 ++++++- frontend/src/components/AppShell.tsx | 27 ++- frontend/src/components/AuthFrame.test.tsx | 2 +- frontend/src/components/AuthFrame.tsx | 7 +- frontend/src/components/NowStrip.tsx | 4 + .../src/components/NumberHandover.test.tsx | 2 +- frontend/src/decor/art.tsx | 195 ++++++++++++++++++ frontend/src/decor/decor.css | 123 +++++++++++ frontend/src/decor/decor.test.tsx | 150 ++++++++++++++ frontend/src/decor/index.tsx | 29 +++ frontend/src/hooks/useAccentHost.test.tsx | 71 +++++++ frontend/src/hooks/useAccentHost.ts | 25 +++ frontend/src/hooks/useBranding.test.tsx | 4 +- frontend/src/hooks/useUndoable.test.tsx | 2 +- frontend/src/i18n/en/theme.ts | 5 + frontend/src/i18n/pl/theme.ts | 8 +- frontend/src/screens/Generator.test.tsx | 35 +++- frontend/src/screens/Generator.tsx | 4 + frontend/src/screens/Login.test.tsx | 38 +++- frontend/src/screens/Login.tsx | 14 +- frontend/src/screens/Mine.test.tsx | 2 +- frontend/src/screens/More.test.tsx | 31 ++- frontend/src/screens/More.tsx | 5 +- frontend/src/screens/SetPassword.test.tsx | 2 +- frontend/src/screens/Swaps.test.tsx | 2 +- frontend/src/screens/admin/Audit.test.tsx | 2 +- frontend/src/screens/admin/People.test.tsx | 4 +- frontend/src/session.test.tsx | 2 +- frontend/src/test/english.test.tsx | 2 +- frontend/src/test/polish-baseline.test.tsx | 2 +- frontend/src/theme.ts | 4 +- frontend/src/tokens.css | 16 ++ frontend/src/ui/Icon.tsx | 7 +- 51 files changed, 1493 insertions(+), 40 deletions(-) create mode 100644 backend/src/oncall/accent.py create mode 100644 backend/tests/test_accent.py create mode 100644 frontend/src/accent.test.tsx create mode 100644 frontend/src/accent.ts create mode 100644 frontend/src/decor/art.tsx create mode 100644 frontend/src/decor/decor.css create mode 100644 frontend/src/decor/decor.test.tsx create mode 100644 frontend/src/decor/index.tsx create mode 100644 frontend/src/hooks/useAccentHost.test.tsx create mode 100644 frontend/src/hooks/useAccentHost.ts diff --git a/.env.example b/.env.example index 82dedcb4..3e8c67ad 100644 --- a/.env.example +++ b/.env.example @@ -15,6 +15,17 @@ ONCALL_VERSION= ONCALL_APP_NAME=On-call ONCALL_APP_SUBTITLE= +# Optional decoration of the interface, off while this is empty. List the +# packs once and leave the line alone: each knows its own days. `winter` (a +# hat on the logo, lights and snow on the "Teraz" strip, a winter night on the +# sign-in screen, a sleigh on the generator's progress bar) shows from +# 6 December to 6 January; `doodles` puts a small drawing on the logo on seven +# days of the year. Both: ONCALL_ACCENT=winter,doodles +ONCALL_ACCENT= +# Another winter season, as MM-DD, both or neither; it may run across New Year. +# ONCALL_ACCENT_FROM=12-01 +# ONCALL_ACCENT_UNTIL=01-06 + # Local development default, publicly known. Every non-local host sets a unique # POSTGRES_PASSWORD (below) before the first start and the same password here; # user and database match POSTGRES_USER and POSTGRES_DB. Changing it on an diff --git a/DESIGN.md b/DESIGN.md index 67305d04..a97637ef 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -556,6 +556,35 @@ in the light theme), today a 12 % blue wash and the day-number pill in action blue, a gap in staffing a pink wash. In the sticky header every wash lies on an opaque `s2`. The start of a week is a 2 px left line. +## Seasonal accent +An opt-in exception to the calm of everything above, off unless the +deployment sets `ONCALL_ACCENT` (`docs/wdrozenie/uruchomienie.md`, "Ozdoby +sezonowe"). The API names what today carries, the shell and the sign-in +screen write it to `data-accent` on `` (`src/accent.ts`), and every +drawing lives in one lazily loaded chunk with its own stylesheet +(`src/decor/`). + +`winter` puts a hat on the logo mark, snow inside the "Teraz" strip and a +garland of lights under it, a night sky with a tree of role marks on the +sign-in screen, and a sleigh ahead of the generator's progress bar. +`doodles` puts one small drawing on the logo mark on seven days of the year. + +### Named Rules +**The Frame, Not the Instrument Rule.** The accent decorates the frame: the +rail, the strip, the sign-in screen, a progress bar. It never draws on the +duty matrix, never covers text or a control, and never borrows a role or +state colour as a state. +**The Decoration Only Rule.** Every drawing carries the class `fx`, is +`aria-hidden`, takes no pointer events and has its own `--fx-*` colours in +`tokens.css`. `decor.css` styles it on a screen only, so a printout, the +e-mails and the exports are the plain interface. +**The Stillness Rule.** Nothing of it moves under `prefers-reduced-motion`, +and what moves without end (the snow and the lights of the strip) can be +turned off by each person in the account menu. The sign-in screen, which +has no such switch yet, stops moving by itself. +**The Insiders Rule.** A share-link session, opened by people outside the +team, is never decorated. + ## Do's and Don'ts ### Do: @@ -583,7 +612,8 @@ lies on an opaque `s2`. The start of a week is a 2 px left line. - **Don't** use the action blue as a text colour or a section background; the text blue is `--sig`. - **Don't** introduce a second accent, gradients (apart from the radial - sign-in background) or coloured icons; icons are monochrome, 24 px. + sign-in background) or coloured icons; icons are monochrome, 24 px. The + one exception is the opt-in seasonal accent, under its own rules above. - **Don't** add a component library or custom date pickers; fields are native (`AGENTS.md`). - **Don't** format numbers or name days inside a component; everything diff --git a/backend/contracts/openapi.json b/backend/contracts/openapi.json index 73c831ec..6635e85b 100644 --- a/backend/contracts/openapi.json +++ b/backend/contracts/openapi.json @@ -3408,6 +3408,21 @@ "PublicConfigResponse": { "description": "Instance settings the UI needs before anyone is logged in.", "properties": { + "accent": { + "items": { + "enum": [ + "winter", + "sparkle", + "doughnut", + "heart", + "egg", + "flip" + ], + "type": "string" + }, + "title": "Accent", + "type": "array" + }, "app_name": { "title": "App Name", "type": "string" @@ -3446,6 +3461,7 @@ "sso_enabled", "app_name", "app_subtitle", + "accent", "version", "audit_retention_days", "login_audit_retention_days", diff --git a/backend/src/oncall/accent.py b/backend/src/oncall/accent.py new file mode 100644 index 00000000..9bf99dfd --- /dev/null +++ b/backend/src/oncall/accent.py @@ -0,0 +1,77 @@ +"""The opt-in seasonal accent: which decorations the interface draws today. + +A deployment lists packs in ``ONCALL_ACCENT``; none is the default. Each pack +carries its own calendar, so the setting is written once and left, and the +answer changes with the Warsaw business date: ``winter`` holds through its +season, ``doodles`` names the one drawing its day puts on the logo mark. +The interface draws what ``/api/v1/config`` lists and keeps no calendar of +its own. +""" + +from collections.abc import Collection +from datetime import date, timedelta +from typing import Literal + +#: What a deployment may list in ONCALL_ACCENT. +AccentPack = Literal["winter", "doodles"] +#: What the interface may be told to draw: `winter`, or the day's doodle. +Accent = Literal["winter", "sparkle", "doughnut", "heart", "egg", "flip"] + +#: The winter season of a deployment that names no bounds of its own, as +#: inclusive MM-DD: St Nicholas' Day to Epiphany. +WINTER_SEASON = ("12-06", "01-06") + +#: Fat Thursday, the last Thursday before Lent. +_FAT_THURSDAY_BEFORE_EASTER = timedelta(days=52) + + +def easter_sunday(year: int) -> date: + """Western Easter, by the anonymous Gregorian computus.""" + golden = year % 19 + century, year_of_century = divmod(year, 100) + leap_centuries, century_rest = divmod(century, 4) + correction = (8 * century + 13) // 25 + epact = (19 * golden + century - leap_centuries - correction + 15) % 30 + leap_years, year_rest = divmod(year_of_century, 4) + weekday = (32 + 2 * century_rest + 2 * leap_years - epact - year_rest) % 7 + late = (golden + 11 * epact + 19 * weekday) // 433 + month = (epact + weekday - 7 * late + 90) // 25 + day = (epact + weekday - 7 * late + 33 * month + 19) % 32 + return date(year, month, day) + + +def in_season(day: date, starts: str, ends: str) -> bool: + """Whether the day lies within inclusive MM-DD bounds. A season that + starts later in the year than it ends runs across New Year.""" + today = day.strftime("%m-%d") + if starts <= ends: + return starts <= today <= ends + return today >= starts or today <= ends + + +def doodle_of(day: date) -> Accent | None: + """The drawing this day puts on the logo mark, on the seven days that + have one. A movable feast wins the day it shares with a fixed one.""" + easter = easter_sunday(day.year) + month_day = (day.month, day.day) + if month_day in ((12, 31), (1, 1)): + return "sparkle" + if day == easter - _FAT_THURSDAY_BEFORE_EASTER: + return "doughnut" + if month_day == (2, 14): + return "heart" + if easter <= day <= easter + timedelta(days=1): + return "egg" + if month_day == (4, 1): + return "flip" + return None + + +def accents_on(day: date, packs: Collection[str], season: tuple[str, str]) -> list[Accent]: + """What the listed packs draw on this day; `season` bounds `winter` only.""" + active: list[Accent] = [] + if "winter" in packs and in_season(day, *season): + active.append("winter") + if "doodles" in packs and (doodle := doodle_of(day)): + active.append(doodle) + return active diff --git a/backend/src/oncall/config.py b/backend/src/oncall/config.py index 4ba4e258..c403af7c 100644 --- a/backend/src/oncall/config.py +++ b/backend/src/oncall/config.py @@ -1,12 +1,15 @@ import os +from datetime import datetime from functools import lru_cache from math import ceil from pathlib import Path -from typing import Self +from typing import Annotated, Self from cryptography.fernet import Fernet from pydantic import Field, SecretStr, field_validator, model_validator -from pydantic_settings import BaseSettings, SettingsConfigDict +from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict + +from oncall.accent import WINTER_SEASON, AccentPack CGROUP_ROOT = Path("/sys/fs/cgroup") @@ -73,6 +76,16 @@ class Settings(BaseSettings): #: public repository carries no organisation name. app_name: str = "On-call" app_subtitle: str = "" + #: Opt-in decoration of the interface (`oncall.accent`): the packs this + #: deployment allows, comma-separated. Empty, the default, draws nothing. + #: It is written once and left, because each pack knows its own days: + #: `winter` holds through its season, 6 December to 6 January unless both + #: bounds below name another (MM-DD, inclusive, across New Year when the + #: first is the later date); `doodles` puts a small drawing on the logo + #: mark on seven days of the year and ignores the bounds. + accent: Annotated[tuple[AccentPack, ...], NoDecode] = () + accent_from: str = "" + accent_until: str = "" #: The release this process runs, shown in the interface. The image bakes #: in the git tag it was built from (backend/Dockerfile, ARG ONCALL_VERSION #: from release.yml), so this names what really runs even when the host's @@ -256,6 +269,30 @@ def _blank_version_means_dev(cls, value: str) -> str: """An empty ONCALL_VERSION (a copied .env with the line unset) is a dev build.""" return value.strip() or DEV_VERSION + @field_validator("accent", mode="before") + @classmethod + def _accent_is_a_comma_separated_list(cls, value: object) -> object: + """`winter,doodles` as the environment writes it; blank is none.""" + if isinstance(value, str): + return tuple(name.strip().lower() for name in value.split(",") if name.strip()) + return value + + @field_validator("accent_from", "accent_until") + @classmethod + def _accent_bound_is_a_day_of_the_year(cls, value: str) -> str: + """Blank is unset; anything else is a day of the year, 29 February + included, kept zero-padded so two bounds compare as text.""" + bound = value.strip() + if not bound: + return "" + try: + return datetime.strptime(f"2000-{bound}", "%Y-%m-%d").strftime("%m-%d") + except ValueError: + raise ValueError( + "ONCALL_ACCENT_FROM and ONCALL_ACCENT_UNTIL are days of the year written " + "MM-DD, such as 12-06." + ) from None + @field_validator("solver_workers", mode="before") @classmethod def _blank_solver_workers_is_unset(cls, value: object) -> object: @@ -316,6 +353,17 @@ def _secrets_key_is_fernet_keys(cls, value: SecretStr | None) -> SecretStr | Non ) from None return SecretStr(",".join(keys)) + @model_validator(mode="after") + def _accent_bounds_come_in_pairs(self) -> Self: + """Half a season has no meaning, and guessing the other half would + decorate on days nobody chose.""" + if bool(self.accent_from) != bool(self.accent_until): + raise ValueError( + "Set both ONCALL_ACCENT_FROM and ONCALL_ACCENT_UNTIL to move the winter " + "season, or leave both empty for 6 December to 6 January." + ) + return self + @model_validator(mode="after") def _smtp_credentials_come_in_pairs(self) -> Self: """A username alone would log in with an empty password, and a @@ -367,6 +415,12 @@ def _https_requires_secure_cookie(self) -> Self: ) return self + @property + def accent_season(self) -> tuple[str, str]: + """The inclusive MM-DD bounds of `winter`: this deployment's own, or + the pack's.""" + return (self.accent_from, self.accent_until) if self.accent_from else WINTER_SEASON + @lru_cache def get_settings() -> Settings: diff --git a/backend/src/oncall/presentation/system.py b/backend/src/oncall/presentation/system.py index 96fb0aa3..ad98e039 100644 --- a/backend/src/oncall/presentation/system.py +++ b/backend/src/oncall/presentation/system.py @@ -2,6 +2,8 @@ from pydantic import BaseModel +from oncall.accent import Accent + class HealthResponse(BaseModel): status: str = "ok" @@ -16,6 +18,10 @@ class PublicConfigResponse(BaseModel): #: Brand shown before login: the product name and its optional subtitle. app_name: str app_subtitle: str + #: The decorations to draw today (`oncall.accent`): `winter` through its + #: season, and the day's doodle for the logo mark. Empty on every day of + #: a deployment that lists no pack. + accent: list[Accent] #: The release running, as its image was built: `1.2.0`, `1.3.0-rc.1`, #: or `dev` for a build from a checkout. version: str diff --git a/backend/src/oncall/routes/system.py b/backend/src/oncall/routes/system.py index 2fead7de..3251fa4a 100644 --- a/backend/src/oncall/routes/system.py +++ b/backend/src/oncall/routes/system.py @@ -1,6 +1,8 @@ from fastapi import APIRouter +from oncall.accent import accents_on from oncall.config import get_settings +from oncall.domain.clock import business_today from oncall.notifications.service import UNDO_WINDOW from oncall.presentation.system import HealthResponse, PublicConfigResponse @@ -20,6 +22,7 @@ async def public_config() -> PublicConfigResponse: sso_enabled=settings.sso_enabled, app_name=settings.app_name, app_subtitle=settings.app_subtitle, + accent=accents_on(business_today(), settings.accent, settings.accent_season), version=settings.version, audit_retention_days=settings.retention_audit_days, login_audit_retention_days=settings.retention_login_audit_days, diff --git a/backend/tests/contract/test_http_contract.py b/backend/tests/contract/test_http_contract.py index 90b75888..2a65b38d 100644 --- a/backend/tests/contract/test_http_contract.py +++ b/backend/tests/contract/test_http_contract.py @@ -33,6 +33,7 @@ async def test_public_response_and_validation_envelopes(client) -> None: "sso_enabled": False, "app_name": "On-call", "app_subtitle": "", + "accent": [], "version": "dev", "audit_retention_days": 365, "login_audit_retention_days": 90, diff --git a/backend/tests/test_accent.py b/backend/tests/test_accent.py new file mode 100644 index 00000000..61ff573b --- /dev/null +++ b/backend/tests/test_accent.py @@ -0,0 +1,153 @@ +"""The seasonal accent: which decorations a day carries, and how a +deployment's setting reaches the interface.""" + +from datetime import UTC, date, datetime + +import pytest + +from oncall.accent import WINTER_SEASON, accents_on, doodle_of, easter_sunday, in_season +from oncall.config import Settings +from oncall.routes import system +from tests.frozen_clock import FrozenClock + + +@pytest.mark.parametrize( + "easter", + [ + date(2008, 3, 23), + date(2024, 3, 31), + date(2026, 4, 5), + date(2027, 3, 28), + date(2029, 4, 1), + date(2038, 4, 25), + ], + ids=str, +) +def test_easter_sunday_is_the_known_date(easter: date) -> None: + assert easter_sunday(easter.year) == easter + + +@pytest.mark.parametrize( + ("day", "inside"), + [ + (date(2026, 12, 5), False), + (date(2026, 12, 6), True), + (date(2026, 12, 31), True), + (date(2027, 1, 1), True), + (date(2027, 1, 6), True), + (date(2027, 1, 7), False), + (date(2027, 6, 17), False), + ], + ids=str, +) +def test_the_winter_season_runs_across_new_year_with_both_ends_included( + day: date, inside: bool +) -> None: + assert in_season(day, *WINTER_SEASON) is inside + + +@pytest.mark.parametrize( + ("day", "inside"), + [ + (date(2027, 1, 31), False), + (date(2027, 2, 1), True), + (date(2028, 2, 29), True), + (date(2027, 3, 1), False), + ], + ids=str, +) +def test_a_season_inside_one_year_does_not_wrap(day: date, inside: bool) -> None: + assert in_season(day, "02-01", "02-29") is inside + + +@pytest.mark.parametrize( + ("day", "doodle"), + [ + (date(2026, 12, 31), "sparkle"), + (date(2027, 1, 1), "sparkle"), + (date(2027, 2, 4), "doughnut"), + (date(2027, 2, 14), "heart"), + (date(2027, 3, 28), "egg"), + (date(2027, 3, 29), "egg"), + (date(2027, 4, 1), "flip"), + (date(2027, 3, 30), None), + (date(2027, 6, 17), None), + ], + ids=str, +) +def test_seven_days_of_a_year_carry_a_doodle(day: date, doodle: str | None) -> None: + assert doodle_of(day) == doodle + + +def test_a_movable_feast_wins_the_day_it_shares_with_a_fixed_one() -> None: + # Easter Sunday on 1 April, and Fat Thursday on 14 February. + assert doodle_of(date(2029, 4, 1)) == "egg" + assert easter_sunday(2075) == date(2075, 4, 7) + assert doodle_of(date(2075, 2, 14)) == "doughnut" + + +def test_no_pack_draws_nothing_on_any_day() -> None: + assert accents_on(date(2026, 12, 24), (), WINTER_SEASON) == [] + assert accents_on(date(2027, 1, 1), (), WINTER_SEASON) == [] + + +def test_each_pack_answers_for_its_own_days() -> None: + both = ("winter", "doodles") + assert accents_on(date(2026, 12, 24), both, WINTER_SEASON) == ["winter"] + assert accents_on(date(2027, 1, 1), both, WINTER_SEASON) == ["winter", "sparkle"] + assert accents_on(date(2027, 2, 4), both, WINTER_SEASON) == ["doughnut"] + assert accents_on(date(2027, 6, 17), both, WINTER_SEASON) == [] + assert accents_on(date(2027, 1, 1), ("winter",), WINTER_SEASON) == ["winter"] + assert accents_on(date(2027, 1, 1), ("doodles",), WINTER_SEASON) == ["sparkle"] + + +def test_a_season_of_the_deployments_own_moves_winter_and_leaves_the_doodles() -> None: + both = ("winter", "doodles") + assert accents_on(date(2026, 12, 1), both, ("12-01", "12-26")) == ["winter"] + assert accents_on(date(2027, 1, 1), both, ("12-01", "12-26")) == ["sparkle"] + + +async def _accent_served(client, monkeypatch, settings: Settings, instant: datetime) -> list[str]: + monkeypatch.setattr(system, "get_settings", lambda: settings) + monkeypatch.setattr("oncall.domain.clock.system_clock", FrozenClock(instant)) + response = await client.get("/api/v1/config") + assert response.status_code == 200 + return response.json()["accent"] + + +async def test_the_interface_is_told_nothing_unless_the_deployment_opts_in( + client, monkeypatch +) -> None: + christmas_eve = datetime(2026, 12, 24, 12, 0, tzinfo=UTC) + + assert await _accent_served(client, monkeypatch, Settings(), christmas_eve) == [] + assert await _accent_served( + client, monkeypatch, Settings(accent="winter,doodles"), christmas_eve + ) == ["winter"] + + +async def test_the_season_starts_with_the_warsaw_day_not_the_utc_one(client, monkeypatch) -> None: + settings = Settings(accent="winter") + + # 23:30 UTC on the fifth is already half past midnight on the sixth in Warsaw. + still_fifth = datetime(2026, 12, 5, 22, 30, tzinfo=UTC) + already_sixth = datetime(2026, 12, 5, 23, 30, tzinfo=UTC) + + assert await _accent_served(client, monkeypatch, settings, still_fifth) == [] + assert await _accent_served(client, monkeypatch, settings, already_sixth) == ["winter"] + + +async def test_the_deployments_own_season_decides_when_winter_is_served( + client, monkeypatch +) -> None: + settings = Settings(accent="winter", accent_from="12-01", accent_until="12-26") + + assert await _accent_served( + client, monkeypatch, settings, datetime(2026, 12, 2, 12, 0, tzinfo=UTC) + ) == ["winter"] + assert ( + await _accent_served( + client, monkeypatch, settings, datetime(2026, 12, 27, 12, 0, tzinfo=UTC) + ) + == [] + ) diff --git a/backend/tests/test_config.py b/backend/tests/test_config.py index bdf437d5..670a46ac 100644 --- a/backend/tests/test_config.py +++ b/backend/tests/test_config.py @@ -311,6 +311,62 @@ def test_a_refused_setting_does_not_echo_the_configuration(monkeypatch) -> None: assert "hunter2-do-not-log" not in str(refused.value) +def test_the_accent_is_off_by_default() -> None: + settings = Settings() + + assert settings.accent == () + assert settings.accent_season == ("12-06", "01-06") + + +@pytest.mark.parametrize("blank", ["", " ", " , "], ids=["empty", "spaces", "commas"]) +def test_a_blank_accent_is_none(monkeypatch, blank: str) -> None: + monkeypatch.setenv("ONCALL_ACCENT", blank) + monkeypatch.setenv("ONCALL_ACCENT_FROM", " ") + monkeypatch.setenv("ONCALL_ACCENT_UNTIL", "") + + settings = Settings() + + assert settings.accent == () + assert settings.accent_season == ("12-06", "01-06") + + +def test_the_accent_lists_packs_separated_by_commas(monkeypatch) -> None: + monkeypatch.setenv("ONCALL_ACCENT", " Winter, doodles ") + + assert Settings().accent == ("winter", "doodles") + assert Settings(accent=("doodles",)).accent == ("doodles",) + + +def test_an_unknown_accent_pack_is_refused_without_echoing_it(monkeypatch) -> None: + monkeypatch.setenv("ONCALL_ACCENT", "winter,halloween-do-not-log") + + with pytest.raises(ValidationError) as refused: + Settings() + + assert "'winter' or 'doodles'" in str(refused.value) + assert "halloween-do-not-log" not in str(refused.value) + + +def test_the_winter_season_of_a_deployment_is_kept_zero_padded() -> None: + settings = Settings(accent="winter", accent_from=" 12-1 ", accent_until="2-29") + + assert settings.accent_season == ("12-01", "02-29") + + +@pytest.mark.parametrize("bound", ["13-01", "02-30", "6 Dec", "12-06-2026", "1206"]) +def test_an_accent_bound_must_be_a_day_of_the_year(bound: str) -> None: + with pytest.raises(ValidationError, match="written MM-DD"): + Settings(accent_from=bound, accent_until="01-06") + + +@pytest.mark.parametrize( + ("starts", "ends"), [("12-01", ""), ("", "01-06")], ids=["no end", "no start"] +) +def test_half_an_accent_season_is_refused(starts: str, ends: str) -> None: + with pytest.raises(ValidationError, match="Set both ONCALL_ACCENT_FROM"): + Settings(accent_from=starts, accent_until=ends) + + @pytest.mark.parametrize("blank", ["", " "], ids=["empty", "spaces"]) def test_blank_solver_workers_leaves_the_count_to_the_cpu_allocation(monkeypatch, blank) -> None: """Compose passes an unset ONCALL_SOLVER_WORKERS as an empty string.""" diff --git a/docker-compose.yml b/docker-compose.yml index 1eafae55..a6f92816 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -97,6 +97,9 @@ services: environment: ONCALL_APP_NAME: ${ONCALL_APP_NAME:-On-call} ONCALL_APP_SUBTITLE: ${ONCALL_APP_SUBTITLE:-} + ONCALL_ACCENT: ${ONCALL_ACCENT:-} + ONCALL_ACCENT_FROM: ${ONCALL_ACCENT_FROM:-} + ONCALL_ACCENT_UNTIL: ${ONCALL_ACCENT_UNTIL:-} ONCALL_DATABASE_URL: ${ONCALL_DATABASE_URL:-postgresql+asyncpg://oncall:oncall@db:5432/oncall} ONCALL_DATABASE_POOL_SIZE: ${ONCALL_DATABASE_POOL_SIZE:-3} ONCALL_DATABASE_MAX_OVERFLOW: ${ONCALL_DATABASE_MAX_OVERFLOW:-2} diff --git a/docs/en/uzytkownik/pierwsze-kroki.md b/docs/en/uzytkownik/pierwsze-kroki.md index f6eae6f9..8254afb3 100644 --- a/docs/en/uzytkownik/pierwsze-kroki.md +++ b/docs/en/uzytkownik/pierwsze-kroki.md @@ -90,6 +90,11 @@ choice is remembered in the browser, also covers messages from the server in the chosen language; a new user always starts in Polish, regardless of the browser settings. +If the administrator has turned seasonal decorations on (winter ones, for +example), then on the days they show, the same place offers **Decorations**: +**On** (the default) or **Off**. The choice applies to your browser only and +is remembered there. + ## Date format Dates in the application are displayed as **`DD-MM-YYYY`**, regardless of the diff --git a/docs/en/wdrozenie/uruchomienie.md b/docs/en/wdrozenie/uruchomienie.md index fe78ebcc..4bdb6ad1 100644 --- a/docs/en/wdrozenie/uruchomienie.md +++ b/docs/en/wdrozenie/uruchomienie.md @@ -81,6 +81,8 @@ The full list with comments is in `.env.example`. | `ONCALL_WEB_HTTPS_PORT` | `8443` | the HTTPS port exposed on the host | | `ONCALL_APP_NAME` | `On-call` | the product name in the interface, e-mails and calendar names | | `ONCALL_APP_SUBTITLE` | empty | the second line under the name in the navigation, on the sign-in screen and in the e-mail header; empty hides the line | +| `ONCALL_ACCENT` | empty | optional decorations of the interface, see [Seasonal decorations](#seasonal-decorations); empty turns them off entirely | +| `ONCALL_ACCENT_FROM`, `ONCALL_ACCENT_UNTIL` | empty | a winter season other than 6 December - 6 January, as `MM-DD`; both or neither | | `ONCALL_PUBLIC_BASE_URL` | `http://localhost:8080` | the address in e-mails, ICS feeds and links | | `ONCALL_HANDOVER_REMINDER_HOUR` | `9` | the hour (Warsaw time) of the announcements and reminders about a starting duty, see [Integrations](../produkt/integracje.md#e-mail-notifications) | | `ONCALL_COORDINATOR_DIGEST_HOUR` | `8` | the hour (Warsaw time, 0-23) of the message sent on working days telling coordinators and administrators who is on duty today and on the days off that follow; independent of `ONCALL_HANDOVER_REMINDER_HOUR` | @@ -107,6 +109,39 @@ In Compose the worker process has an allocation of 2 CPUs, and the default number of solver threads follows from it. Changing the allocation changes that number automatically. +## Seasonal decorations + +The interface can wear seasonal decorations. They are off by default: while +`ONCALL_ACCENT` is empty, nothing changes. + +`ONCALL_ACCENT` is a list of packs separated by commas. You write it once and +leave it: each pack knows its own days, so nobody switches the setting when a +season starts or ends. + +| Pack | When | What it shows | +| --- | --- | --- | +| `winter` | from 6 December to 6 January | a hat on the product mark, a garland of lights under the “Teraz” strip and snow inside that strip, a winter night on the sign-in screen, a sleigh on the generator's progress bar | +| `doodles` | seven days a year | a small drawing on the product mark: on 31 December and 1 January, on Fat Thursday, on 14 February, on Easter Sunday and Monday, and on 1 April | + +```env +ONCALL_ACCENT=winter,doodles +``` + +`ONCALL_ACCENT_FROM` and `ONCALL_ACCENT_UNTIL` set another winter season: a +day of the year as `MM-DD`, both ends included. You give both or neither, and +the season may run across New Year. The `doodles` pack does not read them. An +unknown pack name, a malformed date or only one of the two dates stops `api` +at startup with a message in the log. + +Whether today is one of a pack's days is decided by the date in the +Europe/Warsaw zone. An open browser tab learns it when the page loads. + +The decorations are on the screen only: they do not reach a printout, +e-mails, ICS calendars or CSV reports, and they cover nothing. With the +system's reduced-motion setting they stand still, and each person can turn +them off for themselves in the account menu (**Decorations**). A preview from +a share link never shows them. + ## CA file A deployment names its certificate authorities in **one** PEM file, diff --git a/docs/uzytkownik/pierwsze-kroki.md b/docs/uzytkownik/pierwsze-kroki.md index 60287375..3e3ccabb 100644 --- a/docs/uzytkownik/pierwsze-kroki.md +++ b/docs/uzytkownik/pierwsze-kroki.md @@ -85,6 +85,11 @@ zostaje zapamiętany w przeglądarce, obejmuje także komunikaty z serwera języku; nowy użytkownik zawsze zaczyna po polsku, niezależnie od ustawień przeglądarki. +Jeśli administrator włączył sezonowe ozdoby (na przykład zimowe), w dniach, +w których są widoczne, w tym samym miejscu pojawia się wybór **Ozdoby**: +**Włączone** (domyślnie) albo **Wyłączone**. Wybór dotyczy tylko Twojej +przeglądarki i zostaje w niej zapamiętany. + ## Format dat Daty w aplikacji są wyświetlane jako **`DD-MM-RRRR`**, niezależnie od ustawień diff --git a/docs/wdrozenie/uruchomienie.md b/docs/wdrozenie/uruchomienie.md index e8b764d6..46d6de3b 100644 --- a/docs/wdrozenie/uruchomienie.md +++ b/docs/wdrozenie/uruchomienie.md @@ -79,6 +79,8 @@ Pełna lista z komentarzami jest w `.env.example`. | `ONCALL_WEB_HTTPS_PORT` | `8443` | port HTTPS wystawiony na hosta | | `ONCALL_APP_NAME` | `On-call` | nazwa produktu w interfejsie, e-mailach i nazwach kalendarzy | | `ONCALL_APP_SUBTITLE` | puste | drugi wiersz pod nazwą w nawigacji, na ekranie logowania i w nagłówku e-maili; pusty ukrywa wiersz | +| `ONCALL_ACCENT` | puste | opcjonalne ozdoby interfejsu, patrz [Ozdoby sezonowe](#ozdoby-sezonowe); puste wyłącza je całkowicie | +| `ONCALL_ACCENT_FROM`, `ONCALL_ACCENT_UNTIL` | puste | inny sezon zimowy niż 6 grudnia - 6 stycznia, jako `MM-DD`; obie albo żadna | | `ONCALL_PUBLIC_BASE_URL` | `http://localhost:8080` | adres w e-mailach, kanałach ICS i linkach | | `ONCALL_HANDOVER_REMINDER_HOUR` | `9` | godzina (czasu warszawskiego) zapowiedzi i przypomnień o rozpoczęciu dyżuru, patrz [Integracje](../produkt/integracje.md#powiadomienia-e-mail) | | `ONCALL_COORDINATOR_DIGEST_HOUR` | `8` | godzina (czasu warszawskiego, 0-23) wiadomości wysyłanej w dni robocze do koordynatorów i administratorów o tym, kto ma dyżur dziś i w następujące po nim dni wolne; niezależna od `ONCALL_HANDOVER_REMINDER_HOUR` | @@ -104,6 +106,39 @@ Liczba procesów API razy rozmiar puli połączeń musi mieścić się poniżej Proces roboczy ma w Compose przydział 2 CPU i z niego wynika domyślna liczba wątków solvera. Zmiana przydziału zmienia tę liczbę automatycznie. +## Ozdoby sezonowe + +Interfejs może nosić sezonowe ozdoby. Domyślnie są wyłączone: dopóki +`ONCALL_ACCENT` jest puste, nic się nie zmienia. + +`ONCALL_ACCENT` to lista pakietów oddzielonych przecinkami. Wpisujesz ją raz +i zostawiasz: każdy pakiet zna swoje dni, więc nikt nie przełącza ustawienia +na początku ani na końcu sezonu. + +| Pakiet | Kiedy | Co pokazuje | +| --- | --- | --- | +| `winter` | od 6 grudnia do 6 stycznia | czapkę na znaku produktu, girlandę światełek pod paskiem „Teraz” i śnieg w tym pasku, zimową noc na ekranie logowania, sanie na pasku postępu generatora | +| `doodles` | siedem dni w roku | mały rysunek na znaku produktu: 31 grudnia i 1 stycznia, w Tłusty Czwartek, 14 lutego, w Niedzielę i Poniedziałek Wielkanocny oraz 1 kwietnia | + +```env +ONCALL_ACCENT=winter,doodles +``` + +Inny sezon zimowy ustawiają `ONCALL_ACCENT_FROM` i `ONCALL_ACCENT_UNTIL`: +dzień roku jako `MM-DD`, oba końce włącznie. Podajesz obie albo żadnej, a +sezon może przechodzić przez Nowy Rok. Pakiet `doodles` ich nie czyta. +Nieznana nazwa pakietu, błędna data albo tylko jedna z dwóch dat zatrzymują +`api` przy starcie z komunikatem w logu. + +O tym, czy dziś jest dzień pakietu, decyduje data w strefie Europe/Warsaw. +Otwarta karta przeglądarki dowiaduje się o tym przy załadowaniu strony. + +Ozdoby są tylko na ekranie: nie trafiają do wydruku, e-maili, kalendarzy ICS +ani raportów CSV i niczego nie zasłaniają. Przy systemowym ustawieniu +ograniczenia ruchu stoją w miejscu, a każda osoba może je wyłączyć dla siebie +w menu konta (**Ozdoby**). Podgląd z linku udostępnienia nie pokazuje ich +nigdy. + ## Plik CA Wdrożenie wskazuje swoje urzędy certyfikacji **jednym** plikiem PEM, diff --git a/frontend/src/accent.test.tsx b/frontend/src/accent.test.tsx new file mode 100644 index 00000000..8d18b638 --- /dev/null +++ b/frontend/src/accent.test.tsx @@ -0,0 +1,65 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { act, fireEvent, render, screen } from '@testing-library/react' +import { ACCENT_STORAGE_KEY, applyAccent, readAccentPreference, setAccentPreference, useAccent, useAccentPreference } from './accent' + +afterEach(() => applyAccent('')) + +function Worn() { + return {useAccent().join('+')} +} + +function Switch() { + const [preference, setPreference] = useAccentPreference() + return +} + +describe('the seasonal accent', () => { + it('is worn by nothing until a screen puts it on', () => { + render() + + expect(screen.getByLabelText('worn')).toHaveTextContent('') + expect(document.documentElement).not.toHaveAttribute('data-accent') + }) + + it('reaches every reader through one attribute on , and leaves the same way', () => { + render() + + act(() => applyAccent('winter sparkle')) + expect(document.documentElement).toHaveAttribute('data-accent', 'winter sparkle') + expect(screen.getByLabelText('worn')).toHaveTextContent('winter+sparkle') + + act(() => applyAccent('')) + expect(document.documentElement).not.toHaveAttribute('data-accent') + expect(screen.getByLabelText('worn')).toHaveTextContent('') + }) + + it('stops telling a reader that has left the screen', () => { + const { unmount } = render() + unmount() + + expect(() => act(() => applyAccent('winter'))).not.toThrow() + }) +}) + +describe('the personal switch of the decorations', () => { + it('is on unless this browser turned it off', () => { + expect(readAccentPreference()).toBe('on') + + window.localStorage.setItem(ACCENT_STORAGE_KEY, 'whatever') + expect(readAccentPreference()).toBe('on') + + window.localStorage.setItem(ACCENT_STORAGE_KEY, 'off') + expect(readAccentPreference()).toBe('off') + }) + + it('is remembered in the browser and seen at once by whoever shows it', () => { + render() + + fireEvent.click(screen.getByRole('button', { name: 'on' })) + expect(screen.getByRole('button', { name: 'off' })).toBeInTheDocument() + expect(window.localStorage.getItem(ACCENT_STORAGE_KEY)).toBe('off') + + act(() => setAccentPreference('on')) + expect(screen.getByRole('button', { name: 'on' })).toBeInTheDocument() + }) +}) diff --git a/frontend/src/accent.ts b/frontend/src/accent.ts new file mode 100644 index 00000000..3e003239 --- /dev/null +++ b/frontend/src/accent.ts @@ -0,0 +1,60 @@ +import { useMemo, useSyncExternalStore } from 'react' +import type { Accent } from './api' +import { readStored, writeStored } from './theme' + +/** + * The opt-in seasonal accent. The API lists what today carries (`winter`, + * the day's doodle) and nothing at all unless the deployment set + * ONCALL_ACCENT. A screen that may wear it writes that list to `data-accent` + * on (`useAccentHost`), the one attribute the accent stylesheet and + * the decorated components read, as `data-theme` is for the palette. A + * person can turn the decorations off for their own browser. + */ +export type AccentPreference = 'on' | 'off' + +export const ACCENT_STORAGE_KEY = 'oncall-accent' + +const NONE: Accent[] = [] +const listeners = new Set<() => void>() + +function subscribe(listener: () => void) { + listeners.add(listener) + return () => { + listeners.delete(listener) + } +} + +function notify() { + for (const listener of listeners) listener() +} + +export function readAccentPreference(): AccentPreference { + return readStored(ACCENT_STORAGE_KEY) === 'off' ? 'off' : 'on' +} + +export function setAccentPreference(preference: AccentPreference) { + writeStored(ACCENT_STORAGE_KEY, preference) + notify() +} + +export function useAccentPreference(): [AccentPreference, (preference: AccentPreference) => void] { + return [useSyncExternalStore(subscribe, readAccentPreference), setAccentPreference] +} + +const worn = () => document.documentElement.dataset.accent ?? '' + +/** Writes what the current screen wears to , as the space-separated + * list CSS matches with `~=`; an empty list wears nothing. */ +export function applyAccent(list: string) { + const root = document.documentElement + if (list) root.dataset.accent = list + else delete root.dataset.accent + notify() +} + +/** What the current screen wears right now; empty on every screen of a + * deployment that did not opt in. */ +export function useAccent(): Accent[] { + const list = useSyncExternalStore(subscribe, worn) + return useMemo(() => (list ? (list.split(' ') as Accent[]) : NONE), [list]) +} diff --git a/frontend/src/api.ts b/frontend/src/api.ts index beeecc7c..58811254 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -4,6 +4,10 @@ export type AssignmentRole = 'primary' | 'secondary' | 'late_shift' export type RotationMode = 'hybrid' | 'daily' | 'weekly' export type LateShiftAnchor = 'secondary' | 'primary' | 'independent' +/** What the opt-in seasonal accent may draw: the winter season, or the day's + * doodle on the logo mark (`src/accent.ts`). */ +export type Accent = 'winter' | 'sparkle' | 'doughnut' | 'heart' | 'egg' | 'flip' + /** Instance settings the interface reads before anyone is logged in. */ export interface PublicConfig { ldap_enabled: boolean @@ -14,6 +18,9 @@ export interface PublicConfig { app_name: string /** Optional second line under the name; empty hides it. */ app_subtitle: string + /** The decorations today carries; empty unless the deployment opted in + * (ONCALL_ACCENT) and today is one of a pack's days. */ + accent: Accent[] /** The release running, as its image was built: `1.2.0`, `1.3.0-rc.1`, or * `dev` for a build from a checkout. */ version: string diff --git a/frontend/src/components/AppShell.test.tsx b/frontend/src/components/AppShell.test.tsx index 9428937f..d436629a 100644 --- a/frontend/src/components/AppShell.test.tsx +++ b/frontend/src/components/AppShell.test.tsx @@ -5,7 +5,8 @@ import { renderScreen } from '../test/render' import { AppShell } from './AppShell' import { MoreScreen } from '../screens/More' import { api } from '../api' -import type { ShareSession, SwapRequest } from '../api' +import type { Accent, ShareSession, SwapRequest } from '../api' +import { ACCENT_STORAGE_KEY } from '../accent' import { Access } from '../lib/nav' const swap = (over: Partial & { id: string }): SwapRequest => ({ @@ -31,13 +32,14 @@ function renderShell( avatar: string | null = null, route = '/', subtitle = '', + accent: Accent[] = [], ) { // `null`: the configuration never arrives, as in the first moments after // the page loads. vi.spyOn(api, 'publicConfig').mockImplementation(() => ( version === null ? new Promise(() => {}) - : Promise.resolve({ ldap_enabled: false, app_name: 'On-call', app_subtitle: subtitle, version, audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false }) + : Promise.resolve({ ldap_enabled: false, app_name: 'On-call', app_subtitle: subtitle, accent, version, audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false }) )) vi.spyOn(api, 'publishedSchedule').mockResolvedValue({ generated_at: '2026-09-01T10:00:00Z', @@ -307,6 +309,77 @@ describe('AppShell account menu', () => { }) }) +describe('AppShell seasonal accent', () => { + const SHARE: ShareSession = { label: 'Audyt', starts_on: '2026-09-05', ends_on: '2026-10-02', expires_at: '2026-10-03T00:00:00Z' } + const inWinter = (share: ShareSession | null = null) => { + vi.spyOn(api, 'swaps').mockResolvedValue([]) + return renderShell({ role: 'member', hasTeamMember: true }, 'Piotr Zieliński', share, '1.4.0', null, '/', '', ['winter']) + } + const openMenu = async () => { + fireEvent.click(await screen.findByRole('button', { name: /^Konto: / })) + return screen.findByRole('menu') + } + const worn = () => document.documentElement.getAttribute('data-accent') + + it('wears what today carries: a hat on the mark, snow in the strip and lights under it', async () => { + const { container, unmount } = inWinter() + + await waitFor(() => expect(worn()).toBe('winter')) + await waitFor(() => expect(container.querySelector('.rail .mark .fx-hat')).not.toBeNull()) + const strip = screen.getByRole('region', { name: 'Dyżur teraz' }) + await waitFor(() => expect(strip.querySelector('.fx-garland')).not.toBeNull()) + expect(strip.querySelector('.fx-strip-snow')).not.toBeNull() + + unmount() + expect(worn()).toBeNull() + }) + + it('stays plain on a day the deployment decorates nothing, and offers no switch', async () => { + vi.spyOn(api, 'swaps').mockResolvedValue([]) + const { container } = renderShell({ role: 'member', hasTeamMember: true }) + const menu = await openMenu() + + expect(within(menu).queryByText('Ozdoby')).not.toBeInTheDocument() + expect(container.querySelector('.fx')).toBeNull() + expect(worn()).toBeNull() + }) + + it('lets a person turn the decorations off for their own browser, and on again', async () => { + const { container } = inWinter() + await waitFor(() => expect(container.querySelector('.fx-garland')).not.toBeNull()) + const menu = await openMenu() + + expect(within(menu).getByText('Ozdoby')).toBeInTheDocument() + expect(within(menu).getByRole('menuitemradio', { name: 'Włączone' })).toHaveAttribute('aria-checked', 'true') + fireEvent.click(within(menu).getByRole('menuitemradio', { name: 'Wyłączone' })) + + await waitFor(() => expect(worn()).toBeNull()) + expect(container.querySelector('.fx')).toBeNull() + expect(window.localStorage.getItem(ACCENT_STORAGE_KEY)).toBe('off') + // The menu stays open, as it does for the theme, so the choice can be undone at once. + fireEvent.click(within(screen.getByRole('menu')).getByRole('menuitemradio', { name: 'Włączone' })) + await waitFor(() => expect(worn()).toBe('winter')) + }) + + it('never decorates a share-link session, and offers it no switch', async () => { + const { container } = inWinter(SHARE) + const menu = await openMenu() + + expect(within(menu).getByRole('menuitemradio', { name: 'Ciemny' })).toBeInTheDocument() + expect(within(menu).queryByText('Ozdoby')).not.toBeInTheDocument() + expect(worn()).toBeNull() + expect(container.querySelector('.fx')).toBeNull() + }) + + it('puts the hat on the mark of the phone top bar, where there is no strip to decorate', async () => { + pretendNarrow(true) + const { container } = inWinter() + + await waitFor(() => expect(container.querySelector('.mob-top .mark .fx-hat')).not.toBeNull()) + expect(container.querySelector('.fx-garland')).toBeNull() + }) +}) + describe('AppShell version', () => { const openMenu = async () => { fireEvent.click(await screen.findByRole('button', { name: /^Konto: / })) @@ -351,7 +424,7 @@ describe('AppShell version', () => { it('lists it on the phone „Więcej” screen under the application settings', async () => { vi.spyOn(api, 'publicConfig').mockResolvedValue({ - ldap_enabled: false, app_name: 'On-call', app_subtitle: '', version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, + ldap_enabled: false, app_name: 'On-call', app_subtitle: '', accent: [], version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, }) renderScreen() expect(await screen.findByText('1.4.0')).toBeInTheDocument() diff --git a/frontend/src/components/AppShell.tsx b/frontend/src/components/AppShell.tsx index ba2d4518..96f0afd4 100644 --- a/frontend/src/components/AppShell.tsx +++ b/frontend/src/components/AppShell.tsx @@ -8,6 +8,8 @@ import { formatDate } from '../lib/dates' import { useBranding, useDocumentTitle } from '../hooks/useBranding' import { useNarrow } from '../hooks/useMediaQuery' import { Density, ThemeMode, useDensity, useThemeMode } from '../theme' +import { AccentPreference, useAccentPreference } from '../accent' +import { useAccentHost, useAccentOffered } from '../hooks/useAccentHost' import { useLanguage, useMessages } from '../i18n' import { LanguageMenuRadio } from './LanguageControl' import { Avatar, Icon, IconButton, Mark, Menu, MenuLink, MenuItem, MenuRadioGroup, MenuSeparator, Segmented, cx } from '../ui' @@ -27,7 +29,11 @@ function useThemeOptions() { { value: 'default', label: t.densities.default }, { value: 'compact', label: t.densities.compact }, ] - return { themeOptions, densityOptions } + const decorationOptions: Array<{ value: AccentPreference; label: string }> = [ + { value: 'on', label: t.decorationModes.on }, + { value: 'off', label: t.decorationModes.off }, + ] + return { themeOptions, densityOptions, decorationOptions } } export function ThemeSegmented() { @@ -44,6 +50,15 @@ export function DensitySegmented() { return size="sm" label={t.density} value={density} onChange={setDensity} options={densityOptions} /> } +/** The personal switch of the seasonal decorations; a screen offers it only + * while the deployment has something to decorate with (`useAccentOffered`). */ +export function DecorationsSegmented() { + const t = useMessages().theme + const { decorationOptions } = useThemeOptions() + const [decorations, setDecorations] = useAccentPreference() + return size="sm" label={t.decorations} value={decorations} onChange={setDecorations} options={decorationOptions} /> +} + function RailLink({ path, label, icon, badge }: { path: string; label: string; icon: Parameters[0]['name']; badge?: number }) { const t = useMessages() return ( @@ -58,7 +73,7 @@ function RailLink({ path, label, icon, badge }: { path: string; label: string; i /** * The account menu behind the avatar: who is logged in, the theme, the * matrix density and the language as radio groups (Base UI keeps the menu open while they - * change), the documentation, the palette and the way out. The release + * change), the seasonal decorations on the days there are any, the documentation, the palette and the way out. The release * running closes the menu as a dim footer: this menu is the one place every * layout has (a phone, the collapsed rail, a share-link session), so it is * where the version can always be found. The avatar is the person's photo @@ -76,9 +91,12 @@ function AccountMenu({ displayName, avatar, roleLine, version, share, onPalette, }) { const t = useMessages() const [language] = useLanguage() - const { themeOptions, densityOptions } = useThemeOptions() + const { themeOptions, densityOptions, decorationOptions } = useThemeOptions() const [mode, setMode] = useThemeMode() const [density, setDensity] = useDensity() + const [decorations, setDecorations] = useAccentPreference() + // A share-link session never wears the accent, so it has nothing to switch. + const decorationsOffered = useAccentOffered() && !share return ( label={t.theme.theme} value={mode} onChange={setMode} options={themeOptions} /> label={t.theme.matrixDensity} value={density} onChange={setDensity} options={densityOptions} /> + {decorationsOffered && label={t.theme.decorations} value={decorations} onChange={setDecorations} options={decorationOptions} />} {t.shell.documentation} {!share && {t.shell.commandPalette} Ctrl K} @@ -131,6 +150,8 @@ export function AppShell({ displayName, avatar = null, access, share }: { const t = useMessages() const [language] = useLanguage() const [paletteOpen, setPaletteOpen] = useState(false) + // A share link is opened by people outside the team: no decorations there. + useAccentHost(!share) const logout = useMutation({ mutationFn: api.logout, onSuccess: () => { diff --git a/frontend/src/components/AuthFrame.test.tsx b/frontend/src/components/AuthFrame.test.tsx index 57568c36..d68fe17c 100644 --- a/frontend/src/components/AuthFrame.test.tsx +++ b/frontend/src/components/AuthFrame.test.tsx @@ -8,7 +8,7 @@ import type { PublicConfig } from '../api' const config = (over: Partial): PublicConfig => ({ ldap_enabled: false, app_name: 'Dyżury IT', - app_subtitle: '', + app_subtitle: '', accent: [], version: '1.0.0', audit_retention_days: 365, login_audit_retention_days: 90, diff --git a/frontend/src/components/AuthFrame.tsx b/frontend/src/components/AuthFrame.tsx index 4dd8f726..5e08dfa3 100644 --- a/frontend/src/components/AuthFrame.tsx +++ b/frontend/src/components/AuthFrame.tsx @@ -7,11 +7,13 @@ import { LanguageSegmented } from './LanguageControl' /** The frame around the screens shown before a session exists: the mark, a * headline, a card, and the small print with the documentation link and the - * language, the one preference a visitor can set before signing in. */ -export function AuthFrame({ title, children, screen }: { + * language, the one preference a visitor can set before signing in. + * `backdrop` is drawn behind all of it and is decoration only. */ +export function AuthFrame({ title, children, screen, backdrop }: { title: ReactNode children: ReactNode screen: string + backdrop?: ReactNode }) { const branding = useBranding() const t = useMessages() @@ -19,6 +21,7 @@ export function AuthFrame({ title, children, screen }: { useDocumentTitle(screen, branding.name) return (
+ {backdrop}
diff --git a/frontend/src/components/NowStrip.tsx b/frontend/src/components/NowStrip.tsx index ac612742..58144478 100644 --- a/frontend/src/components/NowStrip.tsx +++ b/frontend/src/components/NowStrip.tsx @@ -9,6 +9,8 @@ import { RoleLabel, Skeleton, cx } from '../ui' import { heldNumber, useForwardingNow } from '../hooks/useForwardingNow' import { useBelowWide } from '../hooks/useMediaQuery' import { NumberPill } from './NumberHandover' +import { useAccent } from '../accent' +import { StripDecor } from '../decor' const ROLES: AssignmentRole[] = ['primary', 'secondary', 'late_shift'] @@ -42,6 +44,7 @@ export function NowStrip({ children }: { children?: React.ReactNode }) { const held = heldNumber(useForwardingNow().data) const handover = useMessages().duty.handover const belowWide = useBelowWide() + const winter = useAccent().includes('winter') // In the slot of the role holding the number, also when the slot names // the calendar day's person: before the reminder hour the number is still // with yesterday's pair. @@ -99,6 +102,7 @@ export function NowStrip({ children }: { children?: React.ReactNode }) { ) })} {children &&
{children}
} + {winter && }
) } diff --git a/frontend/src/components/NumberHandover.test.tsx b/frontend/src/components/NumberHandover.test.tsx index 2a3bde41..23097be2 100644 --- a/frontend/src/components/NumberHandover.test.tsx +++ b/frontend/src/components/NumberHandover.test.tsx @@ -197,7 +197,7 @@ describe('handing the number over', () => { it('starts it in one click, says only that it switches, and Undo ends it', async () => { vi.spyOn(api, 'publicConfig').mockResolvedValue({ - ldap_enabled: false, sso_enabled: false, app_name: 'On-call', app_subtitle: '', version: 'dev', + ldap_enabled: false, sso_enabled: false, app_name: 'On-call', app_subtitle: '', accent: [], version: 'dev', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 30, }) const start = vi.spyOn(api, 'startHandover').mockResolvedValue(HANDOVER) diff --git a/frontend/src/decor/art.tsx b/frontend/src/decor/art.tsx new file mode 100644 index 00000000..eb8c82f4 --- /dev/null +++ b/frontend/src/decor/art.tsx @@ -0,0 +1,195 @@ +import { CSSProperties, Fragment, ReactNode } from 'react' +import type { Accent, AssignmentRole } from '../api' +import './decor.css' + +/** + * The drawings of the seasonal accent. All of it is decoration: hidden from + * assistive technology, never in the way of a pointer, styled only on a + * screen (`decor.css`), and still unless the person allows motion. + */ + +/** The same pseudo-random sequence on every load, so the snow does not jump + * when a screen renders again and a rendering can be compared with the last. */ +function sequence(seed: number) { + let state = seed + return () => { + state = (state + 0x6d2b79f5) | 0 + let mixed = Math.imul(state ^ (state >>> 15), 1 | state) + mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed + return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296 + } +} + +const vars = (values: Record<`--${string}`, string>) => values as CSSProperties + +function flakes(count: number, seed: number, size: [number, number], seconds: [number, number]) { + const next = sequence(seed) + const between = ([low, high]: [number, number]) => low + next() * (high - low) + return Array.from({ length: count }, (_, index) => { + const fall = between(seconds) + return ( + + ) + }) +} + +function stars(count: number, seed: number) { + const next = sequence(seed) + return Array.from({ length: count }, (_, index) => ( + + )) +} + +const HAT = ( + + + + + +) + +/** What each accent adds to the logo mark. A doodle that stands in for the + * ring or the dot has that part hidden by `decor.css`; `flip` is the + * stylesheet turning the mark over and draws nothing of its own. */ +const MARK_ART: Record = { + winter: HAT, + sparkle: ( + + + + + + ), + doughnut: ( + + + + + + ), + heart: ( + + ), + egg: ( + + + + + + ), + flip: null, +} + +export function MarkArt({ accent }: { accent: Accent[] }) { + return accent.map((name) => {MARK_ART[name]}) +} + +const STRIP_SNOW = flakes(34, 6, [2, 4.2], [4.5, 8]) +const BULBS = Array.from({ length: 24 }, (_, index) => index) +/** One shallow scallop of wire per bulb, in a box as many units wide as + * there are bulbs and stretched to the strip's width. */ +const WIRE = `M0 1${BULBS.map((index) => `Q${index + 0.5} 15 ${index + 1} 1`).join('')}` + +export function StripDecor() { + return ( + <> + + + + ) +} + +const NIGHT_STARS = stars(26, 9) +const NIGHT_SNOW = flakes(30, 19, [2, 4.5], [8, 12]) +const TREE_STAR = 'M5 .6 6.12 3.76 9.47 3.85 6.81 5.89 7.76 9.1 5 7.2 2.24 9.1 3.19 5.89 .53 3.85 3.88 3.76Z' +/** The tree, row by row, in the role marks of the schedule. */ +const TREE: AssignmentRole[][] = [ + ['primary'], + ['secondary', 'primary'], + ['late_shift', 'secondary', 'primary'], + ['primary', 'late_shift', 'secondary', 'primary'], + ['secondary', 'primary', 'secondary', 'late_shift', 'primary'], +] + +/** `mark` draws one role mark of the schedule, the tree's only ornament. */ +export function LoginNight({ mark }: { mark: (role: AssignmentRole) => ReactNode }) { + let lit = 0 + return ( + + ) +} + +/** A drift of snow lying on the card's top edge: uneven on top, rounded at the ends. */ +const CAP = 'M0 16C0 12 2 7.2 7 7.2 Q31 5.6 54.9 8.1 Q74.7 4.3 94.5 7.8 Q114.9 4.9 135.4 7 Q152.6 .7 169.7 6.6 Q190.5 5.3 211.3 7.3 Q237.9 5.5 264.5 6.9 Q292.1 1.6 319.7 7.1 Q333.4 4.2 347 7.2C352 7.2 354 12 354 16Z' + +export function LoginCap() { + return ( + + ) +} + +/** `progress` is the bar's own 0-100; the sleigh keeps just ahead of it and + * stops at the end of the track. */ +export function ProgressRider({ progress }: { progress: number }) { + return ( + + ) +} diff --git a/frontend/src/decor/decor.css b/frontend/src/decor/decor.css new file mode 100644 index 00000000..aca13006 --- /dev/null +++ b/frontend/src/decor/decor.css @@ -0,0 +1,123 @@ +/* The seasonal accent (src/accent.ts, drawn by ./art.tsx). It is decoration + * only and stays out of the way: every rule here applies on a screen and + * nowhere else, so a printout is the plain interface; nothing takes a click; + * nothing moves unless the person allows motion. Colours are the --fx-* + * tokens. Loaded with the chunk that draws it, so a deployment that set no + * ONCALL_ACCENT never downloads it. */ +@media not screen { + .fx { display: none; } +} + +@media screen { + .fx { pointer-events: none; } + + /* The logo mark: the hat and the day's doodle reach past its square, and a + doodle that stands in for the ring or the dot hides that part. */ + :root[data-accent] .mark { overflow: visible; } + :root:is([data-accent~='sparkle'], [data-accent~='heart'], [data-accent~='egg']) .mark-dot { display: none; } + :root[data-accent~='doughnut'] .mark-line { display: none; } + :root[data-accent~='flip'] .mark :is(.mark-box, .mark-line, .mark-dot) { transform: rotate(180deg); transform-origin: 32px 32px; } + .fx-hat { transform-box: fill-box; transform-origin: 20% 90%; } + .fx-hat-body { fill: var(--fx-hat); } + .fx-hat-trim { fill: var(--fx-snow); stroke: var(--fx-ol); stroke-width: 1.4; } + .fx-sparkle { fill: var(--fx-spark); } + .fx-sparkle path { transform-box: fill-box; transform-origin: center; } + .fx-dough { fill: var(--fx-dough); } + .fx-icing { fill: var(--fx-snow); } + .fx-sprinkles { fill: none; stroke: var(--fx-hat); stroke-width: 2; stroke-linecap: round; } + .fx-heart { fill: var(--fx-heart); } + .fx-egg ellipse { fill: var(--fx-snow); } + .fx-egg path { fill: none; stroke-width: 2.2; stroke-linecap: round; } + .fx-egg-a { stroke: var(--p-fill); } + .fx-egg-b { stroke: var(--late-fill); } + /* On a phone the mark is white on the action band, so what was drawn in + white or pale gold for the blue square takes the band's colour. */ + .mob-top .fx-sparkle, .mob-top .fx-egg ellipse { fill: var(--act); } + + /* The "Teraz" strip: snow behind its text, a garland hanging from its + lower edge into the page's top padding. */ + :root[data-accent~='winter'] .now { position: relative; } + :root[data-accent~='winter'] .now > :is(.now-slot, .now-tools) { position: relative; z-index: 1; } + .fx-strip-snow { position: absolute; inset: 0; overflow: hidden; container-type: size; } + .fx-garland { position: absolute; left: 0; right: 0; top: 100%; height: 24px; z-index: 1; display: grid; grid-template-columns: repeat(24, minmax(0, 1fr)); justify-items: center; } + .fx-garland svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; } + .fx-garland path { fill: none; stroke: var(--fx-wire); stroke-width: 1.2; vector-effect: non-scaling-stroke; } + .fx-garland i { position: relative; margin-top: 7px; width: 9px; height: 12px; border-radius: 50% 50% 50% 50% / 38% 38% 62% 62%; background: var(--c); box-shadow: 0 0 12px 3px color-mix(in srgb, var(--c) 75%, transparent); } + .fx-garland i::before { content: ''; position: absolute; left: 3px; top: -3px; width: 3px; height: 3.5px; border-radius: 1px; background: var(--muted); } + .fx-garland i:nth-child(4n + 2) { --c: var(--p-fill); } + .fx-garland i:nth-child(4n + 3) { --c: var(--late-fill); } + .fx-garland i:nth-child(4n) { --c: var(--sig); } + .fx-garland i:nth-child(4n + 1) { --c: var(--sec-fill); } + + /* The sign-in screen: a night sky behind the form, a tree of role marks + beside it where there is room, snow on the card. */ + :root[data-accent~='winter'] .login { position: relative; overflow: hidden; } + :root[data-accent~='winter'] :is(.login-box, .login-card) { position: relative; z-index: 1; } + .fx-night, .fx-sky { position: absolute; inset: 0; } + .fx-sky { container-type: size; } + .fx-star { position: absolute; left: var(--x); top: var(--y); width: var(--s); height: var(--s); border-radius: 50%; background: var(--fx-flake); opacity: var(--o); } + .fx-tree { position: absolute; left: calc(50% + 262px); top: 50%; transform: translateY(-50%); display: grid; gap: 5px; justify-items: center; } + .fx-tree-row { display: flex; gap: 5px; } + .fx-tree-light { display: flex; } + .fx-tree-top { width: 32px; height: 32px; margin-bottom: -3px; fill: var(--fx-gold); filter: drop-shadow(0 0 8px color-mix(in srgb, var(--fx-gold) 70%, transparent)); } + .fx-tree-trunk { width: 22px; height: 14px; border-radius: 3px; background: var(--s3); } + .fx-cap { position: absolute; left: 12px; top: -10px; width: calc(100% - 24px); height: 16px; display: block; } + .fx-cap path { fill: var(--fx-snow); } + :root[data-theme='light'] .fx-cap path { stroke: var(--line2); stroke-width: 0.6; } + + /* The generator's progress bar: a sleigh just ahead of the leading edge, + in a track of its own above the bar. */ + .fx-ride { position: relative; height: 26px; margin-bottom: -6px; container-type: inline-size; } + .fx-rider { position: absolute; left: 0; bottom: 0; width: 58px; height: 30px; overflow: visible; transform: translateX(min(var(--p) * 1cqw, 100cqw - 58px)); } + .fx-rider g { transform-origin: 50% 100%; } + .fx-line { fill: none; stroke: var(--fg); stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; } + .fx-line-thin { stroke-width: 1.2; } + .fx-sleigh { fill: var(--fx-hat); } + .fx-driver { fill: var(--late-fill); } + .fx-deer { fill: var(--muted); } + .fx-deer-neck { fill: none; stroke: var(--muted); stroke-width: 2.6; stroke-linecap: round; } +} + +@media screen and (max-width: 900px) { + .fx-tree { display: none; } +} + +/* Everything that moves. Snow exists only here: without motion a flake has + no size, so the strip and the sky are simply clear. */ +@media screen and (prefers-reduced-motion: no-preference) { + .fx-hat { animation: fx-nod 0.9s ease-in-out 0.4s 1; } + .brand:hover .fx-hat { animation-name: fx-nod-again; } + .fx-sparkle path { animation: fx-spark 1.2s ease-in-out 0.4s 1; } + + .fx-flake { position: absolute; top: -6px; left: var(--x); width: var(--s); height: var(--s); border-radius: 50%; background: var(--fx-snow); opacity: var(--o); animation: fx-fall var(--d) linear var(--dl) infinite, fx-sway var(--sd) ease-in-out var(--dl) infinite alternate; } + .fx-garland i { animation: fx-bulb 3.7s ease-in-out infinite; } + .fx-garland i:nth-child(3n + 1) { animation-duration: 2.9s; } + .fx-garland i:nth-child(3n + 2) { animation-duration: 4.3s; } + .fx-garland i:nth-child(5n + 1) { animation-delay: -0.4s; } + .fx-garland i:nth-child(5n + 2) { animation-delay: -1.9s; } + .fx-garland i:nth-child(5n + 3) { animation-delay: -3.1s; } + .fx-garland i:nth-child(5n + 4) { animation-delay: -0.9s; } + .fx-garland i:nth-child(5n) { animation-delay: -2.5s; } + + /* Nobody can switch the sign-in screen off before signing in, so its + motion ends by itself: two falls of snow, a few twinkles, one lighting + of the tree. */ + .fx-sky .fx-flake { background: var(--fx-flake); animation-iteration-count: 2, 10; } + .fx-star { animation: fx-twinkle var(--d) ease-in-out var(--dl) 4; } + .fx-tree-light { animation: fx-light 0.6s ease-out var(--dl) both; } + .fx-tree-top { transform-origin: center; animation: fx-top 3.6s ease-in-out 4; } + + .fx-rider { transition: transform 0.4s; } + .fx-rider g { animation: fx-bob 0.9s ease-in-out infinite; } + + @keyframes fx-nod { 0%, 100% { transform: rotate(0); } 25% { transform: rotate(-9deg); } 55% { transform: rotate(5deg); } 80% { transform: rotate(-2deg); } } + @keyframes fx-nod-again { 0%, 100% { transform: rotate(0); } 25% { transform: rotate(-9deg); } 55% { transform: rotate(5deg); } 80% { transform: rotate(-2deg); } } + @keyframes fx-spark { 0%, 100% { transform: scale(1) rotate(0); } 40% { transform: scale(1.35) rotate(40deg); } 75% { transform: scale(0.9) rotate(80deg); } } + @keyframes fx-fall { from { translate: 0 -10px; } to { translate: 0 calc(100cqh + 12px); } } + @keyframes fx-sway { from { transform: translateX(calc(var(--sw) * -1)); } to { transform: translateX(var(--sw)); } } + @keyframes fx-bulb { 0%, 55%, 100% { opacity: 1; } 75% { opacity: 0.28; } } + @keyframes fx-twinkle { 0%, 100% { opacity: var(--o); } 50% { opacity: 0.15; } } + @keyframes fx-light { from { opacity: 0.2; filter: brightness(0.6); } to { opacity: 1; filter: none; } } + @keyframes fx-top { 0%, 100% { transform: scale(1) rotate(0); } 50% { transform: scale(0.88) rotate(12deg); } } + @keyframes fx-bob { 0%, 100% { transform: translateY(0) rotate(0); } 50% { transform: translateY(-1.5px) rotate(-1.5deg); } } +} diff --git a/frontend/src/decor/decor.test.tsx b/frontend/src/decor/decor.test.tsx new file mode 100644 index 00000000..f7017373 --- /dev/null +++ b/frontend/src/decor/decor.test.tsx @@ -0,0 +1,150 @@ +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { act, render, waitFor } from '@testing-library/react' +import { applyAccent } from '../accent' +import { Mark, RoleMark } from '../ui' +import { LoginCap, LoginNight, ProgressRider, StripDecor } from '.' + +afterEach(() => applyAccent('')) + +/** The mark as a screen draws it while wears `accent`, once the + * decorations have loaded: `drawn` names what must be there by then. */ +async function markWearing(accent: string, drawn: string) { + act(() => applyAccent(accent)) + const { container } = render() + await waitFor(() => expect(container.querySelector(drawn)).not.toBeNull()) + return container.querySelector('svg')! +} + +describe('the logo mark on the days of an accent', () => { + it('stays the plain mark on every other day', () => { + const { container } = render() + + expect(container.querySelector('.fx')).toBeNull() + expect(container.querySelectorAll('svg > *')).toHaveLength(3) + }) + + it('wears a hat through the winter season, over the whole mark', async () => { + const mark = await markWearing('winter', '.fx-hat') + + expect(mark.querySelectorAll('.mark-box, .mark-line, .mark-dot')).toHaveLength(3) + expect(mark.lastElementChild).toHaveClass('fx', 'fx-hat') + }) + + it.each([ + ['sparkle', '.fx-sparkle'], + ['doughnut', '.fx-doughnut'], + ['heart', '.fx-heart'], + ['egg', '.fx-egg'], + ])('carries the %s doodle on its day', async (doodle, drawn) => { + const mark = await markWearing(doodle, drawn) + + expect(mark.querySelectorAll('.fx')).toHaveLength(1) + expect(mark.querySelector(drawn)).toHaveClass('fx') + }) + + it('wears the hat and the doodle together on a day that has both', async () => { + const mark = await markWearing('winter sparkle', '.fx-sparkle') + + expect(mark.querySelector('.fx-hat')).not.toBeNull() + }) + + it('is only turned over on 1 April: the stylesheet does it, and nothing is drawn', async () => { + const mark = await markWearing('winter flip', '.fx-hat') + + expect(mark.querySelectorAll('.fx')).toHaveLength(1) + }) +}) + +describe('the winter decorations', () => { + it('puts snow in the strip and a garland of lights under it, as decoration only', async () => { + const { container } = render(
) + await waitFor(() => expect(container.querySelector('.fx-garland')).not.toBeNull()) + + expect(container.querySelectorAll('.fx-strip-snow .fx-flake')).toHaveLength(34) + expect(container.querySelectorAll('.fx-garland i')).toHaveLength(24) + expect(container.querySelector('.fx-garland path')!.getAttribute('d')).toMatch(/^M0 1Q0\.5 15 1 1Q1\.5 15 2 1/) + for (const layer of container.querySelectorAll('.now > *')) { + expect(layer).toHaveClass('fx') + expect(layer).toHaveAttribute('aria-hidden', 'true') + } + }) + + it('lets the same snow fall on every rendering', async () => { + const first = render() + await waitFor(() => expect(first.container.querySelector('.fx-flake')).not.toBeNull()) + const second = render() + await waitFor(() => expect(second.container.querySelector('.fx-flake')).not.toBeNull()) + + expect(second.container.innerHTML).toBe(first.container.innerHTML) + expect(first.container.querySelector('.fx-flake')!.style.getPropertyValue('--x')).toMatch(/^\d+\.\d\d%$/) + }) + + it('draws the winter night of the sign-in screen: stars, snow and a tree of role marks', async () => { + const { container } = render( } />) + await waitFor(() => expect(container.querySelector('.fx-night')).not.toBeNull()) + + expect(container.firstElementChild).toHaveAttribute('aria-hidden', 'true') + expect(container.querySelectorAll('.fx-star')).toHaveLength(26) + expect(container.querySelectorAll('.fx-sky .fx-flake')).toHaveLength(30) + const rows = Array.from(container.querySelectorAll('.fx-tree-row'), (row) => row.textContent) + expect(rows).toEqual(['P', 'SP', '11–19SP', 'P11–19SP', 'SPS11–19P']) + // The tree lights up one mark after another, top to bottom. + const delays = Array.from(container.querySelectorAll('.fx-tree-light'), (light) => light.style.getPropertyValue('--dl')) + expect(delays).toHaveLength(15) + expect(delays.slice(0, 3)).toEqual(['0.40s', '0.58s', '0.76s']) + }) + + it('lays snow along the whole top edge of the sign-in card', async () => { + const { container } = render() + await waitFor(() => expect(container.querySelector('.fx-cap')).not.toBeNull()) + + const cap = container.querySelector('.fx-cap')! + expect(cap).toHaveAttribute('aria-hidden', 'true') + expect(cap.querySelector('path')!.getAttribute('d')).toMatch(/^M0 16C0 12 2 7\.2 7 7\.2 Q.* 347 7\.2C352 7\.2 354 12 354 16Z$/) + }) + + it('tells the sleigh how far the progress bar has come', async () => { + const { container, rerender } = render() + await waitFor(() => expect(container.querySelector('.fx-ride')).not.toBeNull()) + const ride = container.querySelector('.fx-ride')! + + expect(ride).toHaveAttribute('aria-hidden', 'true') + expect(ride.style.getPropertyValue('--p')).toBe('0') + rerender() + expect(ride.style.getPropertyValue('--p')).toBe('43') + }) +}) + +describe('the accent stylesheet', () => { + const css = readFileSync(resolve(process.cwd(), 'src/decor/decor.css'), 'utf8').replace(/\/\*[\s\S]*?\*\//g, '').trim() + /** The top-level blocks as [the at-rule's prelude, its body]. */ + const blocks = css.split(/^(?=@media)/m).map((block): [string, string] => ( + [block.slice(0, block.indexOf('{')).trim(), block.slice(block.indexOf('{') + 1, block.lastIndexOf('}'))] + )) + + it('styles the screen only, so a printout is the plain interface', () => { + // Only an `@media` and its closing brace start a line, so no rule sits outside one. + expect(css.split('\n').filter((line) => /^\S/.test(line) && !/^(@media .+ \{|\})$/.test(line))).toEqual([]) + expect(blocks.length).toBeGreaterThan(2) + for (const [prelude] of blocks) expect(prelude).toMatch(/^@media (not screen|screen( and \(.+\))?)$/) + + const offScreen = blocks.filter(([prelude]) => prelude === '@media not screen') + expect(offScreen).toHaveLength(1) + expect(offScreen[0][1].replace(/\s+/g, ' ').trim()).toBe('.fx { display: none; }') + }) + + it('moves nothing unless the person allows motion', () => { + const still = blocks.filter(([prelude]) => !prelude.includes('prefers-reduced-motion: no-preference')) + const moving = blocks.filter(([prelude]) => prelude.includes('prefers-reduced-motion: no-preference')) + + expect(moving).toHaveLength(1) + expect(moving[0][1]).toMatch(/animation:/) + for (const [, body] of still) expect(body).not.toMatch(/animation|transition|@keyframes/) + }) + + it('names its colours through the accent tokens, never a literal', () => { + expect(css).not.toMatch(/#[0-9a-fA-F]{3,8}\b|rgba?\(/) + }) +}) diff --git a/frontend/src/decor/index.tsx b/frontend/src/decor/index.tsx new file mode 100644 index 00000000..a36e9f29 --- /dev/null +++ b/frontend/src/decor/index.tsx @@ -0,0 +1,29 @@ +import { ComponentType, ReactNode, Suspense, lazy } from 'react' + +/** + * Where the seasonal accent (`src/accent.ts`) is drawn. The drawings and + * their stylesheet are one chunk (`./art`) that only a deployment with + * ONCALL_ACCENT ever downloads; each of these mounts one drawing and renders + * nothing until the chunk has arrived. A screen mounts them only while + * `useAccent()` names the accent they belong to. The chunk imports nothing + * of the application, so it never reshapes the bundles everybody downloads: + * what a drawing needs from there, its caller hands in. + */ +function deferred

(pick: (art: typeof import('./art')) => ComponentType

) { + const Art = lazy(() => import('./art').then((art) => ({ default: pick(art) }))) + return function Deferred(props: P): ReactNode { + return + } +} + +/** The hat and the day's doodle, inside the logo mark's own . */ +export const MarkArt = deferred((art) => art.MarkArt) +/** Snow inside the "Teraz" strip and the garland of lights under it. */ +export const StripDecor = deferred((art) => art.StripDecor) +/** The winter night behind the sign-in form: stars, snow, and a tree built + * from the role marks its `mark` draws. */ +export const LoginNight = deferred((art) => art.LoginNight) +/** The snow lying on the sign-in card. */ +export const LoginCap = deferred((art) => art.LoginCap) +/** The sleigh riding the leading edge of the generator's progress bar. */ +export const ProgressRider = deferred((art) => art.ProgressRider) diff --git a/frontend/src/hooks/useAccentHost.test.tsx b/frontend/src/hooks/useAccentHost.test.tsx new file mode 100644 index 00000000..96dd8932 --- /dev/null +++ b/frontend/src/hooks/useAccentHost.test.tsx @@ -0,0 +1,71 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { act, screen, waitFor } from '@testing-library/react' +import { api } from '../api' +import type { Accent, PublicConfig } from '../api' +import { ACCENT_STORAGE_KEY, setAccentPreference } from '../accent' +import { renderScreen } from '../test/render' +import { useAccentHost, useAccentOffered } from './useAccentHost' + +const config = (accent: Accent[]): PublicConfig => ({ + ldap_enabled: false, sso_enabled: false, app_name: 'On-call', app_subtitle: '', accent, version: '1.4.0', + audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, +}) + +afterEach(() => vi.restoreAllMocks()) + +function Host({ allowed }: { allowed?: boolean }) { + useAccentHost(allowed) + return {String(useAccentOffered())} +} + +const worn = () => document.documentElement.getAttribute('data-accent') + +describe('useAccentHost', () => { + it('puts what today carries on the screen that hosts it, and takes it off when the screen leaves', async () => { + vi.spyOn(api, 'publicConfig').mockResolvedValue(config(['winter', 'sparkle'])) + const { unmount } = renderScreen() + + await waitFor(() => expect(worn()).toBe('winter sparkle')) + expect(screen.getByLabelText('offered')).toHaveTextContent('true') + + unmount() + expect(worn()).toBeNull() + }) + + it('wears nothing on a day the deployment offers nothing', async () => { + vi.spyOn(api, 'publicConfig').mockResolvedValue(config([])) + const { queryClient } = renderScreen() + + await waitFor(() => expect(queryClient.getQueryData(['public-config'])).toBeDefined()) + expect(worn()).toBeNull() + expect(screen.getByLabelText('offered')).toHaveTextContent('false') + }) + + it('wears nothing before the configuration has arrived', () => { + vi.spyOn(api, 'publicConfig').mockReturnValue(new Promise(() => {})) + renderScreen() + + expect(worn()).toBeNull() + expect(screen.getByLabelText('offered')).toHaveTextContent('false') + }) + + it('never dresses a screen that may not wear it, such as a share-link session', async () => { + vi.spyOn(api, 'publicConfig').mockResolvedValue(config(['winter'])) + renderScreen() + + expect(await screen.findByText('true')).toBeInTheDocument() + expect(worn()).toBeNull() + }) + + it('leaves the screen plain for a person who turned the decorations off, until they turn them on again', async () => { + window.localStorage.setItem(ACCENT_STORAGE_KEY, 'off') + vi.spyOn(api, 'publicConfig').mockResolvedValue(config(['winter'])) + renderScreen() + + expect(await screen.findByText('true')).toBeInTheDocument() + expect(worn()).toBeNull() + + act(() => setAccentPreference('on')) + await waitFor(() => expect(worn()).toBe('winter')) + }) +}) diff --git a/frontend/src/hooks/useAccentHost.ts b/frontend/src/hooks/useAccentHost.ts new file mode 100644 index 00000000..d82cf732 --- /dev/null +++ b/frontend/src/hooks/useAccentHost.ts @@ -0,0 +1,25 @@ +import { useEffect } from 'react' +import { applyAccent, useAccentPreference } from '../accent' +import { usePublicConfig } from './usePublicConfig' + +/** Whether the deployment offers a decoration today, which is when the + * personal switch has something to switch. */ +export function useAccentOffered() { + return (usePublicConfig().data?.accent ?? []).length > 0 +} + +/** + * Lets the screen that calls it wear today's accent: the sign-in screen and + * the shell of a signed-in person. `allowed` is false for a share-link + * session, whose visitor is outside the team. Leaving the screen takes the + * accent off, so the screens that never call this stay plain. + */ +export function useAccentHost(allowed = true) { + const offered = usePublicConfig().data?.accent + const [preference] = useAccentPreference() + const list = allowed && preference === 'on' && offered ? offered.join(' ') : '' + useEffect(() => { + applyAccent(list) + return () => applyAccent('') + }, [list]) +} diff --git a/frontend/src/hooks/useBranding.test.tsx b/frontend/src/hooks/useBranding.test.tsx index 15af3cc7..2ea03834 100644 --- a/frontend/src/hooks/useBranding.test.tsx +++ b/frontend/src/hooks/useBranding.test.tsx @@ -23,7 +23,7 @@ afterEach(() => vi.restoreAllMocks()) describe('useBranding', () => { it('names the product from the deployment configuration and titles the tab with it', async () => { vi.spyOn(api, 'publicConfig').mockResolvedValue({ - ldap_enabled: true, app_name: 'Dyżury NOC', app_subtitle: 'Zespół utrzymania', version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: true, + ldap_enabled: true, app_name: 'Dyżury NOC', app_subtitle: 'Zespół utrzymania', accent: [], version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: true, }) renderScreen() expect(await screen.findByText('Dyżury NOC')).toBeInTheDocument() @@ -35,7 +35,7 @@ describe('useBranding', () => { }) it('falls back to the neutral default while the configuration is missing or blank', async () => { - vi.spyOn(api, 'publicConfig').mockResolvedValue({ ldap_enabled: false, app_name: ' ', app_subtitle: '', version: ' ', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false }) + vi.spyOn(api, 'publicConfig').mockResolvedValue({ ldap_enabled: false, app_name: ' ', app_subtitle: '', accent: [], version: ' ', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false }) renderScreen() expect(screen.getByTestId('name')).toHaveTextContent('On-call') // Neither way in is offered until the configuration says so. diff --git a/frontend/src/hooks/useUndoable.test.tsx b/frontend/src/hooks/useUndoable.test.tsx index 81c09bca..142a6f01 100644 --- a/frontend/src/hooks/useUndoable.test.tsx +++ b/frontend/src/hooks/useUndoable.test.tsx @@ -26,7 +26,7 @@ describe('useUndoable', () => { it('keeps Undo open for as long as the server holds the e-mails', async () => { vi.spyOn(api, 'publicConfig').mockResolvedValue({ - ldap_enabled: false, sso_enabled: false, app_name: 'On-call', app_subtitle: '', version: 'dev', + ldap_enabled: false, sso_enabled: false, app_name: 'On-call', app_subtitle: '', accent: [], version: 'dev', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 30, }) const { queryClient } = renderScreen() diff --git a/frontend/src/i18n/en/theme.ts b/frontend/src/i18n/en/theme.ts index b5cb127e..58e2f134 100644 --- a/frontend/src/i18n/en/theme.ts +++ b/frontend/src/i18n/en/theme.ts @@ -14,4 +14,9 @@ export const theme: Messages['theme'] = { compact: 'Compact', }, language: 'Language', + decorations: 'Decorations', + decorationModes: { + on: 'On', + off: 'Off', + }, } diff --git a/frontend/src/i18n/pl/theme.ts b/frontend/src/i18n/pl/theme.ts index 2b672524..e9334df4 100644 --- a/frontend/src/i18n/pl/theme.ts +++ b/frontend/src/i18n/pl/theme.ts @@ -1,4 +1,5 @@ -/** The colour scheme and density preferences (`src/theme.ts`). */ +/** The colour scheme and density preferences (`src/theme.ts`) and the + * personal switch of the seasonal decorations (`src/accent.ts`). */ export const theme = { theme: 'Motyw', modes: { @@ -13,4 +14,9 @@ export const theme = { compact: 'Zwarta', }, language: 'Język', + decorations: 'Ozdoby', + decorationModes: { + on: 'Włączone', + off: 'Wyłączone', + }, } diff --git a/frontend/src/screens/Generator.test.tsx b/frontend/src/screens/Generator.test.tsx index 95e79112..e17ca2ac 100644 --- a/frontend/src/screens/Generator.test.tsx +++ b/frontend/src/screens/Generator.test.tsx @@ -5,6 +5,7 @@ import { renderScreen } from '../test/render' import { chooseFromMenu } from '../test/menu' import { GeneratorPanel } from './Generator' import { api, ApiError } from '../api' +import { applyAccent } from '../accent' import type { DraftSchedule, PublishPreview, ScheduleRun, ScheduleSummary, SchedulingPolicy } from '../api' const policy: SchedulingPolicy = { @@ -111,7 +112,10 @@ const emptyPreview = { lost_changes: [], carried_changes: [], pending_swaps: [], beforeEach(() => { vi.spyOn(api, 'swapPolicy').mockResolvedValue({ coordinator_approval_required: true, late_shift_anchor: 'secondary' }) }) -afterEach(() => vi.restoreAllMocks()) +afterEach(() => { + vi.restoreAllMocks() + applyAccent('') +}) describe('GeneratorPanel draft persistence', () => { it('uses the server range when there is no calendar deep link', async () => { @@ -879,6 +883,35 @@ describe('GeneratorPanel queue and progress', () => { expect(generate).toHaveBeenCalledTimes(1) }) + it('lets a sleigh ride ahead of the bar in the winter season, and only then', async () => { + stub([]) + let report: ((progress: ScheduleRun) => void) | undefined + vi.spyOn(api, 'generateSchedule').mockImplementation((_input, onProgress) => { + report = onProgress + return new Promise(() => {}) + }) + act(() => applyAccent('winter')) + const { container } = renderScreen() + await waitFor(() => expect(document.querySelector('#generator-from')).toHaveValue('2026-09-21')) + expect(container.querySelector('.fx-ride')).toBeNull() + + fireEvent.click(screen.getByRole('button', { name: 'Generuj kolejny zakres' })) + const bar = await screen.findByRole('progressbar', { name: 'Postęp generowania' }) + await waitFor(() => expect(container.querySelector('.fx-ride')).not.toBeNull()) + const ride = container.querySelector('.fx-ride')! + expect(ride.nextElementSibling).toBe(bar) + expect(ride).toHaveAttribute('aria-hidden', 'true') + expect(ride.style.getPropertyValue('--p')).toBe('0') + + act(() => report?.(run({ id: 'r1', progress: 43 }))) + expect(ride.style.getPropertyValue('--p')).toBe('43') + expect(bar).toHaveAttribute('aria-valuenow', '43') + + act(() => applyAccent('')) + expect(container.querySelector('.fx-ride')).toBeNull() + expect(screen.getByRole('progressbar', { name: 'Postęp generowania' })).toBe(bar) + }) + it('announces stage changes only, not the solver progress within a stage', async () => { stub([]) let report: ((progress: ScheduleRun) => void) | undefined diff --git a/frontend/src/screens/Generator.tsx b/frontend/src/screens/Generator.tsx index 30825ea0..5ce4c299 100644 --- a/frontend/src/screens/Generator.tsx +++ b/frontend/src/screens/Generator.tsx @@ -21,6 +21,8 @@ import { ConfirmDialog } from '../components/ConfirmDialog' import { AcknowledgeBox } from '../components/DecisionFrame' import { DateField } from '../components/DateField' import { ScheduleComparison } from '../components/ScheduleComparison' +import { useAccent } from '../accent' +import { ProgressRider } from '../decor' import { Box, Button, @@ -269,6 +271,7 @@ export function GeneratorPanel() { }) const activeRuns = useQuery({ queryKey: ['active-runs'], queryFn: api.activeRuns }) const generating = generate.isPending || resume.isPending + const winter = useAccent().includes('winter') useEffect(() => { const running = activeRuns.data?.[0] if (!running || generating || resume.isSuccess || resume.isError) return @@ -452,6 +455,7 @@ export function GeneratorPanel() { { label: t.progress.steps.proposal, state: 'todo' }, ]} /> + {winter && }

diff --git a/frontend/src/screens/Login.test.tsx b/frontend/src/screens/Login.test.tsx index 5b3b4284..1838ca05 100644 --- a/frontend/src/screens/Login.test.tsx +++ b/frontend/src/screens/Login.test.tsx @@ -3,6 +3,7 @@ import { fireEvent, screen, waitFor } from '@testing-library/react' import { useQuery } from '@tanstack/react-query' import { useLocation } from 'react-router-dom' import { api, ApiError } from '../api' +import type { PublicConfig } from '../api' import { renderScreen } from '../test/render' import { meKey } from '../session' import { Login } from './Login' @@ -11,7 +12,7 @@ afterEach(() => vi.restoreAllMocks()) async function signInRefusedWith(error: Error) { vi.spyOn(api, 'publicConfig').mockResolvedValue({ - app_name: 'On-call', app_subtitle: '', ldap_enabled: true, version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, + app_name: 'On-call', app_subtitle: '', accent: [], ldap_enabled: true, version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, }) vi.spyOn(api, 'login').mockRejectedValue(error) renderScreen() @@ -22,7 +23,7 @@ async function signInRefusedWith(error: Error) { } const CONFIG = { - app_name: 'On-call', app_subtitle: '', ldap_enabled: false, version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, + app_name: 'On-call', app_subtitle: '', accent: [], ldap_enabled: false, version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, } /** The address bar as the router sees it, so a test can say what a reload would repeat. */ @@ -32,6 +33,7 @@ function LocationProbe() { } const SSO_CONFIG = { ...CONFIG, sso_enabled: true } +const WINTER_CONFIG: PublicConfig = { ...CONFIG, accent: ['winter'] } /** Shows who the shell would treat as signed in, the way `App` reads it. */ function SignedInProbe() { @@ -132,7 +134,7 @@ describe('Login', () => { it('shows the configured subtitle with its own casing', async () => { vi.spyOn(api, 'publicConfig').mockResolvedValue({ - app_name: 'On-call', app_subtitle: 'Zespół infrastruktury (UAT)', ldap_enabled: true, version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, + app_name: 'On-call', app_subtitle: 'Zespół infrastruktury (UAT)', accent: [], ldap_enabled: true, version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, }) renderScreen() expect(await screen.findByText(/Zespół infrastruktury \(UAT\)/)).toHaveTextContent('On-call · Zespół infrastruktury (UAT)') @@ -140,7 +142,7 @@ describe('Login', () => { it('suppresses the browser-native password reveal so its own toggle is the only one shown', async () => { vi.spyOn(api, 'publicConfig').mockResolvedValue({ - app_name: 'On-call', app_subtitle: '', ldap_enabled: true, version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, + app_name: 'On-call', app_subtitle: '', accent: [], ldap_enabled: true, version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, }) renderScreen() const passwordInput = await screen.findByLabelText('Hasło') @@ -205,3 +207,31 @@ describe('Login', () => { expect(screen.getByRole('alert')).not.toHaveTextContent('Brak konta') }) }) + +describe('Login in the winter season', () => { + it('wears the winter night: a hat on the mark, a sky and a tree behind the form, snow on the card', async () => { + vi.spyOn(api, 'publicConfig').mockResolvedValue(WINTER_CONFIG) + const { container, unmount } = renderScreen() + + await waitFor(() => expect(document.documentElement).toHaveAttribute('data-accent', 'winter')) + await waitFor(() => expect(container.querySelector('.login > .fx-night')).not.toBeNull()) + const form = screen.getByRole('form', { name: 'Logowanie' }) + await waitFor(() => expect(form.querySelector('.fx-cap')).not.toBeNull()) + expect(container.querySelector('.login-box .mark .fx-hat')).not.toBeNull() + // Decoration only: the form is what it was, and the fields are still the first things named. + expect(container.querySelector('.fx-night')).toHaveAttribute('aria-hidden', 'true') + expect(screen.getByLabelText('Login')).toBeInTheDocument() + + unmount() + expect(document.documentElement).not.toHaveAttribute('data-accent') + }) + + it('is the plain sign-in screen on every other day', async () => { + vi.spyOn(api, 'publicConfig').mockResolvedValue(CONFIG) + const { container } = renderScreen() + + expect(await screen.findByRole('form', { name: 'Logowanie' })).toBeInTheDocument() + expect(container.querySelector('.fx')).toBeNull() + expect(document.documentElement).not.toHaveAttribute('data-accent') + }) +}) diff --git a/frontend/src/screens/Login.tsx b/frontend/src/screens/Login.tsx index ad0a3a4d..ebf1416f 100644 --- a/frontend/src/screens/Login.tsx +++ b/frontend/src/screens/Login.tsx @@ -2,12 +2,16 @@ import { FormEvent, ReactNode, useEffect, useState } from 'react' import { useLocation, useSearchParams } from 'react-router-dom' import { useMutation, useQueryClient } from '@tanstack/react-query' import { api, ApiError } from '../api' +import type { AssignmentRole } from '../api' import { useBranding } from '../hooks/useBranding' import { useNarrow } from '../hooks/useMediaQuery' import { Messages, useMessages } from '../i18n' -import { AnchorButton, Box, Button, Field, IconButton, Input } from '../ui' +import { AnchorButton, Box, Button, Field, IconButton, Input, RoleMark } from '../ui' import { AuthFrame } from '../components/AuthFrame' import { meKey } from '../session' +import { useAccent } from '../accent' +import { useAccentHost } from '../hooks/useAccentHost' +import { LoginCap, LoginNight } from '../decor' /** What the person can do about a refused sign-in. Only a rejected login or * password can mean a disabled account; a directory outage or a conflict @@ -30,6 +34,9 @@ function ssoRefusalOf(code: string | null): SsoRefusal | null { return SSO_REFUSALS.find((known) => known === code) ?? null } +/** The ornaments of the winter tree beside the form: the schedule's own role marks. */ +const treeMark = (role: AssignmentRole) => + /** `expired` says the session this tab held has ended, so the person knows * why the screen they were on gave way to this one. */ export function Login({ expired = false }: { expired?: boolean }) { @@ -46,6 +53,8 @@ export function Login({ expired = false }: { expired?: boolean }) { const [ssoRefusal, setSsoRefusal] = useState(() => ssoRefusalOf(searchParams.get('sso'))) const branding = useBranding() const narrow = useNarrow() + useAccentHost() + const winter = useAccent().includes('winter') const login = useMutation({ mutationFn: () => api.login(username, password), onSuccess: (user) => queryClient.setQueryData(meKey, user), @@ -94,8 +103,9 @@ export function Login({ expired = false }: { expired?: boolean }) { } return ( - + }>
+ {winter && } {notice} {({ id }) => ( diff --git a/frontend/src/screens/Mine.test.tsx b/frontend/src/screens/Mine.test.tsx index 5dc6bb65..a4c26753 100644 --- a/frontend/src/screens/Mine.test.tsx +++ b/frontend/src/screens/Mine.test.tsx @@ -1312,7 +1312,7 @@ describe('MineScreen availability Undo', () => { it('undoes a paint in one request that names the save', async () => { stub() vi.spyOn(api, 'publicConfig').mockResolvedValue({ - ldap_enabled: false, sso_enabled: false, app_name: 'On-call', app_subtitle: '', version: 'dev', + ldap_enabled: false, sso_enabled: false, app_name: 'On-call', app_subtitle: '', accent: [], version: 'dev', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 30, }) const replace = vi.spyOn(api, 'replaceAvailabilityRange').mockImplementation(echo) diff --git a/frontend/src/screens/More.test.tsx b/frontend/src/screens/More.test.tsx index 6868a9a9..45b6fdb7 100644 --- a/frontend/src/screens/More.test.tsx +++ b/frontend/src/screens/More.test.tsx @@ -1,12 +1,14 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { fireEvent, screen, waitFor } from '@testing-library/react' +import { fireEvent, screen, waitFor, within } from '@testing-library/react' import { api } from '../api' +import type { Accent } from '../api' +import { ACCENT_STORAGE_KEY } from '../accent' import { renderScreen } from '../test/render' import { useUnsavedChanges } from '../hooks/useUnsavedChanges' import { MoreScreen } from './More' -const config = (version: string) => ({ - app_name: 'On-call', app_subtitle: '', ldap_enabled: false, version, audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, +const config = (version: string, accent: Accent[] = []) => ({ + app_name: 'On-call', app_subtitle: '', accent, ldap_enabled: false, version, audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, }) afterEach(() => vi.restoreAllMocks()) @@ -84,3 +86,26 @@ describe('MoreScreen', () => { } }) }) + +describe('MoreScreen seasonal decorations', () => { + it('offers the personal switch on the days there is something to switch', async () => { + vi.spyOn(api, 'publicConfig').mockResolvedValue(config('1.4.0', ['winter'])) + renderScreen() + + const group = await screen.findByRole('radiogroup', { name: 'Ozdoby' }) + expect(within(group).getByRole('radio', { name: 'Włączone' })).toBeChecked() + fireEvent.click(within(group).getByRole('radio', { name: 'Wyłączone' })) + + expect(within(group).getByRole('radio', { name: 'Wyłączone' })).toBeChecked() + expect(window.localStorage.getItem(ACCENT_STORAGE_KEY)).toBe('off') + }) + + it('offers nothing on an ordinary day', async () => { + vi.spyOn(api, 'publicConfig').mockResolvedValue(config('1.4.0')) + renderScreen() + + expect(await screen.findByText('1.4.0')).toBeInTheDocument() + expect(screen.getByRole('radiogroup', { name: 'Motyw' })).toBeInTheDocument() + expect(screen.queryByRole('radiogroup', { name: 'Ozdoby' })).not.toBeInTheDocument() + }) +}) diff --git a/frontend/src/screens/More.tsx b/frontend/src/screens/More.tsx index 2b43c54c..1d3a3400 100644 --- a/frontend/src/screens/More.tsx +++ b/frontend/src/screens/More.tsx @@ -4,7 +4,8 @@ import { api } from '../api' import { Access, adminNav, coordinationNav, docsHref, navLabel, primaryNav, roleLabels, visibleFor } from '../lib/nav' import { useLanguage, useMessages } from '../i18n' import { Avatar, Icon, List, ListRow, PageHeader, SectionHeading, Button } from '../ui' -import { DensitySegmented, ThemeSegmented } from '../components/AppShell' +import { DecorationsSegmented, DensitySegmented, ThemeSegmented } from '../components/AppShell' +import { useAccentOffered } from '../hooks/useAccentHost' import { LanguageSegmented } from '../components/LanguageControl' import { useBranding } from '../hooks/useBranding' import { leaveWithoutAsking } from '../hooks/useUnsavedChanges' @@ -20,6 +21,7 @@ export function MoreScreen({ displayName, avatar = null, access }: { displayName const branding = useBranding() const t = useMessages() const [language] = useLanguage() + const decorationsOffered = useAccentOffered() const logout = useMutation({ mutationFn: api.logout, onSuccess: () => { @@ -59,6 +61,7 @@ export function MoreScreen({ displayName, avatar = null, access }: { displayName }>{t.theme.theme} }>{t.theme.matrixDensity} }>{t.theme.language} + {decorationsOffered && }>{t.theme.decorations}}
{t.shell.documentation}
diff --git a/frontend/src/screens/SetPassword.test.tsx b/frontend/src/screens/SetPassword.test.tsx index 8cadf352..dd2a46ea 100644 --- a/frontend/src/screens/SetPassword.test.tsx +++ b/frontend/src/screens/SetPassword.test.tsx @@ -47,7 +47,7 @@ describe('SetPassword', () => { it.each(['activate', 'reset'] as const)('shows the configured subtitle with its own casing on %s', async (mode) => { vi.spyOn(api, 'publicConfig').mockResolvedValue({ - app_name: 'On-call', app_subtitle: 'Zespół infrastruktury (UAT)', ldap_enabled: false, version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, + app_name: 'On-call', app_subtitle: 'Zespół infrastruktury (UAT)', accent: [], ldap_enabled: false, version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, }) vi.spyOn(api, 'passwordTokenInfo').mockResolvedValue({ username: 'anna', display_name: 'Anna Kowalska', diff --git a/frontend/src/screens/Swaps.test.tsx b/frontend/src/screens/Swaps.test.tsx index 962576b1..7033f369 100644 --- a/frontend/src/screens/Swaps.test.tsx +++ b/frontend/src/screens/Swaps.test.tsx @@ -37,7 +37,7 @@ const NO_APPROVAL: SwapPolicy = { coordinator_approval_required: false, late_shi const serve = (swaps: SwapRequest[]) => async ({ status, limit = 100, offset = 0 }: Parameters[0] = {}) => swaps.filter((item) => !status || status.includes(item.status)).slice(offset, offset + limit) -const CONFIG = { ldap_enabled: false, app_name: 'On-call', app_subtitle: '', version: 'dev', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false } +const CONFIG = { ldap_enabled: false, app_name: 'On-call', app_subtitle: '', accent: [], version: 'dev', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false } function stub(swaps: SwapRequest[], policy: SwapPolicy = APPROVAL_REQUIRED) { vi.spyOn(api, 'swaps').mockImplementation(serve(swaps)) diff --git a/frontend/src/screens/admin/Audit.test.tsx b/frontend/src/screens/admin/Audit.test.tsx index 6e030a50..538a4a6b 100644 --- a/frontend/src/screens/admin/Audit.test.tsx +++ b/frontend/src/screens/admin/Audit.test.tsx @@ -6,7 +6,7 @@ import { renderScreen } from '../../test/render' import { AuditPanel } from './Audit' const config = (over: Partial = {}): PublicConfig => ({ - ldap_enabled: false, app_name: 'On-call', app_subtitle: '', version: '1.4.0', + ldap_enabled: false, app_name: 'On-call', app_subtitle: '', accent: [], version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, ...over, }) diff --git a/frontend/src/screens/admin/People.test.tsx b/frontend/src/screens/admin/People.test.tsx index 1bb94d62..e0af54ce 100644 --- a/frontend/src/screens/admin/People.test.tsx +++ b/frontend/src/screens/admin/People.test.tsx @@ -26,7 +26,7 @@ const member = (over: Partial & { id: string }): TeamMember => ({ function mockData(users: AdminUser[] = [user({ id: 'u1' })], members: TeamMember[] = []) { vi.spyOn(api, 'adminUsers').mockResolvedValue(users) vi.spyOn(api, 'team').mockResolvedValue(members) - vi.spyOn(api, 'publicConfig').mockResolvedValue({ ldap_enabled: false, app_name: 'On-call', app_subtitle: '', version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false }) + vi.spyOn(api, 'publicConfig').mockResolvedValue({ ldap_enabled: false, app_name: 'On-call', app_subtitle: '', accent: [], version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false }) } const rowOf = async (username: string) => (await screen.findByText(username, { selector: 'td' })).closest('tr') as HTMLTableRowElement @@ -757,7 +757,7 @@ describe('PeoplePanel new account in the rotation', () => { }) const ldapConfig = () => vi.spyOn(api, 'publicConfig').mockResolvedValue({ - ldap_enabled: true, app_name: 'On-call', app_subtitle: '', version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, + ldap_enabled: true, app_name: 'On-call', app_subtitle: '', accent: [], version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false, }) // Anna is in the rotation until the end of the year with one open and one diff --git a/frontend/src/session.test.tsx b/frontend/src/session.test.tsx index 12497412..58132578 100644 --- a/frontend/src/session.test.tsx +++ b/frontend/src/session.test.tsx @@ -32,7 +32,7 @@ function serverWhoseSessionEnds() { let checked = false vi.stubGlobal('fetch', vi.fn((path: string) => { if (path === '/api/v1/config') { - return json(200, { app_name: 'On-call', app_subtitle: '', ldap_enabled: false, version: '1.0.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false }) + return json(200, { app_name: 'On-call', app_subtitle: '', accent: [], ldap_enabled: false, version: '1.0.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false }) } if (path === '/api/v1/auth/login') { signedIn = true diff --git a/frontend/src/test/english.test.tsx b/frontend/src/test/english.test.tsx index e9fd5c41..0b6c3cfb 100644 --- a/frontend/src/test/english.test.tsx +++ b/frontend/src/test/english.test.tsx @@ -36,7 +36,7 @@ describe('the English interface', () => { it('offers single sign-on in English, with its refusal', async () => { vi.spyOn(api, 'publicConfig').mockResolvedValue({ - ldap_enabled: false, app_name: 'On-call', app_subtitle: '', version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: true, + ldap_enabled: false, app_name: 'On-call', app_subtitle: '', accent: [], version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: true, }) setLanguage('en') renderScreen(, { route: '/?sso=no_account' }) diff --git a/frontend/src/test/polish-baseline.test.tsx b/frontend/src/test/polish-baseline.test.tsx index 74326a04..4db15596 100644 --- a/frontend/src/test/polish-baseline.test.tsx +++ b/frontend/src/test/polish-baseline.test.tsx @@ -342,7 +342,7 @@ const FORWARDING_AT_ANNA: ForwardingNow = { }, } -const CONFIG = { ldap_enabled: true, app_name: 'On-call', app_subtitle: 'Zespół infrastruktury', version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false } +const CONFIG = { ldap_enabled: true, app_name: 'On-call', app_subtitle: 'Zespół infrastruktury', accent: [], version: '1.4.0', audit_retention_days: 365, login_audit_retention_days: 90, undo_window_seconds: 10, sso_enabled: false } /** Every query any screen makes, answered with the fixtures above. */ function stubApi() { diff --git a/frontend/src/theme.ts b/frontend/src/theme.ts index 03637130..47e43ead 100644 --- a/frontend/src/theme.ts +++ b/frontend/src/theme.ts @@ -20,7 +20,7 @@ function notify() { for (const listener of listeners) listener() } -function readStored(key: string): string | null { +export function readStored(key: string): string | null { try { return window.localStorage.getItem(key) } catch { @@ -28,7 +28,7 @@ function readStored(key: string): string | null { } } -function writeStored(key: string, value: string) { +export function writeStored(key: string, value: string) { try { window.localStorage.setItem(key, value) } catch { diff --git a/frontend/src/tokens.css b/frontend/src/tokens.css index 6bf3b374..34bb5e64 100644 --- a/frontend/src/tokens.css +++ b/frontend/src/tokens.css @@ -82,6 +82,19 @@ --rail-active-ink: #0B1F42; --rail-kbd-line: rgba(163, 181, 201, 0.4); + /* The seasonal accent (src/decor): decoration only, never a state. Snow + and the hat sit on the band, the rail or the mark, which keep their + colours in both schemes; what is drawn on the page follows the scheme. */ + --fx-snow: #FFFFFF; + --fx-flake: rgba(255, 255, 255, 0.9); + --fx-hat: #EB4C79; + --fx-ol: rgba(11, 31, 66, 0.4); + --fx-gold: #FFD98A; + --fx-spark: #FFE6A8; + --fx-dough: #E6A65C; + --fx-heart: #FF8AAA; + --fx-wire: rgba(163, 181, 201, 0.55); + --shadow: 0 30px 60px -30px rgba(2, 8, 24, 0.8); --shadow-sm: 0 10px 30px -12px rgba(2, 8, 24, 0.7); --r: 8px; @@ -138,6 +151,9 @@ --ev-red: #BC3B51; --ev-violet: #721C7A; --ev-teal: #036A6D; + --fx-flake: #9DB3CC; + --fx-gold: #9A6700; + --fx-wire: #A3B5C9; --shadow: 0 24px 48px -24px rgba(33, 65, 108, 0.35); --shadow-sm: 0 2px 8px rgba(33, 65, 108, 0.08); } diff --git a/frontend/src/ui/Icon.tsx b/frontend/src/ui/Icon.tsx index 76f9e643..94a740e2 100644 --- a/frontend/src/ui/Icon.tsx +++ b/frontend/src/ui/Icon.tsx @@ -1,3 +1,5 @@ +import { useAccent } from '../accent' +import { MarkArt } from '../decor' import { cx } from './cx' /** Rounded geometric drawings on a 24-px grid, with a 10% safe margin. */ @@ -87,14 +89,17 @@ export function Icon({ name, size = 20, className, title }: { * Duty ring with an active indicator, shared with the favicon. Square app-icon * construction: a 20% corner radius, the ring in the 75% L-zone with its round * ends kept behind the centre lines, the dot alone in the top-right quarter, - * and a 13% safe margin. + * and a 13% safe margin. On the days of an opt-in seasonal accent it also + * wears that accent's hat or doodle (`src/accent.ts`). */ export function Mark({ size = 26, className }: { size?: number; className?: string }) { + const accent = useAccent() return ( ) } From b76cec6a01fbac05306934c2a730f4a8a8adbb00 Mon Sep 17 00:00:00 2001 From: lowicz Date: Wed, 2 Dec 2026 15:19:32 +0100 Subject: [PATCH 2/8] no-mistakes(review): harden seasonal decorations after review --- DESIGN.md | 7 +- backend/src/oncall/accent.py | 17 +- backend/src/oncall/config.py | 15 +- backend/tests/test_config.py | 33 +++- docs/en/wdrozenie/uruchomienie.md | 4 + docs/wdrozenie/uruchomienie.md | 4 + frontend/src/App.test.tsx | 2 +- frontend/src/App.tsx | 2 +- frontend/src/accent.test.tsx | 17 +- frontend/src/components/AppShell.tsx | 2 +- frontend/src/decor/art.tsx | 4 +- frontend/src/decor/decor.css | 22 +-- frontend/src/decor/decor.test.tsx | 200 +++++++++++++++++----- frontend/src/decor/index.tsx | 10 +- frontend/src/hooks/useAccentHost.test.tsx | 9 +- frontend/src/hooks/useAccentHost.ts | 9 +- frontend/src/screens/More.test.tsx | 14 ++ frontend/src/screens/More.tsx | 5 +- frontend/src/test/stylesheet.ts | 17 ++ frontend/src/theme.test.tsx | 8 + frontend/src/theme.ts | 8 +- frontend/src/tokens.css | 7 +- 22 files changed, 318 insertions(+), 98 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index a97637ef..40652fe4 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -568,6 +568,9 @@ drawing lives in one lazily loaded chunk with its own stylesheet garland of lights under it, a night sky with a tree of role marks on the sign-in screen, and a sleigh ahead of the generator's progress bar. `doodles` puts one small drawing on the logo mark on seven days of the year. +The garland and the snow of the strip are on the desktop "Teraz" strip only: +the top bar of a phone shows only the hat or the day's doodle on the mark, +because a garland under that sticky bar would cover content. ### Named Rules **The Frame, Not the Instrument Rule.** The accent decorates the frame: the @@ -578,8 +581,8 @@ state colour as a state. `aria-hidden`, takes no pointer events and has its own `--fx-*` colours in `tokens.css`. `decor.css` styles it on a screen only, so a printout, the e-mails and the exports are the plain interface. -**The Stillness Rule.** Nothing of it moves under `prefers-reduced-motion`, -and what moves without end (the snow and the lights of the strip) can be +**The Stillness Rule.** Nothing of it moves under `prefers-reduced-motion` +(the snow is a still scatter of flakes), and what moves without end (the snow and the lights of the strip) can be turned off by each person in the account menu. The sign-in screen, which has no such switch yet, stops moving by itself. **The Insiders Rule.** A share-link session, opened by people outside the diff --git a/backend/src/oncall/accent.py b/backend/src/oncall/accent.py index 9bf99dfd..8d29aaf7 100644 --- a/backend/src/oncall/accent.py +++ b/backend/src/oncall/accent.py @@ -12,6 +12,8 @@ from datetime import date, timedelta from typing import Literal +from oncall.workdays import polish_holidays + #: What a deployment may list in ONCALL_ACCENT. AccentPack = Literal["winter", "doodles"] #: What the interface may be told to draw: `winter`, or the day's doodle. @@ -26,18 +28,9 @@ def easter_sunday(year: int) -> date: - """Western Easter, by the anonymous Gregorian computus.""" - golden = year % 19 - century, year_of_century = divmod(year, 100) - leap_centuries, century_rest = divmod(century, 4) - correction = (8 * century + 13) // 25 - epact = (19 * golden + century - leap_centuries - correction + 15) % 30 - leap_years, year_rest = divmod(year_of_century, 4) - weekday = (32 + 2 * century_rest + 2 * leap_years - epact - year_rest) % 7 - late = (golden + 11 * epact + 19 * weekday) // 433 - month = (epact + weekday - 7 * late + 90) // 25 - day = (epact + weekday - 7 * late + 33 * month + 19) % 32 - return date(year, month, day) + """Easter by the statutory calendar, where its Sunday and Monday are the + only holidays between the earliest and the latest date Easter can have.""" + return min(polish_holidays(date(year, 3, 22), date(year, 4, 25))) def in_season(day: date, starts: str, ends: str) -> bool: diff --git a/backend/src/oncall/config.py b/backend/src/oncall/config.py index c403af7c..fc92468c 100644 --- a/backend/src/oncall/config.py +++ b/backend/src/oncall/config.py @@ -1,5 +1,6 @@ import os -from datetime import datetime +import re +from datetime import date from functools import lru_cache from math import ceil from pathlib import Path @@ -274,24 +275,26 @@ def _blank_version_means_dev(cls, value: str) -> str: def _accent_is_a_comma_separated_list(cls, value: object) -> object: """`winter,doodles` as the environment writes it; blank is none.""" if isinstance(value, str): - return tuple(name.strip().lower() for name in value.split(",") if name.strip()) + return tuple(name.strip() for name in value.split(",")) if value.strip() else () return value @field_validator("accent_from", "accent_until") @classmethod def _accent_bound_is_a_day_of_the_year(cls, value: str) -> str: """Blank is unset; anything else is a day of the year, 29 February - included, kept zero-padded so two bounds compare as text.""" - bound = value.strip() - if not bound: + included, in two digits each so two bounds compare as text.""" + if not value.strip(): return "" try: - return datetime.strptime(f"2000-{bound}", "%Y-%m-%d").strftime("%m-%d") + if not re.fullmatch("[0-9]{2}-[0-9]{2}", value): + raise ValueError + date.fromisoformat(f"2000-{value}") except ValueError: raise ValueError( "ONCALL_ACCENT_FROM and ONCALL_ACCENT_UNTIL are days of the year written " "MM-DD, such as 12-06." ) from None + return value @field_validator("solver_workers", mode="before") @classmethod diff --git a/backend/tests/test_config.py b/backend/tests/test_config.py index 670a46ac..10b2d492 100644 --- a/backend/tests/test_config.py +++ b/backend/tests/test_config.py @@ -318,7 +318,7 @@ def test_the_accent_is_off_by_default() -> None: assert settings.accent_season == ("12-06", "01-06") -@pytest.mark.parametrize("blank", ["", " ", " , "], ids=["empty", "spaces", "commas"]) +@pytest.mark.parametrize("blank", ["", " "], ids=["empty", "spaces"]) def test_a_blank_accent_is_none(monkeypatch, blank: str) -> None: monkeypatch.setenv("ONCALL_ACCENT", blank) monkeypatch.setenv("ONCALL_ACCENT_FROM", " ") @@ -331,7 +331,7 @@ def test_a_blank_accent_is_none(monkeypatch, blank: str) -> None: def test_the_accent_lists_packs_separated_by_commas(monkeypatch) -> None: - monkeypatch.setenv("ONCALL_ACCENT", " Winter, doodles ") + monkeypatch.setenv("ONCALL_ACCENT", " winter, doodles ") assert Settings().accent == ("winter", "doodles") assert Settings(accent=("doodles",)).accent == ("doodles",) @@ -347,13 +347,36 @@ def test_an_unknown_accent_pack_is_refused_without_echoing_it(monkeypatch) -> No assert "halloween-do-not-log" not in str(refused.value) -def test_the_winter_season_of_a_deployment_is_kept_zero_padded() -> None: - settings = Settings(accent="winter", accent_from=" 12-1 ", accent_until="2-29") +@pytest.mark.parametrize("names", ["Winter", "WINTER,doodles", "winter,", " , "]) +def test_an_accent_pack_is_named_exactly(monkeypatch, names: str) -> None: + monkeypatch.setenv("ONCALL_ACCENT", names) + + with pytest.raises(ValidationError, match="'winter' or 'doodles'"): + Settings() + + +def test_a_deployment_may_name_its_own_winter_season() -> None: + settings = Settings(accent="winter", accent_from="12-01", accent_until="02-29") assert settings.accent_season == ("12-01", "02-29") -@pytest.mark.parametrize("bound", ["13-01", "02-30", "6 Dec", "12-06-2026", "1206"]) +@pytest.mark.parametrize( + "bound", + [ + "13-01", + "02-30", + "6 Dec", + "12-06-2026", + "1206", + "12-1", + "2-29", + " 12-06 ", + "12-06\n", + "W12-6", + "١٢-٠٦", + ], +) def test_an_accent_bound_must_be_a_day_of_the_year(bound: str) -> None: with pytest.raises(ValidationError, match="written MM-DD"): Settings(accent_from=bound, accent_until="01-06") diff --git a/docs/en/wdrozenie/uruchomienie.md b/docs/en/wdrozenie/uruchomienie.md index 4bdb6ad1..9df6dfb1 100644 --- a/docs/en/wdrozenie/uruchomienie.md +++ b/docs/en/wdrozenie/uruchomienie.md @@ -123,6 +123,10 @@ season starts or ends. | `winter` | from 6 December to 6 January | a hat on the product mark, a garland of lights under the “Teraz” strip and snow inside that strip, a winter night on the sign-in screen, a sleigh on the generator's progress bar | | `doodles` | seven days a year | a small drawing on the product mark: on 31 December and 1 January, on Fat Thursday, on 14 February, on Easter Sunday and Monday, and on 1 April | +The garland and the snow inside the strip are on the desktop “Teraz” strip +only. A phone has no such strip: its top bar shows only the hat or the day's +drawing on the product mark. + ```env ONCALL_ACCENT=winter,doodles ``` diff --git a/docs/wdrozenie/uruchomienie.md b/docs/wdrozenie/uruchomienie.md index 46d6de3b..0b0f1a35 100644 --- a/docs/wdrozenie/uruchomienie.md +++ b/docs/wdrozenie/uruchomienie.md @@ -120,6 +120,10 @@ na początku ani na końcu sezonu. | `winter` | od 6 grudnia do 6 stycznia | czapkę na znaku produktu, girlandę światełek pod paskiem „Teraz” i śnieg w tym pasku, zimową noc na ekranie logowania, sanie na pasku postępu generatora | | `doodles` | siedem dni w roku | mały rysunek na znaku produktu: 31 grudnia i 1 stycznia, w Tłusty Czwartek, 14 lutego, w Niedzielę i Poniedziałek Wielkanocny oraz 1 kwietnia | +Girlanda i śnieg w pasku są tylko na pasku „Teraz” w układzie na komputer. +Telefon nie ma tego paska: jego górny pasek pokazuje samą czapkę albo rysunek +dnia na znaku produktu. + ```env ONCALL_ACCENT=winter,doodles ``` diff --git a/frontend/src/App.test.tsx b/frontend/src/App.test.tsx index c02b15cc..065e2a2f 100644 --- a/frontend/src/App.test.tsx +++ b/frontend/src/App.test.tsx @@ -153,7 +153,7 @@ describe('the dashboard', () => { it.each([ ['/grafik', 'Schedule role=viewer displayName=Jan Kowal hasTeamMember=false'], - ['/wiecej', 'More displayName=Jan Kowal avatar=null'], + ['/wiecej', 'More displayName=Jan Kowal avatar=null share=null'], ])('lets anyone open %s', async (route, shown) => { signIn(user('viewer')) renderScreen(, { route }) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index e78fd6f5..2c0982c5 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -77,7 +77,7 @@ function Dashboard({ displayName, avatar, role, hasTeamMember, share }: { } /> {/* The old path stays linkable. */} } /> - } /> + } /> { act(() => setAccentPreference('on')) expect(screen.getByRole('button', { name: 'on' })).toBeInTheDocument() }) + + it('still switches for this page in a browser that cannot store the choice', () => { + window.localStorage.setItem(ACCENT_STORAGE_KEY, 'on') + const full = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('full') }) + render() + + fireEvent.click(screen.getByRole('button', { name: 'on' })) + expect(screen.getByRole('button', { name: 'off' })).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: 'off' })) + expect(screen.getByRole('button', { name: 'on' })).toBeInTheDocument() + + full.mockRestore() + fireEvent.click(screen.getByRole('button', { name: 'on' })) + expect(window.localStorage.getItem(ACCENT_STORAGE_KEY)).toBe('off') + }) }) diff --git a/frontend/src/components/AppShell.tsx b/frontend/src/components/AppShell.tsx index 96f0afd4..f0b61320 100644 --- a/frontend/src/components/AppShell.tsx +++ b/frontend/src/components/AppShell.tsx @@ -96,7 +96,7 @@ function AccountMenu({ displayName, avatar, roleLine, version, share, onPalette, const [density, setDensity] = useDensity() const [decorations, setDecorations] = useAccentPreference() // A share-link session never wears the accent, so it has nothing to switch. - const decorationsOffered = useAccentOffered() && !share + const decorationsOffered = useAccentOffered(!share) return (
low + next() * (high - low) return Array.from({ length: count }, (_, index) => { const fall = between(seconds) + const fallen = next() return ( { const { container } = render(
) await waitFor(() => expect(container.querySelector('.fx-garland')).not.toBeNull()) - expect(container.querySelectorAll('.fx-strip-snow .fx-flake')).toHaveLength(34) - expect(container.querySelectorAll('.fx-garland i')).toHaveLength(24) - expect(container.querySelector('.fx-garland path')!.getAttribute('d')).toMatch(/^M0 1Q0\.5 15 1 1Q1\.5 15 2 1/) + expect(container.querySelector('.fx-strip-snow .fx-flake')).not.toBeNull() + // About twenty lights. + const lights = container.querySelectorAll('.fx-garland i').length + expect(lights).toBeGreaterThanOrEqual(18) + expect(lights).toBeLessThanOrEqual(24) for (const layer of container.querySelectorAll('.now > *')) { expect(layer).toHaveClass('fx') expect(layer).toHaveAttribute('aria-hidden', 'true') @@ -78,7 +79,6 @@ describe('the winter decorations', () => { await waitFor(() => expect(second.container.querySelector('.fx-flake')).not.toBeNull()) expect(second.container.innerHTML).toBe(first.container.innerHTML) - expect(first.container.querySelector('.fx-flake')!.style.getPropertyValue('--x')).toMatch(/^\d+\.\d\d%$/) }) it('draws the winter night of the sign-in screen: stars, snow and a tree of role marks', async () => { @@ -86,23 +86,20 @@ describe('the winter decorations', () => { await waitFor(() => expect(container.querySelector('.fx-night')).not.toBeNull()) expect(container.firstElementChild).toHaveAttribute('aria-hidden', 'true') - expect(container.querySelectorAll('.fx-star')).toHaveLength(26) - expect(container.querySelectorAll('.fx-sky .fx-flake')).toHaveLength(30) - const rows = Array.from(container.querySelectorAll('.fx-tree-row'), (row) => row.textContent) - expect(rows).toEqual(['P', 'SP', '11–19SP', 'P11–19SP', 'SPS11–19P']) + expect(container.querySelector('.fx-star')).not.toBeNull() + expect(container.querySelector('.fx-sky .fx-flake')).not.toBeNull() + const marks = Array.from(container.querySelectorAll('.fx-tree-light'), (light) => light.textContent) + expect(new Set(marks)).toEqual(new Set(['P', 'S', '11–19'])) // The tree lights up one mark after another, top to bottom. - const delays = Array.from(container.querySelectorAll('.fx-tree-light'), (light) => light.style.getPropertyValue('--dl')) - expect(delays).toHaveLength(15) - expect(delays.slice(0, 3)).toEqual(['0.40s', '0.58s', '0.76s']) + const delays = Array.from(container.querySelectorAll('.fx-tree-light'), (light) => parseFloat(light.style.getPropertyValue('--dl'))) + expect(delays.slice(1).every((delay, index) => delay > delays[index])).toBe(true) }) - it('lays snow along the whole top edge of the sign-in card', async () => { + it('lays snow on the sign-in card', async () => { const { container } = render() await waitFor(() => expect(container.querySelector('.fx-cap')).not.toBeNull()) - const cap = container.querySelector('.fx-cap')! - expect(cap).toHaveAttribute('aria-hidden', 'true') - expect(cap.querySelector('path')!.getAttribute('d')).toMatch(/^M0 16C0 12 2 7\.2 7 7\.2 Q.* 347 7\.2C352 7\.2 354 12 354 16Z$/) + expect(container.querySelector('.fx-cap')).toHaveAttribute('aria-hidden', 'true') }) it('tells the sleigh how far the progress bar has come', async () => { @@ -117,34 +114,157 @@ describe('the winter decorations', () => { }) }) -describe('the accent stylesheet', () => { - const css = readFileSync(resolve(process.cwd(), 'src/decor/decor.css'), 'utf8').replace(/\/\*[\s\S]*?\*\//g, '').trim() - /** The top-level blocks as [the at-rule's prelude, its body]. */ - const blocks = css.split(/^(?=@media)/m).map((block): [string, string] => ( - [block.slice(0, block.indexOf('{')).trim(), block.slice(block.indexOf('{') + 1, block.lastIndexOf('}'))] - )) +/** Every drawing at once, on a day that carries all the marks' doodles. */ +async function everyDrawing() { + act(() => applyAccent('winter sparkle doughnut heart egg')) + const { container } = render( + <> + +
+
+ } /> + +
+ + , + ) + await waitFor(() => { + for (const drawn of ['.fx-hat', '.fx-sparkle', '.fx-doughnut', '.fx-heart', '.fx-egg', '.fx-garland', '.fx-night', '.fx-cap', '.fx-ride']) { + expect(container.querySelector(drawn)).not.toBeNull() + } + }) + return container +} - it('styles the screen only, so a printout is the plain interface', () => { - // Only an `@media` and its closing brace start a line, so no rule sits outside one. - expect(css.split('\n').filter((line) => /^\S/.test(line) && !/^(@media .+ \{|\})$/.test(line))).toEqual([]) - expect(blocks.length).toBeGreaterThan(2) - for (const [prelude] of blocks) expect(prelude).toMatch(/^@media (not screen|screen( and \(.+\))?)$/) +const moves = (element: Element) => { + const { animationName, transitionDuration } = getComputedStyle(element) + return !['', 'none'].includes(animationName) || !['', '0s'].includes(transitionDuration) +} - const offScreen = blocks.filter(([prelude]) => prelude === '@media not screen') - expect(offScreen).toHaveLength(1) - expect(offScreen[0][1].replace(/\s+/g, ' ').trim()).toBe('.fx { display: none; }') +describe('the accent as the stylesheet draws it', () => { + it.each([ + ['sparkle', '.fx-sparkle', { '.mark-dot': 'none', '.mark-line': 'inline' }], + ['heart', '.fx-heart', { '.mark-dot': 'none', '.mark-line': 'inline' }], + ['egg', '.fx-egg', { '.mark-dot': 'none', '.mark-line': 'inline' }], + ['doughnut', '.fx-doughnut', { '.mark-dot': 'inline', '.mark-line': 'none' }], + ['winter', '.fx-hat', { '.mark-dot': 'inline', '.mark-line': 'inline' }], + ])('puts the %s drawing in the place of the part it stands for', async (accent, drawn, parts) => { + loadAccentStylesheet() + const mark = await markWearing(accent, drawn) + + for (const [part, display] of Object.entries(parts)) { + expect(getComputedStyle(mark.querySelector(part)!).display).toBe(display) + } }) - it('moves nothing unless the person allows motion', () => { - const still = blocks.filter(([prelude]) => !prelude.includes('prefers-reduced-motion: no-preference')) - const moving = blocks.filter(([prelude]) => prelude.includes('prefers-reduced-motion: no-preference')) + it('turns the mark over on 1 April', () => { + loadAccentStylesheet() + act(() => applyAccent('flip')) + const { container } = render() - expect(moving).toHaveLength(1) - expect(moving[0][1]).toMatch(/animation:/) - for (const [, body] of still) expect(body).not.toMatch(/animation|transition|@keyframes/) + for (const part of container.querySelectorAll('.mark-box, .mark-line, .mark-dot')) { + expect(getComputedStyle(part).transform).toBe('rotate(180deg)') + } }) - it('names its colours through the accent tokens, never a literal', () => { - expect(css).not.toMatch(/#[0-9a-fA-F]{3,8}\b|rgba?\(/) + it('takes no click', async () => { + loadAccentStylesheet() + for (const drawing of (await everyDrawing()).querySelectorAll('.fx')) { + expect(getComputedStyle(drawing).pointerEvents).toBe('none') + } + }) + + it('leaves the printout plain', async () => { + loadAccentStylesheet({ print: true }) + const container = await everyDrawing() + + for (const drawing of container.querySelectorAll('.fx')) expect(getComputedStyle(drawing).display).toBe('none') + for (const part of container.querySelectorAll('.mark-box, .mark-line, .mark-dot')) { + expect(getComputedStyle(part).display).toBe('inline') + } + }) + + it('moves for a person who allows motion, and on the sign-in screen only for a while', async () => { + loadAccentStylesheet() + const container = await everyDrawing() + + for (const moving of ['.fx-hat', '.fx-sparkle path', '.fx-strip-snow .fx-flake', '.fx-garland i', '.fx-sky .fx-flake', '.fx-star', '.fx-rider']) { + expect(moves(container.querySelector(moving)!)).toBe(true) + } + for (const once of ['.fx-hat', '.fx-sparkle path']) { + expect(getComputedStyle(container.querySelector(once)!).animationIterationCount).toBe('1') + } + for (const element of container.querySelectorAll('.fx-night, .fx-night *')) { + expect(getComputedStyle(element).animationIterationCount).not.toContain('infinite') + } + }) + + it('stands still under reduced motion, the snow as a scatter of flakes', async () => { + loadAccentStylesheet({ reducedMotion: true }) + const container = await everyDrawing() + + for (const element of container.querySelectorAll('.fx, .fx *')) expect(moves(element)).toBe(false) + for (const sky of ['.fx-strip-snow', '.fx-sky']) { + const flakes = Array.from(container.querySelectorAll(`${sky} .fx-flake`), (flake) => getComputedStyle(flake)) + for (const flake of flakes) { + expect(flake.position).toBe('absolute') + expect(parseFloat(flake.width)).toBeGreaterThan(0) + expect(parseFloat(flake.height)).toBeGreaterThan(0) + expect(flake.backgroundColor).not.toBe('rgba(0, 0, 0, 0)') + } + const heights = flakes.map((flake) => parseFloat(flake.top)) + expect(heights.filter((top) => top < 50).length).toBeGreaterThan(3) + expect(heights.filter((top) => top >= 50 && top <= 100).length).toBeGreaterThan(3) + expect(heights.every((top) => top >= 0 && top <= 100)).toBe(true) + } + }) + + it('hangs the same garland in both themes', async () => { + loadAccentStylesheet() + const container = await everyDrawing() + const root = document.documentElement + const paint = () => [ + getComputedStyle(container.querySelector('.fx-garland path')!).stroke, + ...Array.from(container.querySelectorAll('.fx-garland i'), (bulb) => getComputedStyle(bulb).backgroundColor), + ] + const dark = paint() + const darkPage = getComputedStyle(root).getPropertyValue('--bg') + root.dataset.theme = 'light' + try { + expect(getComputedStyle(root).getPropertyValue('--bg')).not.toBe(darkPage) + expect(paint()).toEqual(dark) + } finally { + delete root.dataset.theme + } + expect(new Set(dark.slice(1)).size).toBe(4) + }) +}) + +describe('decorations that cannot be loaded', () => { + afterEach(() => { + vi.doUnmock('./art') + vi.resetModules() + }) + + it('leave the plain interface', async () => { + vi.resetModules() + vi.doMock('./art', () => { throw new Error('the chunk is gone') }) + const decor = await import('.') + const { container } = render( + <> +

interface

+ + + null} /> + + + , + ) + await act(async () => { + await expect(import('./art')).rejects.toThrow() + await new Promise((settled) => { setTimeout(settled, 100) }) + }) + + expect(container.innerHTML).toBe('

interface

') }) }) diff --git a/frontend/src/decor/index.tsx b/frontend/src/decor/index.tsx index a36e9f29..194ebdc9 100644 --- a/frontend/src/decor/index.tsx +++ b/frontend/src/decor/index.tsx @@ -4,13 +4,17 @@ import { ComponentType, ReactNode, Suspense, lazy } from 'react' * Where the seasonal accent (`src/accent.ts`) is drawn. The drawings and * their stylesheet are one chunk (`./art`) that only a deployment with * ONCALL_ACCENT ever downloads; each of these mounts one drawing and renders - * nothing until the chunk has arrived. A screen mounts them only while - * `useAccent()` names the accent they belong to. The chunk imports nothing + * nothing until the chunk has arrived, or for good if it cannot be loaded. + * A screen mounts them only while `useAccent()` names the accent they belong + * to. The chunk imports nothing * of the application, so it never reshapes the bundles everybody downloads: * what a drawing needs from there, its caller hands in. */ function deferred

(pick: (art: typeof import('./art')) => ComponentType

) { - const Art = lazy(() => import('./art').then((art) => ({ default: pick(art) }))) + const Art = lazy>(() => import('./art').then( + (art) => ({ default: pick(art) }), + () => ({ default: () => null }), + )) return function Deferred(props: P): ReactNode { return } diff --git a/frontend/src/hooks/useAccentHost.test.tsx b/frontend/src/hooks/useAccentHost.test.tsx index 96dd8932..25de40c5 100644 --- a/frontend/src/hooks/useAccentHost.test.tsx +++ b/frontend/src/hooks/useAccentHost.test.tsx @@ -13,9 +13,9 @@ const config = (accent: Accent[]): PublicConfig => ({ afterEach(() => vi.restoreAllMocks()) -function Host({ allowed }: { allowed?: boolean }) { +function Host({ allowed = true }: { allowed?: boolean }) { useAccentHost(allowed) - return {String(useAccentOffered())} + return {String(useAccentOffered(allowed))} } const worn = () => document.documentElement.getAttribute('data-accent') @@ -51,10 +51,11 @@ describe('useAccentHost', () => { it('never dresses a screen that may not wear it, such as a share-link session', async () => { vi.spyOn(api, 'publicConfig').mockResolvedValue(config(['winter'])) - renderScreen() + const { queryClient } = renderScreen() - expect(await screen.findByText('true')).toBeInTheDocument() + await waitFor(() => expect(queryClient.getQueryData(['public-config'])).toBeDefined()) expect(worn()).toBeNull() + expect(screen.getByLabelText('offered')).toHaveTextContent('false') }) it('leaves the screen plain for a person who turned the decorations off, until they turn them on again', async () => { diff --git a/frontend/src/hooks/useAccentHost.ts b/frontend/src/hooks/useAccentHost.ts index d82cf732..b992eb62 100644 --- a/frontend/src/hooks/useAccentHost.ts +++ b/frontend/src/hooks/useAccentHost.ts @@ -2,10 +2,11 @@ import { useEffect } from 'react' import { applyAccent, useAccentPreference } from '../accent' import { usePublicConfig } from './usePublicConfig' -/** Whether the deployment offers a decoration today, which is when the - * personal switch has something to switch. */ -export function useAccentOffered() { - return (usePublicConfig().data?.accent ?? []).length > 0 +/** Whether this session has a decoration to wear today, which is when the + * personal switch has something to switch. `allowed` as in `useAccentHost`. */ +export function useAccentOffered(allowed: boolean) { + const offered = usePublicConfig().data?.accent ?? [] + return allowed && offered.length > 0 } /** diff --git a/frontend/src/screens/More.test.tsx b/frontend/src/screens/More.test.tsx index 45b6fdb7..4d53f7f3 100644 --- a/frontend/src/screens/More.test.tsx +++ b/frontend/src/screens/More.test.tsx @@ -100,6 +100,20 @@ describe('MoreScreen seasonal decorations', () => { expect(window.localStorage.getItem(ACCENT_STORAGE_KEY)).toBe('off') }) + it('offers a share-link session no switch, because it never wears the accent', async () => { + vi.spyOn(api, 'publicConfig').mockResolvedValue(config('1.4.0', ['winter'])) + renderScreen( + , + ) + + expect(await screen.findByText('1.4.0')).toBeInTheDocument() + expect(screen.queryByRole('radiogroup', { name: 'Ozdoby' })).not.toBeInTheDocument() + }) + it('offers nothing on an ordinary day', async () => { vi.spyOn(api, 'publicConfig').mockResolvedValue(config('1.4.0')) renderScreen() diff --git a/frontend/src/screens/More.tsx b/frontend/src/screens/More.tsx index 1d3a3400..be3ab8ca 100644 --- a/frontend/src/screens/More.tsx +++ b/frontend/src/screens/More.tsx @@ -1,6 +1,7 @@ import { NavLink } from 'react-router-dom' import { useMutation, useQueryClient } from '@tanstack/react-query' import { api } from '../api' +import type { ShareSession } from '../api' import { Access, adminNav, coordinationNav, docsHref, navLabel, primaryNav, roleLabels, visibleFor } from '../lib/nav' import { useLanguage, useMessages } from '../i18n' import { Avatar, Icon, List, ListRow, PageHeader, SectionHeading, Button } from '../ui' @@ -16,12 +17,12 @@ import { leaveWithoutAsking } from '../hooks/useUnsavedChanges' * running. On a desktop the rail has all of it, so this screen is reachable * but not linked. */ -export function MoreScreen({ displayName, avatar = null, access }: { displayName: string; avatar?: string | null; access: Access }) { +export function MoreScreen({ displayName, avatar = null, access, share = null }: { displayName: string; avatar?: string | null; access: Access; share?: ShareSession | null }) { const queryClient = useQueryClient() const branding = useBranding() const t = useMessages() const [language] = useLanguage() - const decorationsOffered = useAccentOffered() + const decorationsOffered = useAccentOffered(!share) const logout = useMutation({ mutationFn: api.logout, onSuccess: () => { diff --git a/frontend/src/test/stylesheet.ts b/frontend/src/test/stylesheet.ts index cd173e22..6b6edc1b 100644 --- a/frontend/src/test/stylesheet.ts +++ b/frontend/src/test/stylesheet.ts @@ -29,6 +29,23 @@ export function loadRealStylesheet() { return appendStylesheet(appStyles()) } +/** + * Loads the app's stylesheet together with the seasonal accent's, as a browser + * printing the page or a person asking for less motion sees them. jsdom always + * answers for a screen without a motion preference, so the queries about the + * other answer are asked the other way round. + */ +export function loadAccentStylesheet({ print = false, reducedMotion = false } = {}) { + let source = `${appStyles()}\n${readFileSync(resolve(process.cwd(), 'src/decor/decor.css'), 'utf8')}` + if (print) source = source.replace(/(?<=@media (?:not )?)screen/g, 'print') + if (reducedMotion) { + source = source.replace(/(?<=prefers-reduced-motion: )(?:no-preference|reduce)/g, (asked) => ( + asked === 'reduce' ? 'no-preference' : 'reduce' + )) + } + return appendStylesheet(source) +} + /** Applies one real media query's rules unconditionally in jsdom. */ export function loadRealMediaQuery(condition: string) { const source = appendStylesheet(appStyles()) diff --git a/frontend/src/theme.test.tsx b/frontend/src/theme.test.tsx index f1c90420..35ebbb69 100644 --- a/frontend/src/theme.test.tsx +++ b/frontend/src/theme.test.tsx @@ -81,6 +81,14 @@ describe('a blocked preference store', () => { expect(readDensity()).toBe('default') setThemeMode('light') expect(document.documentElement.getAttribute('data-theme')).toBe('light') + setDensity('compact') + expect(readDensity()).toBe('compact') + // Choosing one preference leaves the other as chosen. + expect(document.documentElement.getAttribute('data-theme')).toBe('light') + + vi.restoreAllMocks() + setThemeMode('dark') + setDensity('default') }) }) diff --git a/frontend/src/theme.ts b/frontend/src/theme.ts index 47e43ead..0afd8464 100644 --- a/frontend/src/theme.ts +++ b/frontend/src/theme.ts @@ -20,7 +20,12 @@ function notify() { for (const listener of listeners) listener() } +/** Choices the store refused to keep: each lives for this page only. */ +const unstored = new Map() + export function readStored(key: string): string | null { + const kept = unstored.get(key) + if (kept !== undefined) return kept try { return window.localStorage.getItem(key) } catch { @@ -31,8 +36,9 @@ export function readStored(key: string): string | null { export function writeStored(key: string, value: string) { try { window.localStorage.setItem(key, value) + unstored.delete(key) } catch { - // Private mode or a blocked store: the choice lives for this page only. + unstored.set(key, value) } } diff --git a/frontend/src/tokens.css b/frontend/src/tokens.css index 34bb5e64..00bf3846 100644 --- a/frontend/src/tokens.css +++ b/frontend/src/tokens.css @@ -84,7 +84,8 @@ /* The seasonal accent (src/decor): decoration only, never a state. Snow and the hat sit on the band, the rail or the mark, which keep their - colours in both schemes; what is drawn on the page follows the scheme. */ + colours in both schemes, and the garland under the band keeps its own; + the sky and the tree of the sign-in screen follow the scheme. */ --fx-snow: #FFFFFF; --fx-flake: rgba(255, 255, 255, 0.9); --fx-hat: #EB4C79; @@ -93,7 +94,8 @@ --fx-spark: #FFE6A8; --fx-dough: #E6A65C; --fx-heart: #FF8AAA; - --fx-wire: rgba(163, 181, 201, 0.55); + --fx-wire: #A3B5C9; + --fx-blue: #65B8FF; --shadow: 0 30px 60px -30px rgba(2, 8, 24, 0.8); --shadow-sm: 0 10px 30px -12px rgba(2, 8, 24, 0.7); @@ -153,7 +155,6 @@ --ev-teal: #036A6D; --fx-flake: #9DB3CC; --fx-gold: #9A6700; - --fx-wire: #A3B5C9; --shadow: 0 24px 48px -24px rgba(33, 65, 108, 0.35); --shadow-sm: 0 2px 8px rgba(33, 65, 108, 0.08); } From 58b47dcd4e50f72141fdef60d097dc2c445d7c88 Mon Sep 17 00:00:00 2001 From: lowicz Date: Wed, 2 Dec 2026 15:44:43 +0100 Subject: [PATCH 3/8] no-mistakes(test): restore hat hover nod and phone doughnut icing --- frontend/scripts/decor-load.test.mjs | 55 +++++++++++++++++++++++++ frontend/src/decor/decor.css | 9 +++- frontend/src/decor/decor.test.tsx | 61 +++++++++++++++++++++++++++- frontend/src/decor/index.tsx | 8 +++- frontend/src/test/stylesheet.ts | 7 +++- 5 files changed, 135 insertions(+), 5 deletions(-) create mode 100644 frontend/scripts/decor-load.test.mjs diff --git a/frontend/scripts/decor-load.test.mjs b/frontend/scripts/decor-load.test.mjs new file mode 100644 index 00000000..6f1d4713 --- /dev/null +++ b/frontend/scripts/decor-load.test.mjs @@ -0,0 +1,55 @@ +import { mkdtempSync, mkdirSync, rmSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' +import { afterAll, beforeAll, expect, it, vi } from 'vitest' +import { act, createElement } from 'react' +import { render } from '@testing-library/react' +import { build } from 'vite' + +// Only the production build waits for the stylesheet of a lazy chunk, so only +// there can that stylesheet fail (a release replaced it, the network dropped). +// The decorations are then missing; the interface around them must stay. +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') +let outDir + +beforeAll(async () => { + // Inside node_modules, where vitest runs a file exactly as it was built. + const cache = path.join(root, 'node_modules', '.cache') + mkdirSync(cache, { recursive: true }) + outDir = mkdtempSync(path.join(cache, 'decor-load-')) + await build({ + root, + logLevel: 'silent', + publicDir: false, + build: { + outDir, + rollupOptions: { + input: path.join(root, 'src/decor/index.tsx'), + preserveEntrySignatures: 'strict', + output: { entryFileNames: 'entry.mjs', chunkFileNames: '[name].mjs' }, + }, + }, + }) +}) + +afterAll(() => { + rmSync(outDir, { recursive: true, force: true }) +}) + +it('a decoration stylesheet that cannot be loaded leaves the plain interface', async () => { + const decor = await import(/* @vite-ignore */ pathToFileURL(path.join(outDir, 'entry.mjs')).href) + const { container } = render( + createElement('div', null, createElement('p', null, 'interface'), createElement(decor.StripDecor)), + ) + const stylesheet = await vi.waitFor(() => { + const link = document.head.querySelector('link[rel="stylesheet"]') + expect(link).not.toBeNull() + return link + }) + await act(async () => { + stylesheet.dispatchEvent(new Event('error')) + await new Promise((settled) => { setTimeout(settled, 100) }) + }) + + expect(container.innerHTML).toBe('

interface

') +}) diff --git a/frontend/src/decor/decor.css b/frontend/src/decor/decor.css index 403ad0a0..7dddc7d9 100644 --- a/frontend/src/decor/decor.css +++ b/frontend/src/decor/decor.css @@ -31,8 +31,9 @@ .fx-egg-a { stroke: var(--p-fill); } .fx-egg-b { stroke: var(--late-fill); } /* On a phone the mark is white on the action band, so what was drawn in - white or pale gold for the blue square takes the band's colour. */ - .mob-top .fx-sparkle, .mob-top .fx-egg ellipse { fill: var(--act); } + white or pale gold for the blue square (the sparkle, the doughnut's icing + and the egg's shell) takes the band's colour. */ + .mob-top :is(.fx-sparkle, .fx-icing, .fx-egg ellipse) { fill: var(--act); } .fx-flake { position: absolute; top: var(--y); left: var(--x); width: var(--s); height: var(--s); border-radius: 50%; background: var(--fx-snow); opacity: var(--o); } @@ -88,6 +89,9 @@ /* Everything that moves. Without motion the snow is a still scatter. */ @media screen and (prefers-reduced-motion: no-preference) { .fx-hat { animation: fx-nod 0.9s ease-in-out 0.4s 1; } + /* The load nod stays first in the list: were its name dropped here, it would + start again when the pointer leaves. */ + .brand:hover .fx-hat { animation: fx-nod 0.9s ease-in-out 0.4s 1, fx-nod-again 0.9s ease-in-out 1; } .fx-sparkle path { animation: fx-spark 1.2s ease-in-out 0.4s 1; } .fx-flake { top: -6px; animation: fx-fall var(--d) linear var(--dl) infinite, fx-sway var(--sd) ease-in-out var(--dl) infinite alternate; } @@ -112,6 +116,7 @@ .fx-rider g { animation: fx-bob 0.9s ease-in-out infinite; } @keyframes fx-nod { 0%, 100% { transform: rotate(0); } 25% { transform: rotate(-9deg); } 55% { transform: rotate(5deg); } 80% { transform: rotate(-2deg); } } + @keyframes fx-nod-again { 0%, 100% { transform: rotate(0); } 25% { transform: rotate(-9deg); } 55% { transform: rotate(5deg); } 80% { transform: rotate(-2deg); } } @keyframes fx-spark { 0%, 100% { transform: scale(1) rotate(0); } 40% { transform: scale(1.35) rotate(40deg); } 75% { transform: scale(0.9) rotate(80deg); } } @keyframes fx-fall { from { translate: 0 -10px; } to { translate: 0 calc(100cqh + 12px); } } @keyframes fx-sway { from { transform: translateX(calc(var(--sw) * -1)); } to { transform: translateX(var(--sw)); } } diff --git a/frontend/src/decor/decor.test.tsx b/frontend/src/decor/decor.test.tsx index 604b9869..f91c2fb4 100644 --- a/frontend/src/decor/decor.test.tsx +++ b/frontend/src/decor/decor.test.tsx @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { act, render, waitFor } from '@testing-library/react' import { applyAccent } from '../accent' -import { loadAccentStylesheet } from '../test/stylesheet' +import { HOVERED, loadAccentStylesheet } from '../test/stylesheet' import { Mark, RoleMark } from '../ui' import { LoginCap, LoginNight, ProgressRider, StripDecor } from '.' @@ -141,6 +141,21 @@ const moves = (element: Element) => { return !['', 'none'].includes(animationName) || !['', '0s'].includes(transitionDuration) } +const nods = (hat: Element) => getComputedStyle(hat).animationName.split(', ') + +/** The hat on the logo of the rail, with the pointer still elsewhere. */ +async function brandHat() { + act(() => applyAccent('winter')) + const { container } = render(
) + await waitFor(() => expect(container.querySelector('.fx-hat')).not.toBeNull()) + const brand = container.querySelector('.brand')! + return { + hat: container.querySelector('.fx-hat')!, + enter: () => brand.classList.add(HOVERED), + leave: () => brand.classList.remove(HOVERED), + } +} + describe('the accent as the stylesheet draws it', () => { it.each([ ['sparkle', '.fx-sparkle', { '.mark-dot': 'none', '.mark-line': 'inline' }], @@ -199,6 +214,50 @@ describe('the accent as the stylesheet draws it', () => { } }) + it('nods the hat once more when the pointer comes over the logo, and not when it leaves', async () => { + loadAccentStylesheet() + const { hat, enter, leave } = await brandHat() + const atRest = nods(hat) + expect(atRest).toHaveLength(1) + + for (let pass = 0; pass < 2; pass += 1) { + enter() + // A browser starts the animations whose names join the list, so hover + // adds exactly one, played once, while the one from the load stays: if + // it left the list it would start again when the pointer goes. + expect(nods(hat)).toHaveLength(2) + expect(nods(hat)[0]).toBe(atRest[0]) + expect(nods(hat)[1]).not.toBe(atRest[0]) + expect(getComputedStyle(hat).animationIterationCount.split(', ')).toEqual(['1', '1']) + + leave() + expect(nods(hat)).toEqual(atRest) + } + }) + + it('keeps the hat still under reduced motion when the pointer comes over the logo', async () => { + loadAccentStylesheet({ reducedMotion: true }) + const { hat, enter } = await brandHat() + + enter() + expect(moves(hat)).toBe(false) + }) + + it.each([ + ['sparkle', '.fx-sparkle'], + ['doughnut', '.fx-icing'], + ['egg', '.fx-egg ellipse'], + ])('draws the %s in the blue of the bar on the white mark of a phone', async (doodle, drawn) => { + loadAccentStylesheet() + act(() => applyAccent(doodle)) + const { container } = render(
) + await waitFor(() => expect(container.querySelector(drawn)).not.toBeNull()) + const fill = (selector: string) => getComputedStyle(container.querySelector(selector)!).fill + + expect(fill(drawn)).not.toBe(fill('.mark-box')) + expect(fill(drawn)).toBe(fill('.mark-dot')) + }) + it('stands still under reduced motion, the snow as a scatter of flakes', async () => { loadAccentStylesheet({ reducedMotion: true }) const container = await everyDrawing() diff --git a/frontend/src/decor/index.tsx b/frontend/src/decor/index.tsx index 194ebdc9..72717482 100644 --- a/frontend/src/decor/index.tsx +++ b/frontend/src/decor/index.tsx @@ -10,8 +10,14 @@ import { ComponentType, ReactNode, Suspense, lazy } from 'react' * of the application, so it never reshapes the bundles everybody downloads: * what a drawing needs from there, its caller hands in. */ + +// A function of its own on purpose: the production build wraps the import, +// with every `.then` chained straight onto it, in the loader of the chunk's +// stylesheet, so a handler written there would miss a stylesheet that fails. +const loadArt = () => import('./art') + function deferred

(pick: (art: typeof import('./art')) => ComponentType

) { - const Art = lazy>(() => import('./art').then( + const Art = lazy>(() => loadArt().then( (art) => ({ default: pick(art) }), () => ({ default: () => null }), )) diff --git a/frontend/src/test/stylesheet.ts b/frontend/src/test/stylesheet.ts index 6b6edc1b..c2e8f4d6 100644 --- a/frontend/src/test/stylesheet.ts +++ b/frontend/src/test/stylesheet.ts @@ -5,6 +5,9 @@ import { onTestFinished } from 'vitest' /** The safe-area inset the test stylesheet stands in for a phone's home bar or notch. */ export const SAFE_AREA_INSET = 34 +/** The class that stands in for `:hover` in `loadAccentStylesheet()`. */ +export const HOVERED = 'test-hovered' + function appStyles() { const source = ['src/tokens.css', 'src/styles.css'].map((file) => readFileSync(resolve(process.cwd(), file), 'utf8')).join('\n') return source.replace(/env\(safe-area-inset-(?:top|bottom)\)/g, `${SAFE_AREA_INSET}px`) @@ -33,10 +36,12 @@ export function loadRealStylesheet() { * Loads the app's stylesheet together with the seasonal accent's, as a browser * printing the page or a person asking for less motion sees them. jsdom always * answers for a screen without a motion preference, so the queries about the - * other answer are asked the other way round. + * other answer are asked the other way round. jsdom has no pointer either: + * an element under it carries the class `HOVERED`. */ export function loadAccentStylesheet({ print = false, reducedMotion = false } = {}) { let source = `${appStyles()}\n${readFileSync(resolve(process.cwd(), 'src/decor/decor.css'), 'utf8')}` + .replaceAll(':hover', `.${HOVERED}`) if (print) source = source.replace(/(?<=@media (?:not )?)screen/g, 'print') if (reducedMotion) { source = source.replace(/(?<=prefers-reduced-motion: )(?:no-preference|reduce)/g, (asked) => ( From fe9eea0f59485e3bb3da90e8520a7712d0778a02 Mon Sep 17 00:00:00 2001 From: lowicz Date: Wed, 2 Dec 2026 16:00:10 +0100 Subject: [PATCH 4/8] no-mistakes(document): correct seasonal accent design notes --- DESIGN.md | 12 +++++++----- frontend/src/components/AppShell.tsx | 5 +++-- frontend/src/decor/decor.css | 6 +++--- frontend/src/decor/index.tsx | 6 +++--- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 40652fe4..ebe12034 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -578,13 +578,15 @@ rail, the strip, the sign-in screen, a progress bar. It never draws on the duty matrix, never covers text or a control, and never borrows a role or state colour as a state. **The Decoration Only Rule.** Every drawing carries the class `fx`, is -`aria-hidden`, takes no pointer events and has its own `--fx-*` colours in -`tokens.css`. `decor.css` styles it on a screen only, so a printout, the +`aria-hidden`, takes no pointer events and takes its colours from +`tokens.css`: the accent's own `--fx-*` ones, and the palette where they +already match. `decor.css` styles it on a screen only, so a printout, the e-mails and the exports are the plain interface. **The Stillness Rule.** Nothing of it moves under `prefers-reduced-motion` -(the snow is a still scatter of flakes), and what moves without end (the snow and the lights of the strip) can be -turned off by each person in the account menu. The sign-in screen, which -has no such switch yet, stops moving by itself. +(the snow is a still scatter of flakes), and what moves without end (the +snow and the lights of the strip) can be turned off by each person in the +account menu. The sign-in screen, which has no such switch yet, stops moving +by itself. **The Insiders Rule.** A share-link session, opened by people outside the team, is never decorated. diff --git a/frontend/src/components/AppShell.tsx b/frontend/src/components/AppShell.tsx index f0b61320..9b4623d5 100644 --- a/frontend/src/components/AppShell.tsx +++ b/frontend/src/components/AppShell.tsx @@ -72,8 +72,9 @@ function RailLink({ path, label, icon, badge }: { path: string; label: string; i /** * The account menu behind the avatar: who is logged in, the theme, the - * matrix density and the language as radio groups (Base UI keeps the menu open while they - * change), the seasonal decorations on the days there are any, the documentation, the palette and the way out. The release + * matrix density, the language and, on the days there are any, the seasonal + * decorations as radio groups (Base UI keeps the menu open while they change), + * the documentation, the palette and the way out. The release * running closes the menu as a dim footer: this menu is the one place every * layout has (a phone, the collapsed rail, a share-link session), so it is * where the version can always be found. The avatar is the person's photo diff --git a/frontend/src/decor/decor.css b/frontend/src/decor/decor.css index 7dddc7d9..7a03c455 100644 --- a/frontend/src/decor/decor.css +++ b/frontend/src/decor/decor.css @@ -1,9 +1,9 @@ /* The seasonal accent (src/accent.ts, drawn by ./art.tsx). It is decoration * only and stays out of the way: every rule here applies on a screen and * nowhere else, so a printout is the plain interface; nothing takes a click; - * nothing moves unless the person allows motion. Colours are the --fx-* - * tokens. Loaded with the chunk that draws it, so a deployment that set no - * ONCALL_ACCENT never downloads it. */ + * nothing moves unless the person allows motion. Colours come from + * tokens.css, most of them its --fx-* ones. Loaded with the chunk that draws + * it, so a deployment that set no ONCALL_ACCENT never downloads it. */ @media not screen { .fx { display: none; } } diff --git a/frontend/src/decor/index.tsx b/frontend/src/decor/index.tsx index 72717482..1946648a 100644 --- a/frontend/src/decor/index.tsx +++ b/frontend/src/decor/index.tsx @@ -6,9 +6,9 @@ import { ComponentType, ReactNode, Suspense, lazy } from 'react' * ONCALL_ACCENT ever downloads; each of these mounts one drawing and renders * nothing until the chunk has arrived, or for good if it cannot be loaded. * A screen mounts them only while `useAccent()` names the accent they belong - * to. The chunk imports nothing - * of the application, so it never reshapes the bundles everybody downloads: - * what a drawing needs from there, its caller hands in. + * to. The chunk imports nothing of the application, so it never reshapes the + * bundles everybody downloads: what a drawing needs from there, its caller + * hands in. */ // A function of its own on purpose: the production build wraps the import, From ccf04d5513eb70daa4a05527188d43f6de0a7a6f Mon Sep 17 00:00:00 2001 From: lowicz Date: Wed, 2 Dec 2026 16:35:55 +0100 Subject: [PATCH 5/8] fix(accent): clear the SonarCloud findings on the seasonal decorations Seven open issues on the pull request, fixed in the code with no change in behaviour: - config.py: the MM-DD shape is `\d{2}-\d{2}` under re.ASCII, which is exactly what `[0-9]{2}-[0-9]{2}` matched (S6353, twice). - art.tsx: the seeded sequence keeps its state unsigned (`>>> 0`) instead of signed (`| 0`). The state is only ever read through 32-bit operators, so the bits and the numbers drawn are the same (S7767). - art.tsx: the garland wire is joined from its parts instead of nesting one template literal in another (S4624). - art.tsx: the tree's lights are worked out once, each named by the moment it comes on, so a light and a row have a key of their own instead of an array index, and rendering no longer counts as it goes (S6479). - art.tsx: the props of LoginNight and ProgressRider are read-only (S6759). The markup the decorations render is byte for byte what it was, and the sequence is identical over two million draws from ten seeds. --- backend/src/oncall/config.py | 2 +- frontend/src/decor/art.tsx | 24 +++++++++++++----------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/backend/src/oncall/config.py b/backend/src/oncall/config.py index fc92468c..d37bfc97 100644 --- a/backend/src/oncall/config.py +++ b/backend/src/oncall/config.py @@ -286,7 +286,7 @@ def _accent_bound_is_a_day_of_the_year(cls, value: str) -> str: if not value.strip(): return "" try: - if not re.fullmatch("[0-9]{2}-[0-9]{2}", value): + if not re.fullmatch(r"\d{2}-\d{2}", value, re.ASCII): raise ValueError date.fromisoformat(f"2000-{value}") except ValueError: diff --git a/frontend/src/decor/art.tsx b/frontend/src/decor/art.tsx index dfcf5cd9..59a0afdf 100644 --- a/frontend/src/decor/art.tsx +++ b/frontend/src/decor/art.tsx @@ -13,7 +13,7 @@ import './decor.css' function sequence(seed: number) { let state = seed return () => { - state = (state + 0x6d2b79f5) | 0 + state = (state + 0x6d2b79f5) >>> 0 let mixed = Math.imul(state ^ (state >>> 15), 1 | state) mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296 @@ -113,7 +113,7 @@ const STRIP_SNOW = flakes(34, 6, [2, 4.2], [4.5, 8]) const BULBS = Array.from({ length: 24 }, (_, index) => index) /** One shallow scallop of wire per bulb, in a box as many units wide as * there are bulbs and stretched to the strip's width. */ -const WIRE = `M0 1${BULBS.map((index) => `Q${index + 0.5} 15 ${index + 1} 1`).join('')}` +const WIRE = ['M0 1', ...BULBS.map((index) => `Q${index + 0.5} 15 ${index + 1} 1`)].join('') export function StripDecor() { return ( @@ -130,27 +130,29 @@ export function StripDecor() { const NIGHT_STARS = stars(26, 9) const NIGHT_SNOW = flakes(30, 19, [2, 4.5], [8, 12]) const TREE_STAR = 'M5 .6 6.12 3.76 9.47 3.85 6.81 5.89 7.76 9.1 5 7.2 2.24 9.1 3.19 5.89 .53 3.85 3.88 3.76Z' -/** The tree, row by row, in the role marks of the schedule. */ -const TREE: AssignmentRole[][] = [ +const TREE_ROLES: AssignmentRole[][] = [ ['primary'], ['secondary', 'primary'], ['late_shift', 'secondary', 'primary'], ['primary', 'late_shift', 'secondary', 'primary'], ['secondary', 'primary', 'secondary', 'late_shift', 'primary'], ] +let lit = 0 +/** The tree, row by row, in the role marks of the schedule. Each light comes + * on a moment after the one before it, top to bottom, and that moment names it. */ +const TREE = TREE_ROLES.map((row) => row.map((role) => ({ role, delay: `${(0.4 + 0.18 * lit++).toFixed(2)}s` }))) /** `mark` draws one role mark of the schedule, the tree's only ornament. */ -export function LoginNight({ mark }: { mark: (role: AssignmentRole) => ReactNode }) { - let lit = 0 +export function LoginNight({ mark }: Readonly<{ mark: (role: AssignmentRole) => ReactNode }>) { return (