Clock: a "Delphin Uhr" overlay with the school bus and a parents' timer
Einfg on the kiosk keyboard, or Guide (KEY_EPG) on the IR remote, shows a big analog watch over whatever page is open, built from the Delphin Uhr mockup without its swimming dolphin. The overlay stays mounted and is only hidden, so it appears at once. Beside the watch, only while they run: - The bus: on school days, a silent countdown to `general.clock.bus_time` (07:25) that starts `bus_lead_minutes` (60) before. School days skip weekends and the school and public holidays of `general.clock.subdivision` (DE-BY), fetched daily from openholidaysapi.org and cached under the library cache. A badge on the clock says whether there is school today, and why not. - The dolphin timer, set in parent mode (5/10/15/30 minutes, or until a time). It lives in the backend, so a parent's phone can start it for the kiosk. When it runs out the kiosk opens the clock at 00:00 and a soft bell chimes on the device; it clears after a minute, or at the next key, tap or remote press. Parent mode is now a way in rather than a page: `?parentMode=1` adds a 🔧 button next to the ⌨ one, or an "Eltern" tab in the phone's dock, so the URL can stay bookmarked. The timer comes first there, the device settings below it. Unmapped IR buttons are logged at debug level, to find out what irserver calls a new one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -212,8 +212,8 @@ copied to the device.
|
||||
| `GET /api/library` | Every album with its tracks and colours. ~90 kB, sent once. |
|
||||
| `GET /api/albums/{id}/cover` | The cover, or 404 - the client paints the album's colours instead. |
|
||||
| `POST /api/library/refresh` | Rescan in the background; connected clients are told when it lands. |
|
||||
| `GET /api/state` | Snapshot: what is playing, where, how loud. |
|
||||
| `WS /api/ws` | Push only. A snapshot on connect, then a frame per change, plus the position at 2 Hz while playing. |
|
||||
| `GET /api/state` | Snapshot: what is playing, where, how loud; plus `clock` - today's school day, the bus, the parents' timer. |
|
||||
| `WS /api/ws` | Push only. A snapshot on connect, then a frame per change, plus the position at 2 Hz while playing, and `clock_toggle` when the remote's Guide key asks for the clock. |
|
||||
| `POST /api/play` | `{album_id, track_index?}` |
|
||||
| `POST /api/resume` `/pause` `/next` `/previous` `/seek` | transport |
|
||||
| `POST /api/volume` | `{percent}`, `{delta_percent}`, or `{steps}` - the IR remote's step (`volume_increment` device units) per step |
|
||||
@@ -221,6 +221,7 @@ copied to the device.
|
||||
| `GET` `PUT /api/remote/mapping` | number key -> album (optionally from one `track_index`) or podcast show |
|
||||
| `POST /api/screen/toggle` `/screen/activity` | the kiosk's Del key; its key presses and taps, holding off the idle screen-off |
|
||||
| `GET` `PUT /api/settings` | parent mode |
|
||||
| `POST` `DELETE /api/timer` | parent mode's countdown: `{minutes}` or `{until: "HH:MM"}`; stop or silence it |
|
||||
|
||||
Two decisions worth knowing:
|
||||
|
||||
|
||||
@@ -88,7 +88,9 @@ general:
|
||||
# IR remote control, over lircd's TCP socket (see ansible/roles/pi_lirc for how
|
||||
# lircd itself is set up on the Pi). Omit the whole section to run without a remote.
|
||||
# Play/pause/stop/previous/forward/rewind/volume/mute map to normal music control;
|
||||
# number keys 0-9 play whatever the "remote:" section below assigns them.
|
||||
# number keys 0-9 play whatever the "remote:" section below assigns them; Guide
|
||||
# (KEY_EPG) shows the kiosk's clock. Run with --log-level DEBUG to see the name of a
|
||||
# button that does nothing.
|
||||
lirc:
|
||||
host: "musicmouse-pi.local"
|
||||
port: 2222 # this deployment's lircd listens on 2222, not its own
|
||||
@@ -112,6 +114,16 @@ general:
|
||||
# auto_off_minutes: 15
|
||||
# timeout: 5.0 # seconds before a hung command is killed
|
||||
|
||||
# The clock overlay (Einfg on the kiosk keyboard, Guide on the remote). Optional; these
|
||||
# are the defaults. On school days a bus countdown shows for bus_lead_minutes before
|
||||
# bus_time. School days skip weekends and the school and public holidays of
|
||||
# `subdivision`, fetched daily from openholidaysapi.org and cached under
|
||||
# library.cache - a city code such as DE-BY-AU adds that city's own holidays.
|
||||
# clock:
|
||||
# subdivision: "DE-BY"
|
||||
# bus_time: "07:25"
|
||||
# bus_lead_minutes: 60
|
||||
|
||||
# Home Assistant integration. Omit the whole section to run without MQTT.
|
||||
# The backend exposes three lights, a player sensor, a volume slider, transport
|
||||
# buttons, device triggers for every button/touch area, and a tag scanner.
|
||||
|
||||
@@ -40,6 +40,7 @@ from musicmouse.services.lirc import LircService
|
||||
from musicmouse.services.mqtt import MqttService, build_entities
|
||||
from musicmouse.services.podcasts import PodcastFeedService
|
||||
from musicmouse.services.screen import ScreenService
|
||||
from musicmouse.services.timers import TimerService
|
||||
from musicmouse.services.web import WebService
|
||||
from musicmouse.tippen.curriculum import CurriculumError
|
||||
from musicmouse.tippen.runtime import TippenRuntime, build_tippen_runtime
|
||||
@@ -386,6 +387,22 @@ def _build_services(
|
||||
)
|
||||
)
|
||||
|
||||
# Unconditional, like the overlay it serves: the bus timer and the school-day badge
|
||||
# need nothing configured, and the parents' timer is only started from parent mode.
|
||||
general = app.config.general
|
||||
services.append(
|
||||
TimerService(
|
||||
app.bus,
|
||||
app.state,
|
||||
general.clock,
|
||||
cache_file=general.library.cache / "holidays.json",
|
||||
client=httpx2.AsyncClient(timeout=30.0),
|
||||
alsa_device=None if general.audio_simulated else general.alsa_device,
|
||||
volume=lambda: app.player.volume / 100,
|
||||
clock=clock,
|
||||
)
|
||||
)
|
||||
|
||||
# Unconditional: a show only starts downloading once someone drops a `feed.txt`
|
||||
# into its folder, so there is nothing to gate here with its own config section.
|
||||
web_service = _service_of_type(services, WebService)
|
||||
|
||||
@@ -18,7 +18,18 @@ from musicmouse.tippen.runtime import TippenRuntime
|
||||
|
||||
_log = logging.getLogger(__name__)
|
||||
|
||||
__all__ = ["App", "AppState"]
|
||||
__all__ = ["App", "AppState", "ParentTimer"]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ParentTimer:
|
||||
"""The countdown parents start from parent mode. Wall-clock Unix seconds, so every
|
||||
browser can draw it against its own clock."""
|
||||
|
||||
started_at: float
|
||||
ends_at: float
|
||||
#: Ran out and is chiming; cleared after a minute or by the next thing anyone does.
|
||||
ringing: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -36,6 +47,14 @@ class AppState:
|
||||
#: Whether the lircd TCP link for the IR remote is currently reachable.
|
||||
lirc_connected: bool = False
|
||||
|
||||
#: Owned by :class:`~musicmouse.services.timers.TimerService`.
|
||||
parent_timer: ParentTimer | None = None
|
||||
#: Whether today is a school day; ``None`` on a weekday the holiday calendar could
|
||||
#: not be fetched for (no internet, no cache yet).
|
||||
school_day: bool | None = None
|
||||
#: Why not, when it is not: ``"Wochenende"``, ``"Herbstferien"``, ...
|
||||
school_day_reason: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class App:
|
||||
|
||||
@@ -7,6 +7,9 @@ player's volume instead of being fixed in a recording.
|
||||
A bubble is a sine whose pitch rises as it decays (an air bubble's resonance climbs as
|
||||
it reaches the surface). Two of them make the "blubb"; switching on the second one is
|
||||
higher, switching off it is lower, so the two directions are told apart by ear.
|
||||
|
||||
The parents' timer has its own sound here too: a soft "ding-dong" bell
|
||||
(:func:`chime_wav`), made the same way.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,7 +19,7 @@ import math
|
||||
import wave
|
||||
from array import array
|
||||
|
||||
__all__ = ["RATE", "blubb_wav"]
|
||||
__all__ = ["RATE", "blubb_wav", "chime_wav"]
|
||||
|
||||
RATE = 44100
|
||||
|
||||
@@ -35,6 +38,29 @@ def blubb_wav(*, on: bool, gain: float) -> bytes:
|
||||
|
||||
peak = max(abs(s) for s in samples) or 1.0
|
||||
scale = 32767 * max(0.0, min(1.0, gain)) / peak
|
||||
return _wav(samples, scale)
|
||||
|
||||
|
||||
#: (Hz, start s) of each bell strike: a falling major third, "ding-dong".
|
||||
_CHIME = ((1318.5, 0.0), (1046.5, 0.45))
|
||||
|
||||
#: How long each strike rings out.
|
||||
_CHIME_DECAY = 1.6
|
||||
|
||||
|
||||
def chime_wav(*, gain: float) -> bytes:
|
||||
"""A soft two-note bell for the parents' timer running out. Same format as
|
||||
:func:`blubb_wav`."""
|
||||
length = max(start for _, start in _CHIME) + _CHIME_DECAY
|
||||
samples = [0.0] * (int(length * RATE) + 1)
|
||||
for frequency, start in _CHIME:
|
||||
_add_strike(samples, frequency, int(start * RATE))
|
||||
peak = max(abs(s) for s in samples) or 1.0
|
||||
scale = 32767 * max(0.0, min(1.0, gain)) / peak
|
||||
return _wav(samples, scale)
|
||||
|
||||
|
||||
def _wav(samples: list[float], scale: float) -> bytes:
|
||||
pcm = array("h", (round(s * scale) for s in samples))
|
||||
buffer = io.BytesIO()
|
||||
with wave.open(buffer, "wb") as out:
|
||||
@@ -60,3 +86,19 @@ def _add_bubble(
|
||||
index = offset + i
|
||||
if index < len(samples):
|
||||
samples[index] += math.sin(phase) * envelope
|
||||
|
||||
|
||||
def _add_strike(samples: list[float], frequency: float, offset: int) -> None:
|
||||
"""A bell: the fundamental plus two quieter, faster-fading overtones."""
|
||||
count = int(_CHIME_DECAY * RATE)
|
||||
attack = int(0.006 * RATE)
|
||||
partials = ((1.0, 1.0, 3.0), (2.0, 0.35, 5.0), (3.0, 0.12, 8.0)) # ratio, level, decay
|
||||
for i in range(count):
|
||||
t = i / RATE
|
||||
value = sum(
|
||||
level * math.exp(-decay * t) * math.sin(2 * math.pi * frequency * ratio * t)
|
||||
for ratio, level, decay in partials
|
||||
)
|
||||
index = offset + i
|
||||
if index < len(samples):
|
||||
samples[index] += value * min(1.0, i / attack)
|
||||
|
||||
@@ -32,6 +32,7 @@ _log = logging.getLogger(__name__)
|
||||
|
||||
__all__ = [
|
||||
"SIMULATE",
|
||||
"ClockConfig",
|
||||
"Config",
|
||||
"ConfigError",
|
||||
"Digit",
|
||||
@@ -184,6 +185,22 @@ class ScreenConfig(_Strict):
|
||||
timeout: float = Field(default=5.0, gt=0)
|
||||
|
||||
|
||||
class ClockConfig(_Strict):
|
||||
"""The clock overlay's automatic bus countdown, and whose school days it follows.
|
||||
|
||||
Always present: leave the section out for a Bavarian school bus at 7:25.
|
||||
"""
|
||||
|
||||
#: ISO 3166-2 code the school and public holidays are looked up for, as the
|
||||
#: OpenHolidays API knows it. A city-level code (``DE-BY-AU``) also counts that
|
||||
#: city's own holidays; the state's are always included.
|
||||
subdivision: str = Field(default="DE-BY", pattern=r"^[A-Z]{2}-[A-Z0-9]+(-[A-Z0-9]+)?$")
|
||||
#: When the bus leaves, on school days only.
|
||||
bus_time: str = Field(default="07:25", pattern=r"^([01][0-9]|2[0-3]):[0-5][0-9]$")
|
||||
#: How long before ``bus_time`` the countdown appears.
|
||||
bus_lead_minutes: int = Field(default=60, ge=1, le=240)
|
||||
|
||||
|
||||
class LibraryConfig(_Strict):
|
||||
"""Where the music lives.
|
||||
|
||||
@@ -303,6 +320,7 @@ class GeneralConfig(_Strict):
|
||||
lirc: LircConfig | None = None
|
||||
screen: ScreenConfig | None = None
|
||||
tippen: TippenConfig | None = None
|
||||
clock: ClockConfig = Field(default_factory=ClockConfig)
|
||||
|
||||
min_volume: int = Field(default=0, ge=0, le=200)
|
||||
max_volume: int = Field(default=100, ge=0, le=200)
|
||||
|
||||
@@ -27,6 +27,8 @@ if TYPE_CHECKING:
|
||||
__all__ = [
|
||||
"ActiveFigureChanged",
|
||||
"ButtonEvent",
|
||||
"CancelTimerRequested",
|
||||
"ClockStateChanged",
|
||||
"ConnectionChanged",
|
||||
"DeviceConnected",
|
||||
"DeviceDisconnected",
|
||||
@@ -48,8 +50,10 @@ __all__ = [
|
||||
"PreviousTrackRequested",
|
||||
"RfidTokenRead",
|
||||
"RotaryTurned",
|
||||
"SetTimerRequested",
|
||||
"SetVolumeRequested",
|
||||
"StateEvent",
|
||||
"ToggleClockRequested",
|
||||
"ToggleScreenRequested",
|
||||
"TouchButtonPressed",
|
||||
"TouchButtonReleased",
|
||||
@@ -235,6 +239,25 @@ class ToggleScreenRequested(IntentEvent):
|
||||
"""Switch the attached monitor off if it is on, on if it is off (``general.screen``)."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ToggleClockRequested(IntentEvent):
|
||||
"""Show or hide the clock overlay. Only the kiosk acts on it - the overlay is a
|
||||
front-end thing, the backend just passes the remote's key along."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SetTimerRequested(IntentEvent):
|
||||
"""Start the parents' countdown, replacing one already running."""
|
||||
|
||||
#: Wall-clock end, as Unix seconds.
|
||||
ends_at: float
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class CancelTimerRequested(IntentEvent):
|
||||
"""Stop the parents' countdown, or silence it if it is ringing."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class UserActivity(IntentEvent):
|
||||
"""Someone is at the device - a key press or tap in the kiosk browser. Requests
|
||||
@@ -294,6 +317,12 @@ class LedEffectChanged(StateEvent):
|
||||
return f"LedEffectChanged({self.zone}, {self.effect}, origin={self.origin})"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ClockStateChanged(StateEvent):
|
||||
"""The parents' timer started, rang or stopped, or today's school day changed.
|
||||
The values themselves live on :class:`~musicmouse.app.AppState`."""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ConnectionChanged(StateEvent):
|
||||
target: Literal["firmware", "mqtt", "lirc"]
|
||||
|
||||
175
python-backend/musicmouse/school_days.py
Normal file
175
python-backend/musicmouse/school_days.py
Normal file
@@ -0,0 +1,175 @@
|
||||
"""Whether today is a school day: weekends, public holidays and school holidays.
|
||||
|
||||
The holidays come from the OpenHolidays API (https://openholidaysapi.org), which has
|
||||
both kinds per German state - Bavaria's ``DE-BY`` school holidays include the
|
||||
Buß- und Bettag, which is a school day off but not a public holiday. Public holidays
|
||||
carry their subdivisions, so a city-only one like Augsburg's Friedensfest
|
||||
(``DE-BY-AU``) counts for Augsburg and not for the rest of Bavaria.
|
||||
|
||||
Fetched once a day and kept in a JSON file, so a device that loses its internet keeps
|
||||
knowing the holidays for the rest of the school year.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx2
|
||||
|
||||
_log = logging.getLogger(__name__)
|
||||
|
||||
__all__ = [
|
||||
"API_URL",
|
||||
"Holiday",
|
||||
"HolidayCalendar",
|
||||
"fetch_calendar",
|
||||
"load_calendar",
|
||||
"parse_holidays",
|
||||
"save_calendar",
|
||||
"school_day",
|
||||
]
|
||||
|
||||
API_URL = "https://openholidaysapi.org"
|
||||
|
||||
#: How far back and ahead each fetch reaches. Ahead covers a whole school year from
|
||||
#: any date, so the cache outlives a long outage.
|
||||
_FETCH_BEFORE = timedelta(days=30)
|
||||
_FETCH_AHEAD = timedelta(days=400)
|
||||
|
||||
_WEEKEND = "Wochenende"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Holiday:
|
||||
start: date
|
||||
end: date
|
||||
name: str
|
||||
nationwide: bool
|
||||
subdivisions: tuple[str, ...]
|
||||
|
||||
def covers(self, day: date) -> bool:
|
||||
return self.start <= day <= self.end
|
||||
|
||||
def applies_to(self, subdivision: str) -> bool:
|
||||
"""``DE-BY-AU`` gets ``DE-BY``'s holidays as well as its own; ``DE-BY`` does
|
||||
not get ``DE-BY-AU``'s."""
|
||||
return self.nationwide or any(
|
||||
subdivision == code or subdivision.startswith(code + "-") for code in self.subdivisions
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class HolidayCalendar:
|
||||
#: The day it was fetched, to know when to fetch again.
|
||||
fetched: date
|
||||
subdivision: str
|
||||
school: tuple[Holiday, ...]
|
||||
public: tuple[Holiday, ...]
|
||||
|
||||
|
||||
def parse_holidays(raw: list[dict[str, Any]]) -> tuple[Holiday, ...]:
|
||||
"""The API's JSON list, either endpoint. Entries that do not parse are skipped."""
|
||||
holidays = []
|
||||
for entry in raw:
|
||||
try:
|
||||
names = entry.get("name") or []
|
||||
name = next(
|
||||
(n["text"] for n in names if n.get("language") == "DE"),
|
||||
names[0]["text"] if names else "Feiertag",
|
||||
)
|
||||
holidays.append(
|
||||
Holiday(
|
||||
start=date.fromisoformat(entry["startDate"]),
|
||||
end=date.fromisoformat(entry["endDate"]),
|
||||
name=name,
|
||||
nationwide=bool(entry.get("nationwide")),
|
||||
subdivisions=tuple(s["code"] for s in entry.get("subdivisions") or []),
|
||||
)
|
||||
)
|
||||
except (KeyError, TypeError, ValueError, IndexError):
|
||||
_log.debug("Skipping a holiday entry that does not parse: %r", entry)
|
||||
return tuple(holidays)
|
||||
|
||||
|
||||
def school_day(day: date, calendar: HolidayCalendar | None) -> tuple[bool | None, str | None]:
|
||||
"""``(is_school_day, why_not)``. ``None`` when there is no calendar to ask -
|
||||
the weekend is still known then, a holiday is not."""
|
||||
if day.weekday() >= 5:
|
||||
return False, _WEEKEND
|
||||
if calendar is None:
|
||||
return None, None
|
||||
for holiday in (*calendar.public, *calendar.school):
|
||||
if holiday.covers(day) and holiday.applies_to(calendar.subdivision):
|
||||
return False, holiday.name
|
||||
return True, None
|
||||
|
||||
|
||||
async def fetch_calendar(
|
||||
client: httpx2.AsyncClient, subdivision: str, today: date
|
||||
) -> HolidayCalendar:
|
||||
"""Both lists for ``subdivision``'s state. Raises on any network or HTTP error."""
|
||||
# The API files school holidays under the state; city-level ones are filtered here.
|
||||
state = "-".join(subdivision.split("-")[:2])
|
||||
params = {
|
||||
"countryIsoCode": state.split("-")[0],
|
||||
"subdivisionCode": state,
|
||||
"languageIsoCode": "DE",
|
||||
"validFrom": (today - _FETCH_BEFORE).isoformat(),
|
||||
"validTo": (today + _FETCH_AHEAD).isoformat(),
|
||||
}
|
||||
lists = []
|
||||
for endpoint in ("SchoolHolidays", "PublicHolidays"):
|
||||
response = await client.get(f"{API_URL}/{endpoint}", params=params)
|
||||
response.raise_for_status()
|
||||
lists.append(parse_holidays(response.json()))
|
||||
school, public = lists
|
||||
return HolidayCalendar(fetched=today, subdivision=subdivision, school=school, public=public)
|
||||
|
||||
|
||||
def save_calendar(path: Path, calendar: HolidayCalendar) -> None:
|
||||
def dump(holidays: tuple[Holiday, ...]) -> list[dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
"startDate": h.start.isoformat(),
|
||||
"endDate": h.end.isoformat(),
|
||||
"name": [{"language": "DE", "text": h.name}],
|
||||
"nationwide": h.nationwide,
|
||||
"subdivisions": [{"code": code} for code in h.subdivisions],
|
||||
}
|
||||
for h in holidays
|
||||
]
|
||||
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = {
|
||||
"fetched": calendar.fetched.isoformat(),
|
||||
"subdivision": calendar.subdivision,
|
||||
"school": dump(calendar.school),
|
||||
"public": dump(calendar.public),
|
||||
}
|
||||
temporary = path.with_suffix(".tmp")
|
||||
temporary.write_text(json.dumps(payload), encoding="utf-8")
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def load_calendar(path: Path, subdivision: str) -> HolidayCalendar | None:
|
||||
"""The cached calendar, or ``None`` if there is none for this subdivision."""
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
if payload["subdivision"] != subdivision:
|
||||
return None
|
||||
return HolidayCalendar(
|
||||
fetched=date.fromisoformat(payload["fetched"]),
|
||||
subdivision=subdivision,
|
||||
school=parse_holidays(payload["school"]),
|
||||
public=parse_holidays(payload["public"]),
|
||||
)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except (OSError, KeyError, TypeError, ValueError):
|
||||
_log.warning("Ignoring an unreadable holiday cache at %s", path)
|
||||
return None
|
||||
@@ -25,6 +25,7 @@ from musicmouse.events import (
|
||||
PlayRequested,
|
||||
PreviousTrackRequested,
|
||||
SetVolumeRequested,
|
||||
ToggleClockRequested,
|
||||
ToggleScreenRequested,
|
||||
VolumeChangeRequested,
|
||||
)
|
||||
@@ -46,6 +47,8 @@ _TRANSPORT: dict[str, Callable[[], IntentEvent]] = {
|
||||
"KEY_FORWARD": lambda: NextTrackRequested(source="lirc"),
|
||||
# Does nothing unless general.screen is configured - see ScreenService.
|
||||
"KEY_POWER": lambda: ToggleScreenRequested(source="lirc"),
|
||||
# "Guide": what time is it. Shows the kiosk's clock overlay.
|
||||
"KEY_EPG": lambda: ToggleClockRequested(source="lirc"),
|
||||
}
|
||||
|
||||
#: Acted on every repeat, for a continuous ramp while held - same feel as the rotary
|
||||
@@ -142,8 +145,13 @@ class LircService:
|
||||
elif event.button == "KEY_MUTE":
|
||||
if event.repeat == 0:
|
||||
self._toggle_mute()
|
||||
elif (digit := _DIGITS.get(event.button)) is not None and event.repeat == 0:
|
||||
elif (digit := _DIGITS.get(event.button)) is not None:
|
||||
if event.repeat == 0:
|
||||
self._play_digit(digit)
|
||||
elif event.repeat == 0:
|
||||
# irserver's names do not always match lircd's; this is how to find out
|
||||
# what a new button is called on the device.
|
||||
_log.debug("Unmapped IR button %s", event.button)
|
||||
|
||||
def _toggle_mute(self) -> None:
|
||||
player = self.app.player
|
||||
|
||||
227
python-backend/musicmouse/services/timers.py
Normal file
227
python-backend/musicmouse/services/timers.py
Normal file
@@ -0,0 +1,227 @@
|
||||
"""The clock overlay's backend half: the parents' countdown and today's school day.
|
||||
|
||||
The overlay itself lives in the kiosk browser. What has to live here is what several
|
||||
screens share (a timer set from a parent's phone shows on the kiosk), what has to keep
|
||||
going with the screen off (the chime), and what needs the internet (the holidays).
|
||||
|
||||
The countdown runs on the injected :class:`~musicmouse.clock.Clock` like everything
|
||||
else that waits; wall time comes from ``wall`` so a test can pin the date.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from collections.abc import Callable
|
||||
from datetime import date, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import httpx2
|
||||
|
||||
from musicmouse.app import AppState, ParentTimer
|
||||
from musicmouse.blubb import chime_wav
|
||||
from musicmouse.bus import EventBus
|
||||
from musicmouse.clock import Clock, RealClock
|
||||
from musicmouse.config import ClockConfig
|
||||
from musicmouse.events import (
|
||||
CancelTimerRequested,
|
||||
ClockStateChanged,
|
||||
Event,
|
||||
IntentEvent,
|
||||
LedEffectRequested,
|
||||
SetTimerRequested,
|
||||
)
|
||||
from musicmouse.school_days import (
|
||||
HolidayCalendar,
|
||||
fetch_calendar,
|
||||
load_calendar,
|
||||
save_calendar,
|
||||
school_day,
|
||||
)
|
||||
from musicmouse.sound import play_wav
|
||||
|
||||
_log = logging.getLogger(__name__)
|
||||
|
||||
__all__ = ["RING_SECONDS", "TimerService", "timer_end"]
|
||||
|
||||
#: How long a timer that ran out keeps showing 00:00 before it clears by itself.
|
||||
RING_SECONDS = 60.0
|
||||
|
||||
#: The chime's peak at full player volume, as a fraction of full scale - soft.
|
||||
_CHIME_GAIN = 0.3
|
||||
#: Never quieter than at this player volume: a muted player must not mute the timer.
|
||||
_CHIME_MIN_VOLUME = 0.3
|
||||
|
||||
#: After a failed holiday fetch, try again this much later rather than at midnight.
|
||||
_RETRY_SECONDS = 3600.0
|
||||
#: Wake this long after midnight, so the new day has surely begun.
|
||||
_AFTER_MIDNIGHT = 5.0
|
||||
|
||||
|
||||
def timer_end(now: datetime, *, minutes: int | None = None, until: str | None = None) -> datetime:
|
||||
"""When a timer started at ``now`` ends: ``minutes`` from now, or at the next
|
||||
``until`` ("HH:MM") - tomorrow if that time has already passed today."""
|
||||
if (minutes is None) == (until is None):
|
||||
raise ValueError("give exactly one of minutes and until")
|
||||
if minutes is not None:
|
||||
return now + timedelta(minutes=minutes)
|
||||
assert until is not None
|
||||
hour, minute = (int(part) for part in until.split(":"))
|
||||
end = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
|
||||
return end if end > now else end + timedelta(days=1)
|
||||
|
||||
|
||||
class TimerService:
|
||||
name = "timers"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
bus: EventBus,
|
||||
state: AppState,
|
||||
config: ClockConfig,
|
||||
*,
|
||||
cache_file: Path,
|
||||
client: httpx2.AsyncClient,
|
||||
alsa_device: str | None,
|
||||
volume: Callable[[], float],
|
||||
clock: Clock | None = None,
|
||||
wall: Callable[[], datetime] = datetime.now,
|
||||
) -> None:
|
||||
self.bus = bus
|
||||
self.state = state
|
||||
self.config = config
|
||||
self.cache_file = cache_file
|
||||
self.client = client
|
||||
#: Where the chime plays, or ``None`` for no sound (simulated audio).
|
||||
self.alsa_device = alsa_device
|
||||
#: The player's volume as a fraction, read when the chime plays.
|
||||
self.volume = volume
|
||||
self._clock = clock or RealClock()
|
||||
self._wall = wall
|
||||
self._calendar: HolidayCalendar | None = None
|
||||
self._countdown: asyncio.Task[None] | None = None
|
||||
self._chime_task: asyncio.Task[None] | None = None
|
||||
|
||||
# ------------------------------------------------------------------ lifecycle
|
||||
|
||||
async def run(self) -> None:
|
||||
unsubscribe = [
|
||||
self.bus.subscribe(SetTimerRequested, self._on_set),
|
||||
self.bus.subscribe(CancelTimerRequested, self._on_cancel),
|
||||
self.bus.subscribe_all(self._on_event),
|
||||
]
|
||||
try:
|
||||
while True:
|
||||
fetched = await self.refresh_school_day()
|
||||
await self._clock.sleep(self._seconds_to_midnight() if fetched else _RETRY_SECONDS)
|
||||
finally:
|
||||
for undo in unsubscribe:
|
||||
undo()
|
||||
if self._countdown is not None:
|
||||
self._countdown.cancel()
|
||||
await self.client.aclose()
|
||||
|
||||
# ----------------------------------------------------------------- school day
|
||||
|
||||
async def refresh_school_day(self) -> bool:
|
||||
"""Work out today's school day, fetching the holidays if the cached ones are
|
||||
not from today. ``False`` if a fetch was due and failed."""
|
||||
today = self._wall().date()
|
||||
ok = True
|
||||
if self._calendar is None:
|
||||
self._calendar = load_calendar(self.cache_file, self.config.subdivision)
|
||||
if self._calendar is None or self._calendar.fetched < today:
|
||||
try:
|
||||
self._calendar = await fetch_calendar(self.client, self.config.subdivision, today)
|
||||
save_calendar(self.cache_file, self._calendar)
|
||||
except Exception as exc:
|
||||
ok = False
|
||||
_log.warning(
|
||||
"Could not fetch the school holidays (%s); %s",
|
||||
exc,
|
||||
"using the cached ones" if self._calendar else "only weekends are known",
|
||||
)
|
||||
self._set_school_day(today)
|
||||
return ok
|
||||
|
||||
def _set_school_day(self, today: date) -> None:
|
||||
is_school_day, reason = school_day(today, self._calendar)
|
||||
if (is_school_day, reason) == (self.state.school_day, self.state.school_day_reason):
|
||||
return
|
||||
self.state.school_day = is_school_day
|
||||
self.state.school_day_reason = reason
|
||||
_log.info(
|
||||
"Today is %s",
|
||||
"a school day" if is_school_day else f"no school day ({reason or 'unknown'})",
|
||||
)
|
||||
self.bus.emit(ClockStateChanged())
|
||||
|
||||
def _seconds_to_midnight(self) -> float:
|
||||
now = self._wall()
|
||||
midnight = datetime.combine(now.date() + timedelta(days=1), datetime.min.time())
|
||||
return (midnight - now).total_seconds() + _AFTER_MIDNIGHT
|
||||
|
||||
# ---------------------------------------------------------------- the timer
|
||||
|
||||
def _on_set(self, event: SetTimerRequested) -> None:
|
||||
self._stop_countdown()
|
||||
now = self._wall().timestamp()
|
||||
self.state.parent_timer = ParentTimer(started_at=now, ends_at=event.ends_at)
|
||||
self.bus.emit(ClockStateChanged())
|
||||
self._countdown = asyncio.create_task(
|
||||
self._run_countdown(event.ends_at - now), name="parent-timer"
|
||||
)
|
||||
|
||||
def _on_cancel(self, _event: CancelTimerRequested) -> None:
|
||||
self._stop_countdown()
|
||||
self._clear()
|
||||
|
||||
def _on_event(self, event: Event) -> None:
|
||||
"""Anything a person does silences a ringing timer - the same notion of "a
|
||||
person" as the screen's idle auto-off: intents, minus Home Assistant's LED
|
||||
writes and the backend talking to itself."""
|
||||
timer = self.state.parent_timer
|
||||
if (
|
||||
timer is None
|
||||
or not timer.ringing
|
||||
or not isinstance(event, IntentEvent)
|
||||
or isinstance(event, (LedEffectRequested, SetTimerRequested, CancelTimerRequested))
|
||||
or event.source == "system"
|
||||
):
|
||||
return
|
||||
self._stop_countdown()
|
||||
self._clear()
|
||||
|
||||
async def _run_countdown(self, seconds: float) -> None:
|
||||
await self._clock.sleep(max(0.0, seconds))
|
||||
timer = self.state.parent_timer
|
||||
if timer is None:
|
||||
return
|
||||
self.state.parent_timer = ParentTimer(
|
||||
started_at=timer.started_at, ends_at=timer.ends_at, ringing=True
|
||||
)
|
||||
_log.info("The parents' timer ran out")
|
||||
self.bus.emit(ClockStateChanged())
|
||||
# Its own task: silencing the timer must not cut the chime off mid-note.
|
||||
self._chime_task = asyncio.create_task(self._chime(), name="parent-timer-chime")
|
||||
await self._clock.sleep(RING_SECONDS)
|
||||
self._countdown = None
|
||||
self._clear()
|
||||
|
||||
async def _chime(self) -> None:
|
||||
if self.alsa_device is None:
|
||||
return
|
||||
gain = _CHIME_GAIN * max(_CHIME_MIN_VOLUME, min(1.0, self.volume()))
|
||||
wav = await asyncio.to_thread(chime_wav, gain=gain)
|
||||
await play_wav(self.alsa_device, wav)
|
||||
|
||||
def _stop_countdown(self) -> None:
|
||||
if self._countdown is not None:
|
||||
self._countdown.cancel()
|
||||
self._countdown = None
|
||||
|
||||
def _clear(self) -> None:
|
||||
if self.state.parent_timer is None:
|
||||
return
|
||||
self.state.parent_timer = None
|
||||
self.bus.emit(ClockStateChanged())
|
||||
@@ -12,6 +12,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -22,6 +23,7 @@ from fastapi.responses import FileResponse
|
||||
from musicmouse.app import App
|
||||
from musicmouse.config import Digit, HaConfig, RemoteSlotConfig
|
||||
from musicmouse.events import (
|
||||
CancelTimerRequested,
|
||||
IntentEvent,
|
||||
NextTrackRequested,
|
||||
PauseRequested,
|
||||
@@ -30,11 +32,13 @@ from musicmouse.events import (
|
||||
PlayRequested,
|
||||
PreviousTrackRequested,
|
||||
SeekRequested,
|
||||
SetTimerRequested,
|
||||
SetVolumeRequested,
|
||||
ToggleScreenRequested,
|
||||
UserActivity,
|
||||
VolumeChangeRequested,
|
||||
)
|
||||
from musicmouse.services.timers import timer_end
|
||||
from musicmouse.services.web.hub import StateHub
|
||||
from musicmouse.services.web.remote_settings import read_mapping, write_mapping
|
||||
from musicmouse.services.web.schemas import (
|
||||
@@ -50,6 +54,7 @@ from musicmouse.services.web.schemas import (
|
||||
SeekIn,
|
||||
SettingsIn,
|
||||
SettingsOut,
|
||||
TimerIn,
|
||||
TippenCurriculumOut,
|
||||
TippenProgressOut,
|
||||
TippenRunIn,
|
||||
@@ -206,6 +211,17 @@ def build_router(
|
||||
# screen's idle auto-off does not blank it under a child who is browsing.
|
||||
return emit(UserActivity(source="web"))
|
||||
|
||||
@router.post("/timer", status_code=204)
|
||||
def set_timer(body: TimerIn) -> Response:
|
||||
# The parents' countdown. The new state, ringing and all, arrives over the
|
||||
# websocket like everything else.
|
||||
end = timer_end(datetime.now(), minutes=body.minutes, until=body.until)
|
||||
return emit(SetTimerRequested(ends_at=end.timestamp(), source="web"))
|
||||
|
||||
@router.delete("/timer", status_code=204)
|
||||
def cancel_timer() -> Response:
|
||||
return emit(CancelTimerRequested(source="web"))
|
||||
|
||||
@router.post("/seek", status_code=204)
|
||||
def seek(body: SeekIn) -> Response:
|
||||
return emit(SeekRequested(position=body.position, source="web"))
|
||||
|
||||
@@ -22,7 +22,7 @@ from typing import Any
|
||||
from fastapi import WebSocket
|
||||
|
||||
from musicmouse.app import App
|
||||
from musicmouse.events import Event, StateEvent
|
||||
from musicmouse.events import Event, StateEvent, ToggleClockRequested
|
||||
from musicmouse.services.web.state import snapshot
|
||||
|
||||
_log = logging.getLogger(__name__)
|
||||
@@ -38,17 +38,21 @@ class StateHub:
|
||||
def __init__(self, app: App) -> None:
|
||||
self.app = app
|
||||
self._clients: set[WebSocket] = set()
|
||||
self._unsubscribe: Any = None
|
||||
self._unsubscribe: list[Any] = []
|
||||
|
||||
# ------------------------------------------------------------------- lifecycle
|
||||
|
||||
def start(self) -> None:
|
||||
self._unsubscribe = self.app.bus.subscribe(StateEvent, self._on_state)
|
||||
self._unsubscribe = [
|
||||
self.app.bus.subscribe(StateEvent, self._on_state),
|
||||
# The clock overlay is the kiosk's own; the remote's key only asks for it.
|
||||
self.app.bus.subscribe(ToggleClockRequested, self._on_clock_toggle),
|
||||
]
|
||||
|
||||
def stop(self) -> None:
|
||||
if self._unsubscribe is not None:
|
||||
self._unsubscribe()
|
||||
self._unsubscribe = None
|
||||
for unsubscribe in self._unsubscribe:
|
||||
unsubscribe()
|
||||
self._unsubscribe = []
|
||||
|
||||
async def run(self) -> None:
|
||||
"""Push the playback position while anything is playing."""
|
||||
@@ -102,3 +106,6 @@ class StateHub:
|
||||
|
||||
async def _on_state(self, _event: Event) -> None:
|
||||
await self.broadcast_state()
|
||||
|
||||
async def _on_clock_toggle(self, _event: ToggleClockRequested) -> None:
|
||||
await self.broadcast({"type": "clock_toggle"})
|
||||
|
||||
@@ -8,9 +8,9 @@ configured ceiling is a parent's business, not a child's, so it never crosses th
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
from typing import Literal, Self
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from musicmouse.config import Digit
|
||||
from musicmouse.library import Album
|
||||
@@ -21,6 +21,8 @@ from musicmouse.tippen.rewards import AlbumLock, TrackLock, UnlockHint
|
||||
|
||||
__all__ = [
|
||||
"AlbumOut",
|
||||
"BusOut",
|
||||
"ClockStateOut",
|
||||
"HaConfigOut",
|
||||
"HaDeviceOut",
|
||||
"LibraryOut",
|
||||
@@ -34,6 +36,8 @@ __all__ = [
|
||||
"SeekIn",
|
||||
"SettingsIn",
|
||||
"SettingsOut",
|
||||
"TimerIn",
|
||||
"TimerOut",
|
||||
"TippenCurriculumOut",
|
||||
"TippenGhostStrokeOut",
|
||||
"TippenKeyStatOut",
|
||||
@@ -202,6 +206,33 @@ class ConnectionOut(BaseModel):
|
||||
lirc: bool
|
||||
|
||||
|
||||
class BusOut(BaseModel):
|
||||
#: "HH:MM", when the bus leaves.
|
||||
time: str
|
||||
#: How long before ``time`` its countdown shows.
|
||||
lead_minutes: int
|
||||
|
||||
|
||||
class TimerOut(BaseModel):
|
||||
#: Wall-clock Unix seconds.
|
||||
started_at: float
|
||||
ends_at: float
|
||||
ringing: bool
|
||||
|
||||
|
||||
class ClockStateOut(BaseModel):
|
||||
"""What the clock overlay shows besides the time."""
|
||||
|
||||
#: ``None`` when the holiday calendar could not be fetched; weekends are known
|
||||
#: regardless.
|
||||
school_day: bool | None
|
||||
#: Why today is no school day: "Wochenende", "Herbstferien", ...
|
||||
school_day_reason: str | None
|
||||
#: Today's bus, or ``None`` when there is no school today.
|
||||
bus: BusOut | None
|
||||
parent_timer: TimerOut | None
|
||||
|
||||
|
||||
class PlayerStateOut(BaseModel):
|
||||
playing: bool
|
||||
album_id: str | None
|
||||
@@ -217,6 +248,7 @@ class PlayerStateOut(BaseModel):
|
||||
volume: int
|
||||
active_figure: str | None
|
||||
connected: ConnectionOut
|
||||
clock: ClockStateOut
|
||||
|
||||
|
||||
class PlayIn(BaseModel):
|
||||
@@ -241,6 +273,20 @@ class VolumeIn(BaseModel):
|
||||
steps: int | None = Field(default=None, ge=-10, le=10)
|
||||
|
||||
|
||||
class TimerIn(BaseModel):
|
||||
"""Minutes from now, or a time of day ("HH:MM", tomorrow if already past); exactly
|
||||
one of the two."""
|
||||
|
||||
minutes: int | None = Field(default=None, ge=1, le=12 * 60)
|
||||
until: str | None = Field(default=None, pattern=r"^([01][0-9]|2[0-3]):[0-5][0-9]$")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _exactly_one(self) -> Self:
|
||||
if (self.minutes is None) == (self.until is None):
|
||||
raise ValueError("give exactly one of minutes and until")
|
||||
return self
|
||||
|
||||
|
||||
class SettingsOut(BaseModel):
|
||||
min_volume: int
|
||||
max_volume: int
|
||||
|
||||
@@ -7,8 +7,16 @@ read ``mouse.active_figure``, do not keep a second copy of it that can drift.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
from musicmouse.app import App
|
||||
from musicmouse.services.web.schemas import ConnectionOut, PlayerStateOut
|
||||
from musicmouse.services.web.schemas import (
|
||||
BusOut,
|
||||
ClockStateOut,
|
||||
ConnectionOut,
|
||||
PlayerStateOut,
|
||||
TimerOut,
|
||||
)
|
||||
from musicmouse.services.web.settings import to_percent
|
||||
|
||||
__all__ = ["snapshot"]
|
||||
@@ -45,4 +53,27 @@ def snapshot(app: App) -> PlayerStateOut:
|
||||
mqtt=app.state.mqtt_connected,
|
||||
lirc=app.state.lirc_connected,
|
||||
),
|
||||
clock=clock_state(app),
|
||||
)
|
||||
|
||||
|
||||
def clock_state(app: App, today: date | None = None) -> ClockStateOut:
|
||||
state = app.state
|
||||
config = app.config.general.clock
|
||||
# Without a holiday calendar a weekday counts as a school day: a bus countdown on
|
||||
# a holiday is a smaller surprise than none on the first day back.
|
||||
today = today or date.today()
|
||||
school = state.school_day if state.school_day is not None else today.weekday() < 5
|
||||
timer = state.parent_timer
|
||||
return ClockStateOut(
|
||||
school_day=state.school_day,
|
||||
school_day_reason=state.school_day_reason,
|
||||
bus=BusOut(time=config.bus_time, lead_minutes=config.bus_lead_minutes)
|
||||
if school
|
||||
else None,
|
||||
parent_timer=TimerOut(
|
||||
started_at=timer.started_at, ends_at=timer.ends_at, ringing=timer.ringing
|
||||
)
|
||||
if timer
|
||||
else None,
|
||||
)
|
||||
|
||||
45
python-backend/musicmouse/sound.py
Normal file
45
python-backend/musicmouse/sound.py
Normal file
@@ -0,0 +1,45 @@
|
||||
"""Playing a short synthesised sound on the music's own ALSA device.
|
||||
|
||||
``aplay`` in a subprocess, fed the WAV on stdin: no audio library to load, and a hung
|
||||
or missing ``aplay`` costs a log line, never the event loop.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
_log = logging.getLogger(__name__)
|
||||
|
||||
__all__ = ["play_wav"]
|
||||
|
||||
|
||||
async def play_wav(alsa_device: str, wav: bytes, *, timeout: float = 10.0) -> None:
|
||||
"""Play ``wav`` to the end. Failures are logged, not raised."""
|
||||
try:
|
||||
process = await asyncio.create_subprocess_exec(
|
||||
"aplay",
|
||||
"-q",
|
||||
"-D",
|
||||
alsa_device,
|
||||
"-",
|
||||
stdin=asyncio.subprocess.PIPE,
|
||||
stdout=asyncio.subprocess.DEVNULL,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
except OSError as exc:
|
||||
_log.warning("Could not play a sound: %s", exc)
|
||||
return
|
||||
try:
|
||||
_, error = await asyncio.wait_for(process.communicate(wav), timeout)
|
||||
except TimeoutError:
|
||||
process.kill()
|
||||
await process.wait()
|
||||
_log.warning("A sound took longer than %gs; killed", timeout)
|
||||
return
|
||||
if process.returncode != 0:
|
||||
_log.warning(
|
||||
"Playing a sound failed (exit %d): %s",
|
||||
process.returncode,
|
||||
error.decode(errors="replace").strip(),
|
||||
)
|
||||
@@ -21,6 +21,7 @@ from musicmouse.events import (
|
||||
PlayRequested,
|
||||
PlaySeriesLatestRequested,
|
||||
PreviousTrackRequested,
|
||||
ToggleClockRequested,
|
||||
ToggleScreenRequested,
|
||||
VolumeChangeRequested,
|
||||
)
|
||||
@@ -316,6 +317,26 @@ async def test_the_power_button_toggles_the_screen(
|
||||
assert len(seen) == 1
|
||||
|
||||
|
||||
async def test_the_guide_key_asks_for_the_clock(
|
||||
lircd: tuple[ScriptedLircd, asyncio.base_events.Server], sim: Simulation
|
||||
) -> None:
|
||||
station, server = lircd
|
||||
port = server.sockets[0].getsockname()[1]
|
||||
seen: list[Event] = []
|
||||
sim.bus.subscribe(ToggleClockRequested, seen.append)
|
||||
|
||||
task = await _run_service(sim, _lirc_config(port))
|
||||
try:
|
||||
await station.wait_connected()
|
||||
await station.send("b7c0000000000000 00 key_epg hauppauge")
|
||||
await station.send("b7c0000000000000 00 key_epg hauppauge") # still held
|
||||
await sim.bus.drain()
|
||||
finally:
|
||||
task.cancel()
|
||||
|
||||
assert [event.source for event in seen] == ["lirc"]
|
||||
|
||||
|
||||
async def test_mute_toggles_and_restores(
|
||||
lircd: tuple[ScriptedLircd, asyncio.base_events.Server], sim: Simulation
|
||||
) -> None:
|
||||
|
||||
141
python-backend/tests/test_school_days.py
Normal file
141
python-backend/tests/test_school_days.py
Normal file
@@ -0,0 +1,141 @@
|
||||
"""Which days are school days, from the OpenHolidays API's two lists."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx2
|
||||
import pytest
|
||||
|
||||
from musicmouse.school_days import (
|
||||
HolidayCalendar,
|
||||
fetch_calendar,
|
||||
load_calendar,
|
||||
parse_holidays,
|
||||
save_calendar,
|
||||
school_day,
|
||||
)
|
||||
|
||||
|
||||
def _entry(
|
||||
start: str, end: str, name: str, *codes: str, nationwide: bool = False
|
||||
) -> dict[str, Any]:
|
||||
"""One entry in the API's shape (trimmed to the fields that are read)."""
|
||||
return {
|
||||
"startDate": start,
|
||||
"endDate": end,
|
||||
"name": [{"language": "DE", "text": name}],
|
||||
"nationwide": nationwide,
|
||||
"subdivisions": [{"code": code, "shortName": code[3:]} for code in codes],
|
||||
}
|
||||
|
||||
|
||||
#: Verbatim dates from the API for Bavaria, 2026/27.
|
||||
SCHOOL = [
|
||||
_entry("2026-11-02", "2026-11-06", "Herbstferien", "DE-BY"),
|
||||
_entry("2026-11-18", "2026-11-18", "Buß- und Bettag", "DE-BY"),
|
||||
_entry("2026-12-24", "2027-01-08", "Weihnachtsferien", "DE-BY"),
|
||||
]
|
||||
PUBLIC = [
|
||||
_entry("2026-10-03", "2026-10-03", "Tag der Deutschen Einheit", nationwide=True),
|
||||
_entry("2027-05-27", "2027-05-27", "Fronleichnam", "DE-HE", "DE-BW", "DE-BY"),
|
||||
_entry("2027-08-09", "2027-08-09", "Friedensfest", "DE-BY-AU"),
|
||||
]
|
||||
|
||||
|
||||
def _calendar(subdivision: str = "DE-BY") -> HolidayCalendar:
|
||||
return HolidayCalendar(
|
||||
fetched=date(2026, 10, 1),
|
||||
subdivision=subdivision,
|
||||
school=parse_holidays(SCHOOL),
|
||||
public=parse_holidays(PUBLIC),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("day", "expected"),
|
||||
[
|
||||
(date(2026, 10, 5), (True, None)), # a plain Monday
|
||||
(date(2026, 10, 10), (False, "Wochenende")),
|
||||
(date(2026, 10, 11), (False, "Wochenende")),
|
||||
(date(2026, 11, 4), (False, "Herbstferien")),
|
||||
(date(2026, 11, 9), (True, None)), # the Monday after
|
||||
(date(2026, 11, 18), (False, "Buß- und Bettag")),
|
||||
(date(2027, 1, 7), (False, "Weihnachtsferien")), # spans the new year
|
||||
(date(2027, 5, 27), (False, "Fronleichnam")),
|
||||
],
|
||||
)
|
||||
def test_school_days_in_bavaria(day: date, expected: tuple[bool, str | None]) -> None:
|
||||
assert school_day(day, _calendar()) == expected
|
||||
|
||||
|
||||
def test_a_nationwide_holiday_on_a_weekend_is_still_the_weekend() -> None:
|
||||
assert school_day(date(2026, 10, 3), _calendar()) == (False, "Wochenende")
|
||||
|
||||
|
||||
def test_a_city_holiday_counts_only_for_that_city() -> None:
|
||||
friedensfest = date(2027, 8, 9) # a Monday; pretend it is not in the summer holidays
|
||||
assert school_day(friedensfest, _calendar("DE-BY")) == (True, None)
|
||||
assert school_day(friedensfest, _calendar("DE-BY-AU")) == (False, "Friedensfest")
|
||||
|
||||
|
||||
def test_a_city_also_gets_its_states_holidays() -> None:
|
||||
assert school_day(date(2026, 11, 4), _calendar("DE-BY-AU")) == (False, "Herbstferien")
|
||||
|
||||
|
||||
def test_without_a_calendar_only_the_weekend_is_known() -> None:
|
||||
assert school_day(date(2026, 10, 5), None) == (None, None)
|
||||
assert school_day(date(2026, 10, 10), None) == (False, "Wochenende")
|
||||
|
||||
|
||||
def test_entries_that_do_not_parse_are_skipped() -> None:
|
||||
raw = [{"startDate": "nope"}, {"name": []}, SCHOOL[0]]
|
||||
assert [holiday.name for holiday in parse_holidays(raw)] == ["Herbstferien"]
|
||||
|
||||
|
||||
def test_the_cache_round_trips(tmp_path: Path) -> None:
|
||||
path = tmp_path / "cache" / "holidays.json"
|
||||
save_calendar(path, _calendar())
|
||||
assert load_calendar(path, "DE-BY") == _calendar()
|
||||
|
||||
|
||||
def test_a_cache_for_another_subdivision_is_not_used(tmp_path: Path) -> None:
|
||||
path = tmp_path / "holidays.json"
|
||||
save_calendar(path, _calendar())
|
||||
assert load_calendar(path, "DE-BW") is None
|
||||
|
||||
|
||||
def test_a_broken_or_missing_cache_is_no_cache(tmp_path: Path) -> None:
|
||||
path = tmp_path / "holidays.json"
|
||||
assert load_calendar(path, "DE-BY") is None
|
||||
path.write_text("{not json")
|
||||
assert load_calendar(path, "DE-BY") is None
|
||||
|
||||
|
||||
async def test_fetching_asks_for_the_state_and_both_lists() -> None:
|
||||
requests: list[httpx2.Request] = []
|
||||
|
||||
def handler(request: httpx2.Request) -> httpx2.Response:
|
||||
requests.append(request)
|
||||
body = SCHOOL if request.url.path == "/SchoolHolidays" else PUBLIC
|
||||
return httpx2.Response(200, json=body)
|
||||
|
||||
async with httpx2.AsyncClient(transport=httpx2.MockTransport(handler)) as client:
|
||||
calendar = await fetch_calendar(client, "DE-BY-AU", date(2026, 10, 1))
|
||||
|
||||
assert [r.url.path for r in requests] == ["/SchoolHolidays", "/PublicHolidays"]
|
||||
assert all(r.url.params["subdivisionCode"] == "DE-BY" for r in requests)
|
||||
assert all(r.url.params["countryIsoCode"] == "DE" for r in requests)
|
||||
assert calendar.subdivision == "DE-BY-AU"
|
||||
assert calendar.fetched == date(2026, 10, 1)
|
||||
assert len(calendar.school) == 3
|
||||
assert len(calendar.public) == 3
|
||||
|
||||
|
||||
async def test_a_failed_fetch_raises() -> None:
|
||||
transport = httpx2.MockTransport(lambda _: httpx2.Response(503))
|
||||
async with httpx2.AsyncClient(transport=transport) as client:
|
||||
with pytest.raises(httpx2.HTTPStatusError):
|
||||
await fetch_calendar(client, "DE-BY", date(2026, 10, 1))
|
||||
292
python-backend/tests/test_timers.py
Normal file
292
python-backend/tests/test_timers.py
Normal file
@@ -0,0 +1,292 @@
|
||||
"""The parents' timer and today's school day, on virtual time and a pinned date."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
import wave
|
||||
from array import array
|
||||
from collections.abc import AsyncIterator, Callable
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import httpx2
|
||||
import pytest
|
||||
|
||||
from musicmouse.app import AppState
|
||||
from musicmouse.blubb import RATE, chime_wav
|
||||
from musicmouse.bus import EventBus
|
||||
from musicmouse.clock import FakeClock
|
||||
from musicmouse.color import ColorRGBW
|
||||
from musicmouse.config import ClockConfig
|
||||
from musicmouse.effects import EffectStaticConfig
|
||||
from musicmouse.events import (
|
||||
CancelTimerRequested,
|
||||
ClockStateChanged,
|
||||
LedEffectRequested,
|
||||
NextTrackRequested,
|
||||
SetTimerRequested,
|
||||
UserActivity,
|
||||
)
|
||||
from musicmouse.hardware import LedZone
|
||||
from musicmouse.services.timers import RING_SECONDS, TimerService, timer_end
|
||||
from tests.test_school_days import PUBLIC, SCHOOL
|
||||
|
||||
#: A Monday in the Herbstferien.
|
||||
HOLIDAY = datetime(2026, 11, 2, 18, 0)
|
||||
#: A plain school Monday.
|
||||
SCHOOL_DAY = datetime(2026, 10, 5, 6, 0)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- chime
|
||||
|
||||
|
||||
def test_the_chime_is_a_short_wav_at_the_requested_level() -> None:
|
||||
wav = chime_wav(gain=0.3)
|
||||
with wave.open(io.BytesIO(wav)) as audio:
|
||||
assert audio.getnchannels() == 1
|
||||
assert audio.getframerate() == RATE
|
||||
frames = audio.readframes(audio.getnframes())
|
||||
assert 1.0 < audio.getnframes() / RATE < 3.0
|
||||
peak = max(abs(sample) for sample in array("h", frames))
|
||||
assert peak == round(32767 * 0.3)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------- timer_end
|
||||
|
||||
|
||||
def test_minutes_count_from_now() -> None:
|
||||
assert timer_end(datetime(2026, 10, 5, 18, 50), minutes=15) == datetime(2026, 10, 5, 19, 5)
|
||||
|
||||
|
||||
def test_a_time_later_today_is_today() -> None:
|
||||
now = datetime(2026, 10, 5, 18, 50, 30)
|
||||
assert timer_end(now, until="19:30") == datetime(2026, 10, 5, 19, 30)
|
||||
|
||||
|
||||
def test_a_time_already_past_is_tomorrow() -> None:
|
||||
now = datetime(2026, 10, 5, 23, 40)
|
||||
assert timer_end(now, until="00:10") == datetime(2026, 10, 6, 0, 10)
|
||||
assert timer_end(now, until="23:40") == datetime(2026, 10, 6, 23, 40)
|
||||
|
||||
|
||||
def test_exactly_one_of_minutes_and_until() -> None:
|
||||
with pytest.raises(ValueError):
|
||||
timer_end(HOLIDAY)
|
||||
with pytest.raises(ValueError):
|
||||
timer_end(HOLIDAY, minutes=5, until="19:00")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------- service
|
||||
|
||||
|
||||
class Harness:
|
||||
def __init__(self, bus: EventBus, clock: FakeClock, service: TimerService) -> None:
|
||||
self.bus = bus
|
||||
self.clock = clock
|
||||
self.service = service
|
||||
self.state = service.state
|
||||
self.changes = 0
|
||||
bus.subscribe(ClockStateChanged, self._count)
|
||||
|
||||
def _count(self, _event: ClockStateChanged) -> None:
|
||||
self.changes += 1
|
||||
|
||||
def now(self) -> float:
|
||||
return self.service._wall().timestamp()
|
||||
|
||||
|
||||
def _holiday_api(status: int = 200) -> Callable[[httpx2.Request], httpx2.Response]:
|
||||
def handler(request: httpx2.Request) -> httpx2.Response:
|
||||
if status != 200:
|
||||
return httpx2.Response(status)
|
||||
return httpx2.Response(200, json=SCHOOL if "School" in request.url.path else PUBLIC)
|
||||
|
||||
return handler
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def start() -> datetime:
|
||||
return HOLIDAY
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api_status() -> int:
|
||||
return 200
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def harness(tmp_path: Path, start: datetime, api_status: int) -> AsyncIterator[Harness]:
|
||||
async with EventBus() as bus:
|
||||
clock = FakeClock(idle=bus.drain)
|
||||
service = TimerService(
|
||||
bus,
|
||||
AppState(),
|
||||
ClockConfig(),
|
||||
cache_file=tmp_path / "holidays.json",
|
||||
client=httpx2.AsyncClient(transport=httpx2.MockTransport(_holiday_api(api_status))),
|
||||
alsa_device=None,
|
||||
volume=lambda: 0.5,
|
||||
clock=clock,
|
||||
wall=lambda: start + timedelta(seconds=clock.now()),
|
||||
)
|
||||
task = asyncio.create_task(service.run())
|
||||
await clock.advance(0)
|
||||
try:
|
||||
yield Harness(bus, clock, service)
|
||||
finally:
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
|
||||
|
||||
async def _set(h: Harness, minutes: float) -> None:
|
||||
await h.bus.emit_and_wait(SetTimerRequested(ends_at=h.now() + minutes * 60, source="web"))
|
||||
await h.clock.advance(0)
|
||||
|
||||
|
||||
async def test_a_timer_counts_down_then_rings(harness: Harness) -> None:
|
||||
await _set(harness, 5)
|
||||
timer = harness.state.parent_timer
|
||||
assert timer is not None and not timer.ringing
|
||||
assert timer.ends_at - timer.started_at == 300
|
||||
|
||||
await harness.clock.advance(299)
|
||||
assert not harness.state.parent_timer.ringing # type: ignore[union-attr]
|
||||
await harness.clock.advance(1)
|
||||
assert harness.state.parent_timer.ringing # type: ignore[union-attr]
|
||||
|
||||
|
||||
async def test_a_ringing_timer_clears_itself_after_a_minute(harness: Harness) -> None:
|
||||
await _set(harness, 1)
|
||||
await harness.clock.advance(60)
|
||||
assert harness.state.parent_timer is not None
|
||||
|
||||
await harness.clock.advance(RING_SECONDS - 1)
|
||||
assert harness.state.parent_timer is not None
|
||||
await harness.clock.advance(1)
|
||||
assert harness.state.parent_timer is None
|
||||
|
||||
|
||||
async def test_anything_a_person_does_silences_it(harness: Harness) -> None:
|
||||
await _set(harness, 1)
|
||||
await harness.clock.advance(60)
|
||||
|
||||
await harness.bus.emit_and_wait(NextTrackRequested(source="lirc"))
|
||||
assert harness.state.parent_timer is None
|
||||
|
||||
|
||||
async def test_a_key_press_in_the_kiosk_silences_it(harness: Harness) -> None:
|
||||
await _set(harness, 1)
|
||||
await harness.clock.advance(60)
|
||||
|
||||
await harness.bus.emit_and_wait(UserActivity(source="web"))
|
||||
assert harness.state.parent_timer is None
|
||||
|
||||
|
||||
async def test_the_backend_and_home_assistant_do_not_silence_it(harness: Harness) -> None:
|
||||
await _set(harness, 1)
|
||||
await harness.clock.advance(60)
|
||||
|
||||
await harness.bus.emit_and_wait(NextTrackRequested(source="system"))
|
||||
effect = EffectStaticConfig(color=ColorRGBW(1, 0, 0, 0))
|
||||
await harness.bus.emit_and_wait(
|
||||
LedEffectRequested(zone=LedZone.MOUSE, effect=effect, source="mqtt")
|
||||
)
|
||||
assert harness.state.parent_timer is not None
|
||||
|
||||
|
||||
async def test_input_while_counting_down_does_not_stop_it(harness: Harness) -> None:
|
||||
await _set(harness, 5)
|
||||
await harness.bus.emit_and_wait(NextTrackRequested(source="lirc"))
|
||||
assert harness.state.parent_timer is not None
|
||||
|
||||
|
||||
async def test_cancel_stops_a_running_timer(harness: Harness) -> None:
|
||||
await _set(harness, 5)
|
||||
await harness.bus.emit_and_wait(CancelTimerRequested(source="web"))
|
||||
assert harness.state.parent_timer is None
|
||||
|
||||
await harness.clock.advance(600) # and it does not come back to ring
|
||||
assert harness.state.parent_timer is None
|
||||
|
||||
|
||||
async def test_a_new_timer_replaces_the_old_one(harness: Harness) -> None:
|
||||
await _set(harness, 5)
|
||||
await _set(harness, 30)
|
||||
|
||||
await harness.clock.advance(300)
|
||||
timer = harness.state.parent_timer
|
||||
assert timer is not None and not timer.ringing
|
||||
|
||||
|
||||
async def test_every_step_is_announced(harness: Harness) -> None:
|
||||
before = harness.changes
|
||||
await _set(harness, 1) # set
|
||||
await harness.clock.advance(60) # ringing
|
||||
await harness.clock.advance(RING_SECONDS) # cleared
|
||||
assert harness.changes - before == 3
|
||||
|
||||
|
||||
# -------------------------------------------------------------------- school day
|
||||
|
||||
|
||||
async def test_a_holiday_is_no_school_day(harness: Harness) -> None:
|
||||
assert harness.state.school_day is False
|
||||
assert harness.state.school_day_reason == "Herbstferien"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("start", [SCHOOL_DAY])
|
||||
async def test_a_plain_monday_is_a_school_day(harness: Harness) -> None:
|
||||
assert harness.state.school_day is True
|
||||
assert harness.state.school_day_reason is None
|
||||
|
||||
|
||||
async def test_the_holidays_are_cached(harness: Harness) -> None:
|
||||
assert harness.service.cache_file.exists()
|
||||
|
||||
|
||||
async def test_the_day_changes_at_midnight(harness: Harness) -> None:
|
||||
# Friday 2026-11-06 is the last day of the Herbstferien; Saturday is the weekend.
|
||||
await harness.clock.advance(4 * 86400)
|
||||
assert harness.state.school_day_reason == "Herbstferien"
|
||||
await harness.clock.advance(86400)
|
||||
assert harness.state.school_day_reason == "Wochenende"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("start", "api_status"), [(SCHOOL_DAY, 503)])
|
||||
async def test_offline_without_a_cache_the_weekday_is_unknown(harness: Harness) -> None:
|
||||
assert harness.state.school_day is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api_status", [503])
|
||||
async def test_offline_with_a_cache_the_cache_is_used(
|
||||
tmp_path: Path, start: datetime, api_status: int
|
||||
) -> None:
|
||||
from musicmouse.school_days import HolidayCalendar, parse_holidays, save_calendar
|
||||
|
||||
cache = tmp_path / "holidays.json"
|
||||
save_calendar(
|
||||
cache,
|
||||
HolidayCalendar(
|
||||
fetched=start.date() - timedelta(days=3),
|
||||
subdivision="DE-BY",
|
||||
school=parse_holidays(SCHOOL),
|
||||
public=parse_holidays(PUBLIC),
|
||||
),
|
||||
)
|
||||
async with EventBus() as bus:
|
||||
service = TimerService(
|
||||
bus,
|
||||
AppState(),
|
||||
ClockConfig(),
|
||||
cache_file=cache,
|
||||
client=httpx2.AsyncClient(transport=httpx2.MockTransport(_holiday_api(api_status))),
|
||||
alsa_device=None,
|
||||
volume=lambda: 0.5,
|
||||
wall=lambda: start,
|
||||
)
|
||||
assert await service.refresh_school_day() is False
|
||||
await service.client.aclose()
|
||||
|
||||
assert service.state.school_day_reason == "Herbstferien"
|
||||
@@ -9,7 +9,9 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import contextlib
|
||||
import json
|
||||
import time
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import TypeAlias
|
||||
|
||||
@@ -17,8 +19,15 @@ import httpx2
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
|
||||
from musicmouse.app import ParentTimer
|
||||
from musicmouse.config import WebConfig, load_config
|
||||
from musicmouse.events import ToggleScreenRequested
|
||||
from musicmouse.events import (
|
||||
CancelTimerRequested,
|
||||
ClockStateChanged,
|
||||
SetTimerRequested,
|
||||
ToggleClockRequested,
|
||||
ToggleScreenRequested,
|
||||
)
|
||||
from musicmouse.library.analysis import BeatGrid, TrackCurves
|
||||
from musicmouse.library.models import track_key
|
||||
from musicmouse.services.web.service import build_app
|
||||
@@ -318,6 +327,76 @@ async def test_volume_needs_one_of_the_fields(client: Client) -> None:
|
||||
assert (await client.post("/api/volume", json={})).status_code == 422
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------- clock
|
||||
|
||||
|
||||
async def test_a_timer_in_minutes_is_an_intent(client: Client, sim: Simulation) -> None:
|
||||
seen: list[SetTimerRequested] = []
|
||||
sim.bus.subscribe(SetTimerRequested, seen.append)
|
||||
|
||||
before = time.time()
|
||||
response = await client.post("/api/timer", json={"minutes": 15})
|
||||
await sim.bus.drain()
|
||||
|
||||
assert response.status_code == 204
|
||||
assert len(seen) == 1
|
||||
assert before + 900 <= seen[0].ends_at <= time.time() + 900
|
||||
|
||||
|
||||
async def test_a_timer_until_a_time_is_an_intent(client: Client, sim: Simulation) -> None:
|
||||
seen: list[SetTimerRequested] = []
|
||||
sim.bus.subscribe(SetTimerRequested, seen.append)
|
||||
|
||||
response = await client.post("/api/timer", json={"until": "19:30"})
|
||||
await sim.bus.drain()
|
||||
|
||||
assert response.status_code == 204
|
||||
end = datetime.fromtimestamp(seen[0].ends_at)
|
||||
assert (end.hour, end.minute) == (19, 30)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body", [{}, {"minutes": 5, "until": "19:30"}, {"minutes": 0}, {"until": "25:00"}]
|
||||
)
|
||||
async def test_a_timer_needs_exactly_one_valid_field(client: Client, body: dict) -> None:
|
||||
assert (await client.post("/api/timer", json=body)).status_code == 422
|
||||
|
||||
|
||||
async def test_cancelling_the_timer_is_an_intent(client: Client, sim: Simulation) -> None:
|
||||
seen: list[CancelTimerRequested] = []
|
||||
sim.bus.subscribe(CancelTimerRequested, seen.append)
|
||||
|
||||
response = await client.delete("/api/timer")
|
||||
await sim.bus.drain()
|
||||
|
||||
assert response.status_code == 204
|
||||
assert len(seen) == 1
|
||||
|
||||
|
||||
async def test_the_state_carries_the_clock(client: Client, sim: Simulation) -> None:
|
||||
sim.app.state.school_day = True
|
||||
sim.app.state.parent_timer = ParentTimer(started_at=100.0, ends_at=400.0)
|
||||
|
||||
clock = (await client.get("/api/state")).json()["clock"]
|
||||
|
||||
assert clock == {
|
||||
"school_day": True,
|
||||
"school_day_reason": None,
|
||||
"bus": {"time": "07:25", "lead_minutes": 60},
|
||||
"parent_timer": {"started_at": 100.0, "ends_at": 400.0, "ringing": False},
|
||||
}
|
||||
|
||||
|
||||
async def test_no_bus_without_school(client: Client, sim: Simulation) -> None:
|
||||
sim.app.state.school_day = False
|
||||
sim.app.state.school_day_reason = "Herbstferien"
|
||||
|
||||
clock = (await client.get("/api/state")).json()["clock"]
|
||||
|
||||
assert clock["bus"] is None
|
||||
assert clock["school_day_reason"] == "Herbstferien"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------- websocket
|
||||
|
||||
|
||||
@@ -383,6 +462,26 @@ async def test_switching_albums_while_playing_reaches_every_client(
|
||||
assert (await last_state(socket))["album_title"] == "Eule"
|
||||
|
||||
|
||||
async def test_a_clock_change_reaches_the_clients(api: FastAPI, sim: Simulation) -> None:
|
||||
async with websocket_connect(api, "/api/ws") as socket:
|
||||
await socket.next_json()
|
||||
|
||||
sim.app.state.parent_timer = ParentTimer(started_at=1.0, ends_at=2.0, ringing=True)
|
||||
await sim.bus.emit_and_wait(ClockStateChanged())
|
||||
|
||||
state = await last_state(socket)
|
||||
assert state["clock"]["parent_timer"]["ringing"] is True
|
||||
|
||||
|
||||
async def test_the_remotes_clock_key_reaches_the_clients(api: FastAPI, sim: Simulation) -> None:
|
||||
async with websocket_connect(api, "/api/ws") as socket:
|
||||
await socket.next_json()
|
||||
|
||||
await sim.bus.emit_and_wait(ToggleClockRequested(source="lirc"))
|
||||
|
||||
assert await socket.next_json() == {"type": "clock_toggle"}
|
||||
|
||||
|
||||
async def test_a_refresh_tells_the_clients_to_reload_the_library(
|
||||
api: FastAPI, client: Client, sim: Simulation
|
||||
) -> None:
|
||||
|
||||
BIN
web/public/clock/bus.webp
Normal file
BIN
web/public/clock/bus.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
BIN
web/public/clock/dolphin-watch.webp
Normal file
BIN
web/public/clock/dolphin-watch.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
150
web/src/App.tsx
150
web/src/App.tsx
@@ -23,7 +23,8 @@ import { BrowseView } from "./components/BrowseView";
|
||||
import { HelpOverlay } from "./components/HelpOverlay";
|
||||
import { MobileBrowse } from "./components/mobile/MobileBrowse";
|
||||
import { MobileDock } from "./components/mobile/MobileDock";
|
||||
import { ParentPanel } from "./components/ParentPanel";
|
||||
import { ClockOverlay } from "./components/ClockOverlay";
|
||||
import { ParentPage, ParentPanel } from "./components/ParentPanel";
|
||||
import { PlayerBar } from "./components/PlayerBar";
|
||||
import { PlayView } from "./components/PlayView";
|
||||
import { RemoteAssignPopup } from "./components/RemoteAssignPopup";
|
||||
@@ -75,14 +76,22 @@ const PODCAST_SKIP_SECONDS = 30;
|
||||
export function App() {
|
||||
const [ui, setUi] = useState<UiState>(initialUiState);
|
||||
const library = useLibrary();
|
||||
const connection = usePlayerState(library.reload);
|
||||
// The remote's Guide key. Only the kiosk on the device shows the clock for it - a
|
||||
// tablet in another room has no business popping one up, same rule as Del.
|
||||
const onRemoteClockToggle = useCallback(() => {
|
||||
if (ON_THE_DEVICE) setUi((previous) => ({ ...previous, showClock: !previous.showClock }));
|
||||
}, []);
|
||||
const connection = usePlayerState(library.reload, onRemoteClockToggle);
|
||||
const [gridRef, columns] = useGridColumns();
|
||||
// A phone gets its own touch layout (components/mobile/); everything else - the
|
||||
// kiosk, a desktop browser, a tablet - keeps the keyboard-first one.
|
||||
const phone = usePhoneLayout();
|
||||
const [parentMode, setParentMode] = useState(
|
||||
// `?parentMode=1` only adds a way into parent mode (the 🔧 button, or the phone's
|
||||
// "Eltern" tab), so the URL can stay bookmarked on a parent's tablet or phone.
|
||||
const [parentAccess] = useState(
|
||||
() => new URLSearchParams(location.search).get("parentMode") === "1",
|
||||
);
|
||||
const [parentPanelOpen, setParentPanelOpen] = useState(false);
|
||||
const [perfOpen, setPerfOpen] = useState(
|
||||
() => PERF_ENABLED && new URLSearchParams(location.search).get("perf") === "1",
|
||||
);
|
||||
@@ -419,6 +428,34 @@ export function App() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// The parents' timer ran out: the kiosk shows the clock with it, chiming 00:00.
|
||||
const ringing = state?.clock.parent_timer?.ringing ?? false;
|
||||
useEffect(() => {
|
||||
if (ringing && ON_THE_DEVICE) setUi((previous) => ({ ...previous, showClock: true }));
|
||||
}, [ringing]);
|
||||
|
||||
// ... and the next key press or tap anywhere silences it. The backend does the same
|
||||
// for the remote and the mouse; this is the kiosk's (and any open tab's) share.
|
||||
useEffect(() => {
|
||||
if (!ringing) return;
|
||||
const silence = () => void api.clearTimer().catch(() => {});
|
||||
window.addEventListener("keydown", silence, true);
|
||||
window.addEventListener("pointerdown", silence, true);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", silence, true);
|
||||
window.removeEventListener("pointerdown", silence, true);
|
||||
};
|
||||
}, [ringing]);
|
||||
|
||||
// The "Eltern" tab only exists on a phone; a window that grows out of the phone
|
||||
// layout while on it goes back to the music, with the sheet open in its place.
|
||||
useEffect(() => {
|
||||
if (!phone && ui.page === "parents") {
|
||||
setUi((previous) => ({ ...previous, page: "music" }));
|
||||
setParentPanelOpen(true);
|
||||
}
|
||||
}, [phone, ui.page]);
|
||||
|
||||
// An abandoned "A" press disarms itself rather than leaving the app half-primed.
|
||||
useEffect(() => {
|
||||
if (!ui.assignPending) return;
|
||||
@@ -659,11 +696,22 @@ export function App() {
|
||||
|
||||
{!phone && <TabRail page={ui.page} onSelect={onSelectPage} showRoom={haConfig != null} />}
|
||||
|
||||
{phone && (ui.page === "room" || (ui.page === "music" && ui.view === "browse")) && (
|
||||
{phone && ui.page === "parents" && parentAccess && (
|
||||
<ParentPage
|
||||
clock={state?.clock ?? null}
|
||||
onOpenPerf={PERF_ENABLED ? () => setPerfOpen(true) : undefined}
|
||||
/>
|
||||
)}
|
||||
|
||||
{phone &&
|
||||
(ui.page === "room" ||
|
||||
(ui.page === "parents" && parentAccess) ||
|
||||
(ui.page === "music" && ui.view === "browse")) && (
|
||||
<MobileDock
|
||||
page={ui.page}
|
||||
onSelectPage={onSelectPhonePage}
|
||||
showRoom={haConfig != null}
|
||||
showParents={parentAccess}
|
||||
searching={ui.page === "music" && ui.searchOpen}
|
||||
typed={ui.search}
|
||||
onOpenSearch={() => setUi((previous) => ({ ...previous, searchOpen: true }))}
|
||||
@@ -698,55 +746,42 @@ export function App() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{parentMode && <ParentPanel onClose={() => setParentMode(false)} />}
|
||||
<ClockOverlay
|
||||
visible={ui.showClock}
|
||||
clock={state?.clock ?? null}
|
||||
onClose={() => setUi((previous) => ({ ...previous, showClock: false }))}
|
||||
/>
|
||||
|
||||
{PERF_ENABLED && !perfOpen && (
|
||||
<button
|
||||
onClick={() => setPerfOpen(true)}
|
||||
aria-label="Leistungseinstellungen"
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: 8,
|
||||
bottom: 8,
|
||||
zIndex: 5,
|
||||
width: 32,
|
||||
height: 32,
|
||||
border: "none",
|
||||
borderRadius: 999,
|
||||
cursor: "pointer",
|
||||
background: "oklch(15% 0.03 var(--hue) / .35)",
|
||||
color: "#fff",
|
||||
opacity: 0.5,
|
||||
}}
|
||||
>
|
||||
⚡
|
||||
</button>
|
||||
{parentAccess && parentPanelOpen && (
|
||||
<ParentPanel clock={state?.clock ?? null} onClose={() => setParentPanelOpen(false)} />
|
||||
)}
|
||||
|
||||
{PERF_ENABLED && perfOpen && <PerfPanel onClose={() => setPerfOpen(false)} />}
|
||||
|
||||
{/* The F1 sheet, reachable without knowing about F1. Not on a phone (no keyboard)
|
||||
or the typing page (TippenApp has its own help and owns every key there). */}
|
||||
{!phone && ui.page !== "typing" && !ui.showHelp && (
|
||||
<button
|
||||
{/* Small tools in the bottom-left corner. Not on a phone: there the dock covers
|
||||
that corner, and parent mode is a tab in it instead. The F1 sheet's button is
|
||||
not on the typing page either (TippenApp has its own help and owns every key). */}
|
||||
{!phone && (
|
||||
<div style={{ position: "absolute", left: 8, bottom: 8, zIndex: 5, display: "flex", gap: 8 }}>
|
||||
{PERF_ENABLED && !perfOpen && (
|
||||
<ToolButton label="Leistungseinstellungen" onClick={() => setPerfOpen(true)}>
|
||||
⚡
|
||||
</ToolButton>
|
||||
)}
|
||||
{ui.page !== "typing" && !ui.showHelp && (
|
||||
<ToolButton
|
||||
label="Tastenkürzel"
|
||||
onClick={() => setUi((previous) => ({ ...previous, showHelp: true }))}
|
||||
aria-label="Tastenkürzel"
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: PERF_ENABLED && !perfOpen ? 48 : 8,
|
||||
bottom: 8,
|
||||
zIndex: 5,
|
||||
width: 32,
|
||||
height: 32,
|
||||
border: "none",
|
||||
borderRadius: 999,
|
||||
cursor: "pointer",
|
||||
background: "oklch(15% 0.03 var(--hue) / .35)",
|
||||
color: "#fff",
|
||||
opacity: 0.5,
|
||||
}}
|
||||
>
|
||||
⌨
|
||||
</button>
|
||||
</ToolButton>
|
||||
)}
|
||||
{parentAccess && !parentPanelOpen && (
|
||||
<ToolButton label="Eltern-Einstellungen" onClick={() => setParentPanelOpen(true)}>
|
||||
🔧
|
||||
</ToolButton>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(!state || library.loading) && <Splash error={library.error} />}
|
||||
@@ -765,6 +800,29 @@ export function App() {
|
||||
);
|
||||
}
|
||||
|
||||
/** One of the small round buttons in the bottom-left corner. */
|
||||
function ToolButton({ label, onClick, children }: { label: string; onClick: () => void; children: ReactNode }) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
style={{
|
||||
width: 32,
|
||||
height: 32,
|
||||
border: "none",
|
||||
borderRadius: 999,
|
||||
cursor: "pointer",
|
||||
background: "oklch(15% 0.03 var(--hue) / .35)",
|
||||
color: "#fff",
|
||||
opacity: 0.5,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** The one fixed round button in each top corner: back (left) and the music/room
|
||||
* toggle (right). Same position and shape everywhere they appear, so "top left" and
|
||||
* "top right" always mean the same thing. */
|
||||
|
||||
@@ -103,6 +103,10 @@ export const api = {
|
||||
/** Someone is at the kiosk: holds off the screen's idle auto-off. */
|
||||
screenActivity: () => post("/screen/activity"),
|
||||
|
||||
/** The parents' countdown: minutes from now, or until a time of day ("HH:MM"). */
|
||||
setTimer: (timer: { minutes: number } | { until: string }) => post("/timer", timer),
|
||||
clearTimer: () => request<void>("/timer", { method: "DELETE" }),
|
||||
|
||||
settings: () => request<Settings>("/settings"),
|
||||
saveSettings: (settings: Settings) =>
|
||||
request<Settings>("/settings", { method: "PUT", body: JSON.stringify(settings) }),
|
||||
|
||||
@@ -90,6 +90,19 @@ export interface PlayerState {
|
||||
volume: number;
|
||||
active_figure: string | null;
|
||||
connected: { firmware: boolean; mqtt: boolean; lirc: boolean };
|
||||
clock: ClockState;
|
||||
}
|
||||
|
||||
/** What the clock overlay shows besides the time. Mirrors `ClockStateOut`. */
|
||||
export interface ClockState {
|
||||
/** `null` when the holiday calendar could not be fetched (weekends are still known). */
|
||||
school_day: boolean | null;
|
||||
/** Why there is no school today: "Wochenende", "Herbstferien", ... */
|
||||
school_day_reason: string | null;
|
||||
/** Today's bus, `null` without school. `time` is "HH:MM". */
|
||||
bus: { time: string; lead_minutes: number } | null;
|
||||
/** The parents' countdown, in wall-clock Unix seconds. */
|
||||
parent_timer: { started_at: number; ends_at: number; ringing: boolean } | null;
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
@@ -106,7 +119,9 @@ export interface Settings {
|
||||
export type ServerMessage =
|
||||
| { type: "state"; state: PlayerState }
|
||||
| { type: "position"; position: number; duration: number }
|
||||
| { type: "library" };
|
||||
| { type: "library" }
|
||||
/** The IR remote's Guide key: show or hide the clock. */
|
||||
| { type: "clock_toggle" };
|
||||
|
||||
export interface HaDevice {
|
||||
entity_id: string;
|
||||
|
||||
187
web/src/components/ClockOverlay.tsx
Normal file
187
web/src/components/ClockOverlay.tsx
Normal file
@@ -0,0 +1,187 @@
|
||||
/** The "Delphin Uhr": a big analog wrist watch over whatever page is showing, with the
|
||||
* countdowns that are running right now beside it - the school bus on school-day
|
||||
* mornings, and the parents' timer. Built from `claude-design/Delphin Uhr.dc.html`,
|
||||
* minus the mascot swimming through the scene (too distracting for a clock you read
|
||||
* at a glance).
|
||||
*
|
||||
* Mounted for as long as the app is, and only hidden: Einfg and the remote's Guide key
|
||||
* have to show it at once, not after a first render. The second ticker only runs while
|
||||
* it is on screen. Any click closes it. */
|
||||
|
||||
import { memo } from "react";
|
||||
|
||||
import type { ClockState } from "../api/types";
|
||||
import { useNow } from "../hooks/useNow";
|
||||
import { activeCountdowns, type Countdown, formatCountdown, handAngles } from "../lib/clock";
|
||||
import { SKIN } from "../lib/skins";
|
||||
import { SHOW_DECORATIVE_ANIMATIONS } from "../lib/theme";
|
||||
import { Drift, type DriftField } from "./Drift";
|
||||
|
||||
const BUBBLES: DriftField = [
|
||||
[5, 14, 0.5, 9, 0],
|
||||
[12, 22, 0.5, 12, -3],
|
||||
[22, 10, 0.5, 8, -6],
|
||||
[48, 16, 0.5, 11, -2],
|
||||
[63, 12, 0.5, 10, -7],
|
||||
[78, 24, 0.5, 14, -5],
|
||||
[88, 12, 0.5, 9, -1],
|
||||
[95, 18, 0.5, 13, -9],
|
||||
];
|
||||
|
||||
/** The four colours every ring of the dial cycles through, starting at 12. */
|
||||
const HUES = ["205", "175", "245", "pink"] as const;
|
||||
|
||||
const CARD_IMAGE: Record<Countdown["kind"], { src: string; alt: string }> = {
|
||||
bus: { src: "/clock/bus.webp", alt: "Bus" },
|
||||
timer: { src: SKIN.mascotWatch, alt: "Timer" },
|
||||
};
|
||||
|
||||
interface Props {
|
||||
visible: boolean;
|
||||
clock: ClockState | null;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function ClockOverlay({ visible, clock, onClose }: Props) {
|
||||
const now = useNow(visible);
|
||||
const countdowns = clock ? activeCountdowns(now, clock) : [];
|
||||
const angles = handAngles(now);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="clock-overlay"
|
||||
hidden={!visible}
|
||||
onClick={onClose}
|
||||
role="dialog"
|
||||
aria-label="Uhr"
|
||||
>
|
||||
{SHOW_DECORATIVE_ANIMATIONS && (
|
||||
<Drift field={BUBBLES} bubbleColor={(alpha) => `oklch(90% 0.02 var(--hue) / ${alpha})`} />
|
||||
)}
|
||||
|
||||
{clock && clock.school_day !== null && <SchoolDayBadge clock={clock} />}
|
||||
|
||||
<div className="clock-watch">
|
||||
<WatchCase />
|
||||
<div className="clock-face">
|
||||
<Dial />
|
||||
<div className="clock-hand clock-hand-hour" style={{ transform: `rotate(${angles.hour}deg)` }}>
|
||||
<div />
|
||||
</div>
|
||||
<div className="clock-hand clock-hand-minute" style={{ transform: `rotate(${angles.minute}deg)` }}>
|
||||
<div />
|
||||
</div>
|
||||
<div className="clock-hand clock-hand-second" style={{ transform: `rotate(${angles.second}deg)` }}>
|
||||
<div />
|
||||
</div>
|
||||
<div className="clock-pin" />
|
||||
<div className="clock-pin-dot" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{countdowns.length > 0 && (
|
||||
<div className="clock-countdowns">
|
||||
{countdowns.map((countdown) => (
|
||||
<CountdownCard key={countdown.kind} countdown={countdown} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SchoolDayBadge({ clock }: { clock: ClockState }) {
|
||||
const text = clock.school_day
|
||||
? "🎒 Schultag"
|
||||
: clock.school_day_reason === "Wochenende"
|
||||
? "🏖️ Wochenende"
|
||||
: `🏖️ Schulfrei${clock.school_day_reason ? ` · ${clock.school_day_reason}` : ""}`;
|
||||
return (
|
||||
<div className="clock-badge" data-school={clock.school_day || undefined}>
|
||||
{text}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CountdownCard({ countdown }: { countdown: Countdown }) {
|
||||
const image = CARD_IMAGE[countdown.kind];
|
||||
return (
|
||||
<div className="clock-card" data-soon={countdown.soon || undefined} data-ringing={countdown.ringing || undefined}>
|
||||
<div className="clock-card-image">
|
||||
<img src={image.src} alt={image.alt} />
|
||||
</div>
|
||||
<div className="clock-card-body">
|
||||
<div className="clock-card-time">{formatCountdown(countdown.remaining)}</div>
|
||||
<div className="clock-card-bar">
|
||||
<div style={{ width: `${(countdown.fraction * 100).toFixed(2)}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Straps and crown buttons: everything outside the round face. Static. */
|
||||
const WatchCase = memo(function WatchCase() {
|
||||
return (
|
||||
<>
|
||||
<div className="clock-strap" data-pos="top-left" />
|
||||
<div className="clock-strap" data-pos="top-right" />
|
||||
<div className="clock-strap" data-pos="bottom-left" />
|
||||
<div className="clock-strap" data-pos="bottom-right" />
|
||||
<div className="clock-button" style={{ transform: "rotate(60deg) translateY(-38vmin)" }} data-hue="pink" />
|
||||
<div className="clock-button" style={{ transform: "rotate(118deg) translateY(-38vmin)" }} data-hue="205" />
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
/** The bezel dots, coloured hour sections, minute track and numbers. Static, so it is
|
||||
* rendered once and never again on a tick. */
|
||||
const Dial = memo(function Dial() {
|
||||
return (
|
||||
<>
|
||||
{Array.from({ length: 48 }, (_, i) => {
|
||||
const angle = i * 7.5;
|
||||
const big = i % 2 === 0;
|
||||
return (
|
||||
<div
|
||||
key={`dot${i}`}
|
||||
className="clock-dot"
|
||||
data-big={big || undefined}
|
||||
data-hue={big ? HUES[(i / 2) % 4] : undefined}
|
||||
style={{ transform: `translate(-50%,-50%) rotate(${angle}deg) translateY(-36.8vmin) rotate(${-angle}deg)` }}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<div className="clock-face-inner" />
|
||||
<div className="clock-sections" />
|
||||
<div className="clock-sections-gaps" />
|
||||
<div className="clock-sections-rim" />
|
||||
<div className="clock-center" />
|
||||
<div className="clock-minute-track" />
|
||||
<div className="clock-minute-ticks" />
|
||||
<div className="clock-minute-ticks-major" />
|
||||
<div className="clock-numbers clock-numbers-minutes">
|
||||
{Array.from({ length: 12 }, (_, i) => (
|
||||
<div key={i} style={{ transform: place(i * 30, 29.5) }}>
|
||||
{i === 0 ? 60 : i * 5}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="clock-numbers clock-numbers-hours">
|
||||
{Array.from({ length: 12 }, (_, i) => {
|
||||
const hour = i + 1;
|
||||
return (
|
||||
<div key={hour} data-hue={HUES[hour % 4]} style={{ transform: place(hour * 30, 22.4) }}>
|
||||
{hour}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
/** Centre an element on the face, then push it `radius` vmin out at `angle`, upright. */
|
||||
function place(angle: number, radius: number): string {
|
||||
return `translate(-50%,-50%) rotate(${angle}deg) translateY(-${radius}vmin) rotate(${-angle}deg)`;
|
||||
}
|
||||
@@ -38,6 +38,7 @@ const SECTIONS: Array<[title: string, rows: Array<[caps: string[], label: string
|
||||
[
|
||||
[["A", "0-9"], "Album auf Fernbedienungs-Taste legen"],
|
||||
[["⇧A", "0-9"], "Nur dieses Lied auf die Taste legen"],
|
||||
[["EINFG"], "Uhr an / aus"],
|
||||
[["ENTF"], "Bildschirm aus / an"],
|
||||
[["F1"], "Diese Hilfe"],
|
||||
[["ESC"], "Schließen / Suche löschen"],
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
/** Parent mode: reachable only via `?parentMode=1`, never from the child-facing UI.
|
||||
* That URL only adds a way in - a 🔧 button on the kiosk and desktop (`ParentPanel`, a
|
||||
* sheet), an "Eltern" tab on a phone (`ParentPage`) - so a parent's tablet or phone can
|
||||
* keep it bookmarked. Both show the same `ParentSettings`, the timer first.
|
||||
*
|
||||
* This hides the settings, it does not protect them - there is no login, and the
|
||||
* endpoints behind it are as open as the rest of the API. That matches the device's
|
||||
@@ -6,10 +9,42 @@
|
||||
* implied.
|
||||
*/
|
||||
|
||||
import type { CSSProperties } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { api } from "../api/client";
|
||||
import type { Settings } from "../api/types";
|
||||
import type { ClockState, Settings } from "../api/types";
|
||||
import { useNow } from "../hooks/useNow";
|
||||
import { busWindow, formatTimeOfDay } from "../lib/clock";
|
||||
|
||||
/** The quick-start buttons, in minutes. */
|
||||
const TIMER_PRESETS = [5, 10, 15, 30] as const;
|
||||
|
||||
const PRIMARY_BUTTON: CSSProperties = {
|
||||
border: "none",
|
||||
cursor: "pointer",
|
||||
background: "var(--accent)",
|
||||
color: "#fff",
|
||||
fontSize: 15,
|
||||
fontWeight: 800,
|
||||
padding: "11px 20px",
|
||||
borderRadius: 999,
|
||||
};
|
||||
|
||||
const SECONDARY_BUTTON: CSSProperties = {
|
||||
...PRIMARY_BUTTON,
|
||||
background: "oklch(88% 0.02 var(--hue))",
|
||||
color: "var(--ink)",
|
||||
};
|
||||
|
||||
const SECTION_TITLE: CSSProperties = { fontSize: 16, fontWeight: 900, color: "var(--ink)" };
|
||||
|
||||
const HINT: CSSProperties = {
|
||||
fontSize: 13,
|
||||
fontWeight: 600,
|
||||
color: "oklch(50% 0.03 var(--hue))",
|
||||
lineHeight: 1.5,
|
||||
};
|
||||
|
||||
/** Every setting that is always there; the screen's auto-off is only sometimes. */
|
||||
type AlwaysSetting = Exclude<keyof Settings, "screen_auto_off_minutes">;
|
||||
@@ -64,7 +99,226 @@ function NumberField({
|
||||
);
|
||||
}
|
||||
|
||||
export function ParentPanel({ onClose }: { onClose: () => void }) {
|
||||
/** The kiosk's and a desktop's way in: a sheet over the app. */
|
||||
export function ParentPanel({ clock, onClose }: { clock: ClockState | null; onClose: () => void }) {
|
||||
return (
|
||||
<div className="overlay" style={{ zIndex: 9, background: "oklch(15% 0.03 var(--hue) / .75)" }}>
|
||||
<div className="sheet" style={{ padding: 28, width: 460, maxHeight: "100%", overflow: "auto" }}>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 12 }}>
|
||||
<div style={{ fontSize: 20, fontWeight: 900, color: "var(--ink)", flex: 1 }}>
|
||||
🔧 Eltern-Einstellungen
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
aria-label="Schließen"
|
||||
style={{
|
||||
border: "none",
|
||||
cursor: "pointer",
|
||||
background: "oklch(88% 0.02 var(--hue))",
|
||||
color: "var(--ink)",
|
||||
fontSize: 18,
|
||||
fontWeight: 900,
|
||||
width: 36,
|
||||
height: 36,
|
||||
borderRadius: 999,
|
||||
}}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
<div style={{ marginTop: 18 }}>
|
||||
<ParentSettings clock={clock} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A phone's way in: the "Eltern" tab, as a page of its own above the dock. A sheet
|
||||
* on a small screen is a page with a worse close button, so it is just a page. */
|
||||
export function ParentPage({ clock, onOpenPerf }: { clock: ClockState | null; onOpenPerf?: () => void }) {
|
||||
return (
|
||||
<div className="m-page">
|
||||
<div className="m-scroll" style={{ padding: "0 var(--m-gutter) calc(var(--m-dock-clearance) + 24px)" }}>
|
||||
<div
|
||||
style={{
|
||||
padding: "calc(16px + env(safe-area-inset-top)) 0 16px",
|
||||
fontSize: 24,
|
||||
fontWeight: 900,
|
||||
color: "var(--paper)",
|
||||
}}
|
||||
>
|
||||
🔧 Eltern
|
||||
</div>
|
||||
<div className="sheet" style={{ padding: 20 }}>
|
||||
<ParentSettings clock={clock} phone />
|
||||
</div>
|
||||
{onOpenPerf && (
|
||||
<button
|
||||
onClick={onOpenPerf}
|
||||
style={{ ...SECONDARY_BUTTON, width: "100%", marginTop: 16, minHeight: 48 }}
|
||||
>
|
||||
⚡ Leistung
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Everything parent mode shows, timer first: the timer is what a parent opens it for
|
||||
* most, and it works on its own, without waiting for the settings to load. */
|
||||
export function ParentSettings({ clock, phone = false }: { clock: ClockState | null; phone?: boolean }) {
|
||||
return (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
|
||||
<TimerSection clock={clock} phone={phone} />
|
||||
<div style={{ height: 1, background: "oklch(88% 0.02 var(--hue))" }} />
|
||||
<DeviceSettings />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TimerSection({ clock, phone }: { clock: ClockState | null; phone: boolean }) {
|
||||
const [until, setUntil] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const timer = clock?.parent_timer ?? null;
|
||||
const now = useNow(timer !== null);
|
||||
|
||||
const start = async (request: { minutes: number } | { until: string }) => {
|
||||
setError(null);
|
||||
try {
|
||||
await api.setTimer(request);
|
||||
} catch {
|
||||
setError("Timer konnte nicht gestartet werden.");
|
||||
}
|
||||
};
|
||||
|
||||
const stop = async () => {
|
||||
setError(null);
|
||||
try {
|
||||
await api.clearTimer();
|
||||
} catch {
|
||||
setError("Timer konnte nicht gestoppt werden.");
|
||||
}
|
||||
};
|
||||
|
||||
const remaining = timer ? Math.max(0, Math.ceil(timer.ends_at - now.getTime() / 1000)) : 0;
|
||||
const buttonHeight = phone ? 52 : 44;
|
||||
|
||||
return (
|
||||
<section style={{ display: "flex", flexDirection: "column", gap: 12 }}>
|
||||
<div style={SECTION_TITLE}>🐬 Delfin-Timer</div>
|
||||
|
||||
{timer && (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: 12,
|
||||
padding: "12px 14px",
|
||||
borderRadius: 16,
|
||||
background: timer.ringing ? "oklch(90% 0.08 345)" : "oklch(94% 0.03 var(--hue))",
|
||||
}}
|
||||
>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 28,
|
||||
fontWeight: 900,
|
||||
fontVariantNumeric: "tabular-nums",
|
||||
color: "var(--ink)",
|
||||
}}
|
||||
>
|
||||
{timer.ringing ? "Zeit um!" : `noch ${Math.ceil(remaining / 60)} Min`}
|
||||
</div>
|
||||
<div style={HINT}>
|
||||
{timer.ringing ? "Klingelt gerade" : `läuft bis ${formatTimeOfDay(timer.ends_at)} Uhr`}
|
||||
</div>
|
||||
</div>
|
||||
<button onClick={() => void stop()} style={{ ...PRIMARY_BUTTON, minHeight: buttonHeight }}>
|
||||
{timer.ringing ? "Ausschalten" : "Stoppen"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: phone ? "1fr 1fr" : "repeat(4, 1fr)",
|
||||
gap: 8,
|
||||
}}
|
||||
>
|
||||
{TIMER_PRESETS.map((minutes) => (
|
||||
<button
|
||||
key={minutes}
|
||||
onClick={() => void start({ minutes })}
|
||||
style={{ ...SECONDARY_BUTTON, minHeight: buttonHeight, padding: "8px 0", fontSize: 16 }}
|
||||
>
|
||||
{minutes} Min
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (until) void start({ until });
|
||||
}}
|
||||
style={{ display: "flex", gap: 8, flexWrap: phone ? "wrap" : "nowrap" }}
|
||||
>
|
||||
<input
|
||||
type="time"
|
||||
aria-label="Bis wann"
|
||||
required
|
||||
value={until}
|
||||
onChange={(event) => setUntil(event.target.value)}
|
||||
style={{
|
||||
flex: 1,
|
||||
minWidth: phone ? "100%" : 0,
|
||||
minHeight: buttonHeight,
|
||||
boxSizing: "border-box",
|
||||
padding: "8px 12px",
|
||||
borderRadius: 12,
|
||||
border: "2px solid oklch(85% 0.02 var(--hue))",
|
||||
fontSize: 18,
|
||||
fontWeight: 800,
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!until}
|
||||
style={{
|
||||
...PRIMARY_BUTTON,
|
||||
minHeight: buttonHeight,
|
||||
flex: phone ? "1 1 100%" : "none",
|
||||
opacity: until ? 1 : 0.5,
|
||||
}}
|
||||
>
|
||||
{until ? `Bis ${until.replace(/^0/, "")} Uhr` : "Bis … starten"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div style={HINT}>{schoolDayLine(clock)}</div>
|
||||
|
||||
{error && <div style={{ fontSize: 14, fontWeight: 700, color: "oklch(55% 0.18 30)" }}>{error}</div>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function schoolDayLine(clock: ClockState | null): string {
|
||||
if (!clock) return "";
|
||||
if (clock.school_day === false) {
|
||||
return `🏖️ Heute schulfrei${clock.school_day_reason ? ` (${clock.school_day_reason})` : ""} – kein Bus-Timer.`;
|
||||
}
|
||||
const bus = clock.bus ? busWindow(clock.bus) : null;
|
||||
const busText = bus ? ` – Bus-Timer ${bus.from}–${bus.to} Uhr.` : ".";
|
||||
return clock.school_day
|
||||
? `🎒 Heute ist Schultag${busText}`
|
||||
: `Ferienkalender nicht erreichbar – Schultag angenommen${busText}`;
|
||||
}
|
||||
|
||||
/** The device settings that live in `config.yml`. */
|
||||
function DeviceSettings() {
|
||||
const [settings, setSettings] = useState<Settings | null>(null);
|
||||
const [status, setStatus] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -98,35 +352,12 @@ export function ParentPanel({ onClose }: { onClose: () => void }) {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="overlay" style={{ zIndex: 6, background: "oklch(15% 0.03 var(--hue) / .75)" }}>
|
||||
<div className="sheet" style={{ padding: 28, width: 460, maxHeight: "100%", overflow: "auto" }}>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: 12 }}>
|
||||
<div style={{ fontSize: 20, fontWeight: 900, color: "var(--ink)", flex: 1 }}>
|
||||
🔧 Eltern-Einstellungen
|
||||
</div>
|
||||
<button
|
||||
onClick={onClose}
|
||||
aria-label="Schließen"
|
||||
style={{
|
||||
border: "none",
|
||||
cursor: "pointer",
|
||||
background: "oklch(88% 0.02 var(--hue))",
|
||||
color: "var(--ink)",
|
||||
fontSize: 18,
|
||||
fontWeight: 900,
|
||||
width: 36,
|
||||
height: 36,
|
||||
borderRadius: 999,
|
||||
}}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<section style={{ display: "flex", flexDirection: "column", gap: 14 }}>
|
||||
<div style={SECTION_TITLE}>⚙️ Gerät</div>
|
||||
{settings === null ? (
|
||||
<div style={{ marginTop: 18, color: "oklch(45% 0.03 var(--hue))" }}>Wird geladen …</div>
|
||||
<div style={{ color: "oklch(45% 0.03 var(--hue))" }}>{status ?? "Wird geladen …"}</div>
|
||||
) : (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 18 }}>
|
||||
<>
|
||||
{FIELDS.map(([key, label, hint, min, max, step]) => (
|
||||
<NumberField
|
||||
key={key}
|
||||
@@ -153,60 +384,23 @@ export function ParentPanel({ onClose }: { onClose: () => void }) {
|
||||
/>
|
||||
)}
|
||||
|
||||
<div style={{ display: "flex", gap: 10, marginTop: 6 }}>
|
||||
<button
|
||||
onClick={() => void save()}
|
||||
disabled={busy}
|
||||
style={{
|
||||
border: "none",
|
||||
cursor: "pointer",
|
||||
background: "var(--accent)",
|
||||
color: "#fff",
|
||||
fontSize: 15,
|
||||
fontWeight: 800,
|
||||
padding: "11px 20px",
|
||||
borderRadius: 999,
|
||||
}}
|
||||
>
|
||||
<div style={{ display: "flex", gap: 10, marginTop: 6, flexWrap: "wrap" }}>
|
||||
<button onClick={() => void save()} disabled={busy} style={PRIMARY_BUTTON}>
|
||||
Speichern
|
||||
</button>
|
||||
<button
|
||||
onClick={() => void rescan()}
|
||||
style={{
|
||||
border: "none",
|
||||
cursor: "pointer",
|
||||
background: "oklch(88% 0.02 var(--hue))",
|
||||
color: "var(--ink)",
|
||||
fontSize: 15,
|
||||
fontWeight: 800,
|
||||
padding: "11px 20px",
|
||||
borderRadius: 999,
|
||||
}}
|
||||
>
|
||||
<button onClick={() => void rescan()} style={SECONDARY_BUTTON}>
|
||||
Bibliothek neu einlesen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
fontSize: 12,
|
||||
fontWeight: 600,
|
||||
color: "oklch(50% 0.03 var(--hue))",
|
||||
lineHeight: 1.5,
|
||||
}}
|
||||
>
|
||||
<div style={{ ...HINT, fontSize: 12 }}>
|
||||
Speichern schreibt in die <code>config.yml</code> auf dem Gerät. Die neue
|
||||
Obergrenze gilt sofort, ohne Neustart.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status && (
|
||||
<div style={{ marginTop: 14, fontSize: 14, fontWeight: 700, color: "var(--ink)" }}>
|
||||
{status}
|
||||
</div>
|
||||
{status && <div style={{ fontSize: 14, fontWeight: 700, color: "var(--ink)" }}>{status}</div>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,6 +22,9 @@ interface Props {
|
||||
page: Page;
|
||||
onSelectPage: (page: Page) => void;
|
||||
showRoom: boolean;
|
||||
/** `?parentMode=1`: parent mode is a tab here, in thumb reach, rather than a
|
||||
* floating button. */
|
||||
showParents: boolean;
|
||||
searching: boolean;
|
||||
typed: string;
|
||||
onOpenSearch: () => void;
|
||||
@@ -38,12 +41,14 @@ interface Props {
|
||||
const TABS: { page: Page; label: string }[] = [
|
||||
{ page: "music", label: "Musik" },
|
||||
{ page: "room", label: "Zimmer" },
|
||||
{ page: "parents", label: "Eltern" },
|
||||
];
|
||||
|
||||
export function MobileDock({
|
||||
page,
|
||||
onSelectPage,
|
||||
showRoom,
|
||||
showParents,
|
||||
searching,
|
||||
typed,
|
||||
onOpenSearch,
|
||||
@@ -57,7 +62,9 @@ export function MobileDock({
|
||||
}: Props) {
|
||||
const keyboardInset = useKeyboardInset();
|
||||
const input = useRef<HTMLInputElement | null>(null);
|
||||
const tabs = TABS.filter((tab) => tab.page !== "room" || showRoom);
|
||||
const tabs = TABS.filter(
|
||||
(tab) => (tab.page !== "room" || showRoom) && (tab.page !== "parents" || showParents),
|
||||
);
|
||||
const canSearch = page === "music";
|
||||
|
||||
return (
|
||||
|
||||
21
web/src/hooks/useNow.ts
Normal file
21
web/src/hooks/useNow.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
/** The current time, ticking just after each full second while `running` - so a
|
||||
* second hand or a countdown never skips or shows a second twice. Stopped, it keeps
|
||||
* the last value and costs nothing. */
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export function useNow(running = true): Date {
|
||||
const [now, setNow] = useState(() => new Date());
|
||||
useEffect(() => {
|
||||
if (!running) return;
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const tick = () => {
|
||||
const date = new Date();
|
||||
setNow(date);
|
||||
timer = setTimeout(tick, 1000 - date.getMilliseconds() + 5);
|
||||
};
|
||||
tick();
|
||||
return () => clearTimeout(timer);
|
||||
}, [running]);
|
||||
return now;
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
State arrives over a websocket that only pushes: every command goes out as a plain
|
||||
POST. A reconnect reseeds from `GET /api/state` rather than assuming the UI's copy is
|
||||
still right, and `onLibraryChanged` fires when a rescan has finished.
|
||||
still right, and `onLibraryChanged` fires when a rescan has finished. `onClockToggle`
|
||||
fires when the IR remote's Guide key asks for the clock.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
@@ -24,13 +25,18 @@ export interface Connection {
|
||||
optimistic: (patch: Partial<PlayerState>) => void;
|
||||
}
|
||||
|
||||
export function usePlayerState(onLibraryChanged: () => void): Connection {
|
||||
export function usePlayerState(
|
||||
onLibraryChanged: () => void,
|
||||
onClockToggle: () => void = () => {},
|
||||
): Connection {
|
||||
const [state, setState] = useState<PlayerState | null>(null);
|
||||
const [online, setOnline] = useState(false);
|
||||
|
||||
// Kept in a ref so reconnecting never re-runs the effect that owns the socket.
|
||||
const libraryChanged = useRef(onLibraryChanged);
|
||||
libraryChanged.current = onLibraryChanged;
|
||||
const clockToggle = useRef(onClockToggle);
|
||||
clockToggle.current = onClockToggle;
|
||||
|
||||
useEffect(() => {
|
||||
let socket: WebSocket | null = null;
|
||||
@@ -68,6 +74,8 @@ export function usePlayerState(onLibraryChanged: () => void): Connection {
|
||||
);
|
||||
} else if (message.type === "library") {
|
||||
libraryChanged.current();
|
||||
} else if (message.type === "clock_toggle") {
|
||||
clockToggle.current();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
112
web/src/lib/__tests__/clock.test.ts
Normal file
112
web/src/lib/__tests__/clock.test.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { ClockState } from "../../api/types";
|
||||
import { activeCountdowns, busWindow, formatCountdown, handAngles } from "../clock";
|
||||
|
||||
const BUS: ClockState = {
|
||||
school_day: true,
|
||||
school_day_reason: null,
|
||||
bus: { time: "07:25", lead_minutes: 60 },
|
||||
parent_timer: null,
|
||||
};
|
||||
|
||||
const at = (hours: number, minutes: number, seconds = 0) => new Date(2026, 9, 5, hours, minutes, seconds);
|
||||
const unix = (date: Date) => date.getTime() / 1000;
|
||||
|
||||
describe("handAngles", () => {
|
||||
it("points every hand at 12 at midnight", () => {
|
||||
expect(handAngles(at(0, 0))).toEqual({ hour: 0, minute: 0, second: 0 });
|
||||
});
|
||||
|
||||
it("creeps the hour hand between the numbers", () => {
|
||||
expect(handAngles(at(3, 30, 15))).toEqual({ hour: 105.125, minute: 181.5, second: 90 });
|
||||
});
|
||||
|
||||
it("goes round twice a day", () => {
|
||||
expect(handAngles(at(15, 0)).hour).toBe(90);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the bus countdown", () => {
|
||||
it("is hidden until an hour before the bus", () => {
|
||||
expect(activeCountdowns(at(6, 24, 59), BUS)).toEqual([]);
|
||||
});
|
||||
|
||||
it("shows for the hour before the bus", () => {
|
||||
const [bus] = activeCountdowns(at(6, 25), BUS);
|
||||
expect(bus).toMatchObject({ kind: "bus", remaining: 3600, fraction: 1, soon: false });
|
||||
});
|
||||
|
||||
it("turns pink for the last ten minutes", () => {
|
||||
expect(activeCountdowns(at(7, 15), BUS)[0]).toMatchObject({ remaining: 600, soon: true });
|
||||
});
|
||||
|
||||
it("is gone the moment the bus leaves", () => {
|
||||
expect(activeCountdowns(at(7, 25), BUS)).toEqual([]);
|
||||
});
|
||||
|
||||
it("is not there without school", () => {
|
||||
expect(activeCountdowns(at(7, 0), { ...BUS, school_day: false, bus: null })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the parents' timer", () => {
|
||||
const started = at(18, 50);
|
||||
const timer = (ringing = false): ClockState => ({
|
||||
...BUS,
|
||||
parent_timer: { started_at: unix(started), ends_at: unix(at(19, 5)), ringing },
|
||||
});
|
||||
|
||||
it("counts down from when it was started", () => {
|
||||
expect(activeCountdowns(at(18, 50), timer())[0]).toMatchObject({
|
||||
kind: "timer",
|
||||
remaining: 900,
|
||||
fraction: 1,
|
||||
});
|
||||
expect(activeCountdowns(at(19, 0), timer())[0]).toMatchObject({ remaining: 300, soon: true });
|
||||
});
|
||||
|
||||
it("waits at zero for the ringing frame instead of vanishing", () => {
|
||||
expect(activeCountdowns(at(19, 5, 2), timer())[0]).toMatchObject({ remaining: 0 });
|
||||
});
|
||||
|
||||
it("shows zero while ringing, however late", () => {
|
||||
expect(activeCountdowns(at(19, 6), timer(true))[0]).toMatchObject({ remaining: 0, ringing: true });
|
||||
});
|
||||
|
||||
it("is gone when the backend never says it rang", () => {
|
||||
expect(activeCountdowns(at(19, 6), timer())).toEqual([]);
|
||||
});
|
||||
|
||||
it("sorts the one ending first on top", () => {
|
||||
const morning: ClockState = {
|
||||
...BUS,
|
||||
parent_timer: { started_at: unix(at(6, 50)), ends_at: unix(at(7, 0)), ringing: false },
|
||||
};
|
||||
expect(activeCountdowns(at(6, 55), morning).map((c) => c.kind)).toEqual(["timer", "bus"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("busWindow", () => {
|
||||
it("states the window without leading zeros", () => {
|
||||
expect(busWindow({ time: "07:25", lead_minutes: 60 })).toEqual({ from: "6:25", to: "7:25" });
|
||||
});
|
||||
|
||||
it("wraps back past midnight", () => {
|
||||
expect(busWindow({ time: "00:10", lead_minutes: 30 })).toEqual({ from: "23:40", to: "0:10" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatCountdown", () => {
|
||||
it("shows hours and minutes, rounded up", () => {
|
||||
expect(formatCountdown(900)).toBe("00:15");
|
||||
expect(formatCountdown(899)).toBe("00:15");
|
||||
expect(formatCountdown(61)).toBe("00:02");
|
||||
expect(formatCountdown(3600)).toBe("01:00");
|
||||
});
|
||||
|
||||
it("stops at zero", () => {
|
||||
expect(formatCountdown(0)).toBe("00:00");
|
||||
expect(formatCountdown(-3)).toBe("00:00");
|
||||
});
|
||||
});
|
||||
@@ -521,3 +521,31 @@ describe("Del", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Einfg", () => {
|
||||
it("toggles the clock, on every page", () => {
|
||||
for (const page of ["music", "room", "typing", "parents"] as const) {
|
||||
expect(press("Insert", { ...initialUiState, page })).toContainEqual({
|
||||
type: "ui",
|
||||
patch: { showClock: true },
|
||||
});
|
||||
expect(press("Insert", { ...initialUiState, page, showClock: true })).toContainEqual({
|
||||
type: "ui",
|
||||
patch: { showClock: false },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("is closed by Esc before anything else", () => {
|
||||
const ui = { ...initialUiState, view: "play" as const, showClock: true };
|
||||
expect(press("Escape", ui)).toEqual([{ type: "ui", patch: { showClock: false } }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the parents page", () => {
|
||||
it("ignores browse keys and escapes back to music", () => {
|
||||
const ui = { ...initialUiState, page: "parents" as const };
|
||||
expect(press("x", ui)).toEqual([]);
|
||||
expect(press("Escape", ui)).toEqual([{ type: "ui", patch: { page: "music" } }]);
|
||||
});
|
||||
});
|
||||
|
||||
104
web/src/lib/clock.ts
Normal file
104
web/src/lib/clock.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
/** The clock overlay's arithmetic, kept pure so it is tested without a DOM: where the
|
||||
* hands point, and which countdowns show at a given moment.
|
||||
*
|
||||
* The backend decides *whether* there is a bus today (school days only) and owns the
|
||||
* parents' timer; this only places them on the browser's own clock. */
|
||||
|
||||
import type { ClockState } from "../api/types";
|
||||
|
||||
export interface HandAngles {
|
||||
hour: number;
|
||||
minute: number;
|
||||
second: number;
|
||||
}
|
||||
|
||||
/** Degrees clockwise from 12, each hand moving continuously - the hour hand creeps
|
||||
* between numbers like a real one. */
|
||||
export function handAngles(date: Date): HandAngles {
|
||||
const seconds = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds();
|
||||
return {
|
||||
hour: (seconds / 120) % 360,
|
||||
minute: (seconds / 10) % 360,
|
||||
second: (date.getSeconds() * 6) % 360,
|
||||
};
|
||||
}
|
||||
|
||||
export type CountdownKind = "bus" | "timer";
|
||||
|
||||
export interface Countdown {
|
||||
kind: CountdownKind;
|
||||
/** Whole seconds to go, never below 0. */
|
||||
remaining: number;
|
||||
/** Share of the countdown still to go, 1 at the start and 0 at the end. */
|
||||
fraction: number;
|
||||
/** The last ten minutes: the number and the bar turn pink. */
|
||||
soon: boolean;
|
||||
/** The parents' timer ran out and is chiming. */
|
||||
ringing: boolean;
|
||||
}
|
||||
|
||||
const SOON_SECONDS = 10 * 60;
|
||||
const RINGING_GRACE_SECONDS = 5;
|
||||
|
||||
/** Every countdown that should show at `now`, the one ending first on top. */
|
||||
export function activeCountdowns(now: Date, clock: ClockState): Countdown[] {
|
||||
const out: Countdown[] = [];
|
||||
const nowSeconds = now.getTime() / 1000;
|
||||
|
||||
if (clock.bus) {
|
||||
const [hours = 0, minutes = 0] = clock.bus.time.split(":").map(Number);
|
||||
const target = new Date(now);
|
||||
target.setHours(hours, minutes, 0, 0);
|
||||
const remaining = target.getTime() / 1000 - nowSeconds;
|
||||
const lead = clock.bus.lead_minutes * 60;
|
||||
if (remaining > 0 && remaining <= lead) {
|
||||
out.push(countdown("bus", remaining, lead, false));
|
||||
}
|
||||
}
|
||||
|
||||
const timer = clock.parent_timer;
|
||||
if (timer) {
|
||||
const remaining = timer.ends_at - nowSeconds;
|
||||
// The backend says when it rings; until that frame arrives, a timer at 0 waits at
|
||||
// 0 for a few seconds rather than vanishing for a moment.
|
||||
if (timer.ringing || remaining > -RINGING_GRACE_SECONDS) {
|
||||
out.push(countdown("timer", remaining, timer.ends_at - timer.started_at, timer.ringing));
|
||||
}
|
||||
}
|
||||
|
||||
return out.sort((a, b) => a.remaining - b.remaining);
|
||||
}
|
||||
|
||||
function countdown(kind: CountdownKind, remaining: number, total: number, ringing: boolean): Countdown {
|
||||
const left = ringing ? 0 : Math.max(0, Math.ceil(remaining));
|
||||
return {
|
||||
kind,
|
||||
remaining: left,
|
||||
fraction: total > 0 ? Math.max(0, Math.min(1, left / total)) : 0,
|
||||
soon: ringing || left <= SOON_SECONDS,
|
||||
ringing,
|
||||
};
|
||||
}
|
||||
|
||||
/** Hours and minutes to go, rounded up, as the design has it: "00:15" for a quarter
|
||||
* of an hour. Never minutes and seconds - "14:44" reads as a time of day. */
|
||||
export function formatCountdown(seconds: number): string {
|
||||
const minutes = Math.max(0, Math.ceil(seconds / 60));
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
return `${pad(Math.floor(minutes / 60))}:${pad(minutes % 60)}`;
|
||||
}
|
||||
|
||||
/** "19:30" from Unix seconds, in the browser's time zone. */
|
||||
export function formatTimeOfDay(unixSeconds: number): string {
|
||||
const date = new Date(unixSeconds * 1000);
|
||||
return `${date.getHours()}:${String(date.getMinutes()).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/** The bus countdown's window as "6:25" and "7:25", for parent mode to state. */
|
||||
export function busWindow(bus: { time: string; lead_minutes: number }): { from: string; to: string } {
|
||||
const [hours = 0, minutes = 0] = bus.time.split(":").map(Number);
|
||||
const end = hours * 60 + minutes;
|
||||
const start = (((end - bus.lead_minutes) % 1440) + 1440) % 1440;
|
||||
const show = (total: number) => `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
|
||||
return { from: show(start), to: show(end) };
|
||||
}
|
||||
@@ -28,13 +28,15 @@ export interface UiState {
|
||||
shelfRow: number;
|
||||
/** Which top-level page is showing. Orthogonal to `view`/`search`/`group`/… below,
|
||||
* so switching pages and back leaves the music side exactly as it was. */
|
||||
page: "music" | "room" | "typing";
|
||||
page: "music" | "room" | "typing" | "parents";
|
||||
view: "browse" | "play";
|
||||
openAlbumId: string | null;
|
||||
/** Which track is highlighted in the open album's track list. Only meaningful while
|
||||
* `openAlbumId` is set; reset to a sensible value each time a modal opens. */
|
||||
modalTrackIndex: number;
|
||||
showHelp: boolean;
|
||||
/** The clock overlay, over whichever page is showing. */
|
||||
showClock: boolean;
|
||||
cols: number;
|
||||
/** Armed on the play screen: the next digit assigns what's playing to that remote key
|
||||
* instead of doing whatever it would normally do. `a` arms "album" (the whole album
|
||||
@@ -55,6 +57,7 @@ export const initialUiState: UiState = {
|
||||
openAlbumId: null,
|
||||
modalTrackIndex: 0,
|
||||
showHelp: false,
|
||||
showClock: false,
|
||||
cols: 4,
|
||||
assignPending: null,
|
||||
};
|
||||
@@ -192,13 +195,16 @@ export function browseBackActions(state: UiState): Action[] {
|
||||
|
||||
/** ESC peels one layer off at a time rather than dumping you back at the top. */
|
||||
function escape(state: UiState): Action[] {
|
||||
if (state.showClock) {
|
||||
return [{ type: "ui", patch: { showClock: false } }];
|
||||
}
|
||||
if (state.assignPending) {
|
||||
return [{ type: "ui", patch: { assignPending: null } }];
|
||||
}
|
||||
if (state.showHelp || state.openAlbumId !== null) {
|
||||
return [{ type: "ui", patch: { showHelp: false, openAlbumId: null } }];
|
||||
}
|
||||
if (state.page === "room") {
|
||||
if (state.page === "room" || state.page === "parents") {
|
||||
return [{ type: "ui", patch: { page: "music" } }];
|
||||
}
|
||||
if (state.view === "play") {
|
||||
@@ -263,6 +269,12 @@ export function handleKey(
|
||||
// another room.
|
||||
if (key === "Delete" && !event.ctrlKey && !event.metaKey) return [{ type: "screen" }];
|
||||
|
||||
// Einfg, right next to it: the clock, over whatever is on screen - the typing tab
|
||||
// included, like Del, since no lesson drills it either.
|
||||
if (key === "Insert" && !event.ctrlKey && !event.metaKey) {
|
||||
return [{ type: "pop", freq: 520 }, { type: "ui", patch: { showClock: !state.showClock } }];
|
||||
}
|
||||
|
||||
// The typing tab is a second app mounted alongside this one (TippenApp.tsx) with its
|
||||
// own complete keyboard handling, including its own Escape/F1 bindings. It must own
|
||||
// every key while active - even Shift+media and Space below, which would otherwise
|
||||
@@ -299,11 +311,11 @@ export function handleKey(
|
||||
return [{ type: "pop", freq: 420 }, { type: "remote", digit: key }];
|
||||
}
|
||||
|
||||
// The room page has no browse hierarchy of its own - only ESC (handled below) and
|
||||
// the global transport above (Shift+media, Space) make sense there. Everything else
|
||||
// would otherwise mutate the hidden music state without anything on screen to show
|
||||
// for it.
|
||||
if (state.page === "room" && key !== "Escape") {
|
||||
// The room and parents pages have no browse hierarchy of their own - only ESC
|
||||
// (handled below) and the global transport above (Shift+media, Space) make sense
|
||||
// there. Everything else would otherwise mutate the hidden music state without
|
||||
// anything on screen to show for it.
|
||||
if ((state.page === "room" || state.page === "parents") && key !== "Escape") {
|
||||
return [];
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ export const DINOSAUR: Skin = {
|
||||
mascotName: "Der Dino",
|
||||
mascot: "/dinosaur-mascot.png",
|
||||
mascotRemote: "/dinosaur-remote.png",
|
||||
// No drawing with a watch yet; the plain mascot stands in.
|
||||
mascotWatch: "/dinosaur-mascot.png",
|
||||
mascotFacesLeft: true,
|
||||
mascotMotion: "walk",
|
||||
drift: "leaves",
|
||||
|
||||
@@ -9,6 +9,7 @@ export const DOLPHIN: Skin = {
|
||||
mascotName: "Der Delphin",
|
||||
mascot: "/dolphin-mascot.png",
|
||||
mascotRemote: "/dolphin-remote.png",
|
||||
mascotWatch: "/clock/dolphin-watch.webp",
|
||||
mascotFacesLeft: false,
|
||||
mascotMotion: "swim",
|
||||
drift: "bubbles",
|
||||
|
||||
@@ -27,6 +27,8 @@ export interface Skin {
|
||||
mascot: string;
|
||||
/** The mascot holding a remote, for "Mein Zimmer". */
|
||||
mascotRemote: string;
|
||||
/** The mascot with a watch: the clock overlay's card for the parents' timer. */
|
||||
mascotWatch: string;
|
||||
/** The play view's swimming mascot is animated assuming it faces right; a drawing
|
||||
* that faces left is mirrored so it looks where it is going. */
|
||||
mascotFacesLeft: boolean;
|
||||
|
||||
@@ -113,12 +113,14 @@ export const PAGE_ICON: Record<UiState["page"], string> = {
|
||||
music: "♪",
|
||||
room: "💡",
|
||||
typing: "⌨️",
|
||||
parents: "🔧",
|
||||
};
|
||||
|
||||
export const PAGE_LABEL: Record<UiState["page"], string> = {
|
||||
music: "Musik",
|
||||
room: "Mein Zimmer",
|
||||
typing: "Tippen",
|
||||
parents: "Eltern",
|
||||
};
|
||||
|
||||
/** A shelf/row's frosted background and border, tinted with its group's hue - or,
|
||||
|
||||
@@ -9,6 +9,7 @@ import "./styles/app.css";
|
||||
import "./styles/mobile.css";
|
||||
import "./styles/room.css";
|
||||
import "./styles/tippen.css";
|
||||
import "./styles/clock.css";
|
||||
|
||||
// Before the first render, so nothing ever paints in the wrong skin's colours.
|
||||
applySkin();
|
||||
|
||||
533
web/src/styles/clock.css
Normal file
533
web/src/styles/clock.css
Normal file
@@ -0,0 +1,533 @@
|
||||
/* The clock overlay (ClockOverlay.tsx), ported from `claude-design/Delphin Uhr.dc.html`.
|
||||
Sized in vmin like the design, so the same watch fills a 1080p kiosk and a phone held
|
||||
upright. */
|
||||
|
||||
.clock-overlay {
|
||||
--clock-ink: oklch(28% 0.04 220);
|
||||
--clock-pink: oklch(70% 0.16 340);
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 8;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6vmin;
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
oklch(55% 0.07 var(--hue)) 0%,
|
||||
oklch(38% 0.06 var(--hue)) 45%,
|
||||
oklch(20% 0.045 var(--hue)) 100%
|
||||
);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
/* `display: flex` above would otherwise beat the `hidden` attribute. */
|
||||
.clock-overlay[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Upright screens: the countdowns go under the watch instead of beside it. */
|
||||
@media (orientation: portrait) {
|
||||
.clock-overlay {
|
||||
flex-direction: column;
|
||||
gap: 4vmin;
|
||||
}
|
||||
}
|
||||
|
||||
.clock-badge {
|
||||
position: absolute;
|
||||
top: calc(18px + env(safe-area-inset-top));
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
padding: 1.2vmin 3vmin;
|
||||
border-radius: 999px;
|
||||
font-size: max(16px, 3vmin);
|
||||
font-weight: 900;
|
||||
white-space: nowrap;
|
||||
color: var(--clock-ink);
|
||||
background: oklch(97% 0.01 var(--hue) / 0.75);
|
||||
box-shadow: 0 1vmin 3vmin oklch(15% 0.05 var(--hue) / 0.3);
|
||||
}
|
||||
|
||||
.clock-badge[data-school] {
|
||||
background: oklch(92% 0.08 85 / 0.92);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- the watch */
|
||||
|
||||
.clock-watch {
|
||||
position: relative;
|
||||
flex: none;
|
||||
width: 78vmin;
|
||||
height: 96vmin;
|
||||
filter: drop-shadow(0 3vmin 5vmin oklch(15% 0.05 210 / 0.5));
|
||||
}
|
||||
|
||||
.clock-strap {
|
||||
position: absolute;
|
||||
width: 15vmin;
|
||||
height: 24vmin;
|
||||
box-sizing: border-box;
|
||||
border: 0.55vmin solid var(--clock-ink);
|
||||
--strap: oklch(70% 0.16 340);
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
var(--strap) 0%,
|
||||
var(--strap) 70%,
|
||||
oklch(from var(--strap) calc(l - 0.08) c h) 100%
|
||||
);
|
||||
}
|
||||
|
||||
.clock-strap[data-pos^="top"] {
|
||||
top: 0;
|
||||
border-radius: 2.4vmin 2.4vmin 0.8vmin 0.8vmin;
|
||||
transform-origin: 50% 100%;
|
||||
}
|
||||
|
||||
.clock-strap[data-pos^="bottom"] {
|
||||
bottom: 0;
|
||||
border-radius: 0.8vmin 0.8vmin 2.4vmin 2.4vmin;
|
||||
transform-origin: 50% 0%;
|
||||
}
|
||||
|
||||
.clock-strap[data-pos="top-left"] {
|
||||
left: 16vmin;
|
||||
transform: perspective(40vmin) rotateX(10deg) rotate(-8deg);
|
||||
}
|
||||
|
||||
.clock-strap[data-pos="top-right"] {
|
||||
right: 16vmin;
|
||||
--strap: oklch(66% 0.12 205);
|
||||
transform: perspective(40vmin) rotateX(10deg) rotate(8deg);
|
||||
}
|
||||
|
||||
.clock-strap[data-pos="bottom-left"] {
|
||||
left: 16vmin;
|
||||
--strap: oklch(64% 0.11 175);
|
||||
transform: perspective(40vmin) rotateX(-10deg) rotate(8deg);
|
||||
}
|
||||
|
||||
.clock-strap[data-pos="bottom-right"] {
|
||||
right: 16vmin;
|
||||
--strap: oklch(58% 0.12 245);
|
||||
transform: perspective(40vmin) rotateX(-10deg) rotate(-8deg);
|
||||
}
|
||||
|
||||
.clock-button {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: 6vmin;
|
||||
height: 10vmin;
|
||||
margin: -5vmin 0 0 -3vmin;
|
||||
box-sizing: border-box;
|
||||
border-radius: 1.6vmin;
|
||||
border: 0.55vmin solid var(--clock-ink);
|
||||
}
|
||||
|
||||
.clock-button[data-hue="pink"] {
|
||||
background: var(--clock-pink);
|
||||
}
|
||||
|
||||
.clock-button[data-hue="205"] {
|
||||
background: oklch(66% 0.12 205);
|
||||
}
|
||||
|
||||
.clock-face {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 9vmin;
|
||||
width: 78vmin;
|
||||
height: 78vmin;
|
||||
box-sizing: border-box;
|
||||
border-radius: 50%;
|
||||
border: 0.6vmin solid var(--clock-ink);
|
||||
background:
|
||||
radial-gradient(
|
||||
circle closest-side,
|
||||
transparent 88.6%,
|
||||
var(--clock-ink) 88.6%,
|
||||
var(--clock-ink) 89.6%,
|
||||
transparent 89.6%
|
||||
),
|
||||
conic-gradient(
|
||||
from 210deg,
|
||||
oklch(94% 0.008 210),
|
||||
oklch(81% 0.015 210),
|
||||
oklch(96% 0.006 210),
|
||||
oklch(79% 0.015 210),
|
||||
oklch(94% 0.008 210)
|
||||
);
|
||||
}
|
||||
|
||||
.clock-face > * {
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
/* The bezel's 48 dots: big coloured ones on the 5-minute marks, small grey between. */
|
||||
.clock-dot {
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: 1.1vmin;
|
||||
height: 1.1vmin;
|
||||
border-radius: 50%;
|
||||
background: oklch(62% 0.02 220);
|
||||
box-shadow: inset 0 0 0 0.2vmin oklch(30% 0.03 220 / 0.35);
|
||||
}
|
||||
|
||||
.clock-dot[data-big] {
|
||||
width: 1.9vmin;
|
||||
height: 1.9vmin;
|
||||
}
|
||||
|
||||
.clock-dot[data-hue="205"] {
|
||||
background: oklch(64% 0.12 205);
|
||||
}
|
||||
|
||||
.clock-dot[data-hue="175"] {
|
||||
background: oklch(64% 0.12 175);
|
||||
}
|
||||
|
||||
.clock-dot[data-hue="245"] {
|
||||
background: oklch(64% 0.12 245);
|
||||
}
|
||||
|
||||
.clock-dot[data-hue="pink"] {
|
||||
background: var(--clock-pink);
|
||||
}
|
||||
|
||||
/* Every ring below is centred on the face; only the diameter differs. */
|
||||
.clock-face-inner,
|
||||
.clock-sections,
|
||||
.clock-sections-gaps,
|
||||
.clock-sections-rim,
|
||||
.clock-center,
|
||||
.clock-minute-track,
|
||||
.clock-minute-ticks,
|
||||
.clock-minute-ticks-major {
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: var(--d);
|
||||
height: var(--d);
|
||||
margin: calc(var(--d) / -2) 0 0 calc(var(--d) / -2);
|
||||
box-sizing: border-box;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.clock-face-inner {
|
||||
--d: 68.4vmin;
|
||||
background: oklch(99% 0.005 210);
|
||||
box-shadow: inset 0 0.6vmin 1.4vmin oklch(30% 0.03 220 / 0.18);
|
||||
}
|
||||
|
||||
.clock-sections {
|
||||
--d: 55.6vmin;
|
||||
background: conic-gradient(
|
||||
from -15deg,
|
||||
oklch(91% 0.06 205) 0deg 30deg,
|
||||
oklch(91% 0.06 175) 30deg 60deg,
|
||||
oklch(91% 0.06 245) 60deg 90deg,
|
||||
oklch(91% 0.07 345) 90deg 120deg,
|
||||
oklch(91% 0.06 205) 120deg 150deg,
|
||||
oklch(91% 0.06 175) 150deg 180deg,
|
||||
oklch(91% 0.06 245) 180deg 210deg,
|
||||
oklch(91% 0.07 345) 210deg 240deg,
|
||||
oklch(91% 0.06 205) 240deg 270deg,
|
||||
oklch(91% 0.06 175) 270deg 300deg,
|
||||
oklch(91% 0.06 245) 300deg 330deg,
|
||||
oklch(91% 0.07 345) 330deg 360deg
|
||||
);
|
||||
}
|
||||
|
||||
.clock-sections-gaps {
|
||||
--d: 55.6vmin;
|
||||
background: repeating-conic-gradient(
|
||||
from 14.6deg,
|
||||
oklch(99% 0.005 210) 0deg 0.8deg,
|
||||
transparent 0.8deg 30deg
|
||||
);
|
||||
}
|
||||
|
||||
.clock-sections-rim {
|
||||
--d: 55.6vmin;
|
||||
border: 0.4vmin solid var(--clock-ink);
|
||||
}
|
||||
|
||||
.clock-center {
|
||||
--d: 20vmin;
|
||||
background: oklch(99% 0.005 210);
|
||||
box-shadow: 0 0 0 0.4vmin oklch(28% 0.04 220 / 0.25);
|
||||
}
|
||||
|
||||
.clock-minute-track {
|
||||
--d: 66.8vmin;
|
||||
background: conic-gradient(
|
||||
from -15deg,
|
||||
oklch(80% 0.1 205) 0deg 30deg,
|
||||
oklch(80% 0.1 175) 30deg 60deg,
|
||||
oklch(80% 0.1 245) 60deg 90deg,
|
||||
oklch(80% 0.13 345) 90deg 120deg,
|
||||
oklch(80% 0.1 205) 120deg 150deg,
|
||||
oklch(80% 0.1 175) 150deg 180deg,
|
||||
oklch(80% 0.1 245) 180deg 210deg,
|
||||
oklch(80% 0.13 345) 210deg 240deg,
|
||||
oklch(80% 0.1 205) 240deg 270deg,
|
||||
oklch(80% 0.1 175) 270deg 300deg,
|
||||
oklch(80% 0.1 245) 300deg 330deg,
|
||||
oklch(80% 0.13 345) 330deg 360deg
|
||||
);
|
||||
mask-image: radial-gradient(circle closest-side, transparent 82.8%, #000 83.2%);
|
||||
}
|
||||
|
||||
.clock-minute-ticks {
|
||||
--d: 66.8vmin;
|
||||
background: repeating-conic-gradient(
|
||||
from -0.5deg,
|
||||
var(--clock-ink) 0deg 1deg,
|
||||
transparent 1deg 6deg
|
||||
);
|
||||
mask-image: radial-gradient(circle closest-side, transparent 94.6%, #000 95%);
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.clock-minute-ticks-major {
|
||||
--d: 66.8vmin;
|
||||
background: repeating-conic-gradient(
|
||||
from -1.3deg,
|
||||
var(--clock-ink) 0deg 2.6deg,
|
||||
transparent 2.6deg 30deg
|
||||
);
|
||||
mask-image: radial-gradient(circle closest-side, transparent 93.2%, #000 93.6%);
|
||||
}
|
||||
|
||||
.clock-numbers {
|
||||
inset: 0;
|
||||
font-weight: 900;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.clock-numbers > div {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
}
|
||||
|
||||
.clock-numbers-minutes {
|
||||
font-size: 2.3vmin;
|
||||
color: var(--clock-ink);
|
||||
}
|
||||
|
||||
.clock-numbers-hours {
|
||||
font-size: 8.2vmin;
|
||||
letter-spacing: -0.3vmin;
|
||||
-webkit-text-stroke: 0.45vmin var(--clock-ink);
|
||||
paint-order: stroke fill;
|
||||
}
|
||||
|
||||
.clock-numbers-hours > [data-hue="205"] {
|
||||
color: oklch(56% 0.13 205);
|
||||
}
|
||||
|
||||
.clock-numbers-hours > [data-hue="175"] {
|
||||
color: oklch(56% 0.13 175);
|
||||
}
|
||||
|
||||
.clock-numbers-hours > [data-hue="245"] {
|
||||
color: oklch(56% 0.13 245);
|
||||
}
|
||||
|
||||
.clock-numbers-hours > [data-hue="pink"] {
|
||||
color: oklch(60% 0.19 345);
|
||||
}
|
||||
|
||||
/* A hand is a box standing on the centre, rotated about its foot. */
|
||||
.clock-hand {
|
||||
left: 50%;
|
||||
bottom: 50%;
|
||||
transform-origin: 50% 100%;
|
||||
}
|
||||
|
||||
.clock-hand-hour,
|
||||
.clock-hand-minute {
|
||||
filter: drop-shadow(0.35vmin 0 0 var(--clock-ink)) drop-shadow(-0.35vmin 0 0 var(--clock-ink))
|
||||
drop-shadow(0 0.35vmin 0 var(--clock-ink)) drop-shadow(0 -0.35vmin 0 var(--clock-ink))
|
||||
drop-shadow(0 1vmin 1vmin oklch(15% 0.05 210 / 0.3));
|
||||
}
|
||||
|
||||
.clock-hand > div {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 0;
|
||||
}
|
||||
|
||||
.clock-hand-hour {
|
||||
width: 5.4vmin;
|
||||
height: 15vmin;
|
||||
margin-left: -2.7vmin;
|
||||
}
|
||||
|
||||
.clock-hand-hour > div {
|
||||
bottom: -3.5vmin;
|
||||
background: oklch(92% 0.06 345);
|
||||
clip-path: polygon(50% 0%, 100% 22%, 66% 22%, 66% 100%, 34% 100%, 34% 22%, 0% 22%);
|
||||
}
|
||||
|
||||
.clock-hand-minute {
|
||||
width: 5vmin;
|
||||
height: 24vmin;
|
||||
margin-left: -2.5vmin;
|
||||
}
|
||||
|
||||
.clock-hand-minute > div {
|
||||
bottom: -3.5vmin;
|
||||
background: oklch(92% 0.05 200);
|
||||
clip-path: polygon(50% 0%, 100% 14%, 64% 14%, 64% 100%, 36% 100%, 36% 14%, 0% 14%);
|
||||
}
|
||||
|
||||
.clock-hand-second {
|
||||
width: 0.7vmin;
|
||||
height: 27vmin;
|
||||
margin-left: -0.35vmin;
|
||||
}
|
||||
|
||||
.clock-hand-second > div {
|
||||
bottom: -5vmin;
|
||||
border-radius: 1vmin;
|
||||
background: oklch(64% 0.19 345);
|
||||
}
|
||||
|
||||
.clock-pin {
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: 4.2vmin;
|
||||
height: 4.2vmin;
|
||||
margin: -2.1vmin 0 0 -2.1vmin;
|
||||
border-radius: 50%;
|
||||
background: oklch(80% 0.1 205);
|
||||
box-shadow: 0 0 0 0.5vmin var(--clock-ink);
|
||||
}
|
||||
|
||||
.clock-pin-dot {
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
width: 1.4vmin;
|
||||
height: 1.4vmin;
|
||||
margin: -0.7vmin 0 0 -0.7vmin;
|
||||
border-radius: 50%;
|
||||
background: var(--clock-ink);
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- the countdowns */
|
||||
|
||||
.clock-countdowns {
|
||||
position: relative;
|
||||
flex: 0 1 74vmin;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3vmin;
|
||||
}
|
||||
|
||||
@media (orientation: portrait) {
|
||||
.clock-countdowns {
|
||||
flex: none;
|
||||
width: 88vw;
|
||||
}
|
||||
}
|
||||
|
||||
.clock-card {
|
||||
--clock-bar: oklch(66% 0.12 205);
|
||||
--clock-time: oklch(30% 0.05 210);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 3.5vmin;
|
||||
padding: 3vmin 4vmin 3vmin 3vmin;
|
||||
border-radius: 4.5vmin;
|
||||
background: oklch(97% 0.01 210 / 0.68);
|
||||
backdrop-filter: blur(10px);
|
||||
box-shadow: 0 2vmin 5vmin oklch(15% 0.05 210 / 0.35);
|
||||
}
|
||||
|
||||
[data-blur="off"] .clock-card {
|
||||
backdrop-filter: none;
|
||||
background: oklch(97% 0.01 210 / 0.88);
|
||||
}
|
||||
|
||||
.clock-card[data-soon] {
|
||||
--clock-bar: var(--clock-pink);
|
||||
--clock-time: oklch(58% 0.19 345);
|
||||
}
|
||||
|
||||
.clock-card[data-ringing] {
|
||||
animation: clockRing 1.2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes clockRing {
|
||||
0%,
|
||||
100% {
|
||||
background: oklch(97% 0.01 210 / 0.68);
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
background: oklch(88% 0.09 345 / 0.92);
|
||||
transform: scale(1.03);
|
||||
}
|
||||
}
|
||||
|
||||
.clock-card-image {
|
||||
width: 24vmin;
|
||||
height: 18vmin;
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.clock-card-image > img {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
filter: drop-shadow(0 1vmin 1.5vmin oklch(15% 0.05 210 / 0.3));
|
||||
}
|
||||
|
||||
.clock-card-body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6vmin;
|
||||
}
|
||||
|
||||
.clock-card-time {
|
||||
font-size: 15vmin;
|
||||
font-weight: 900;
|
||||
line-height: 0.95;
|
||||
font-variant-numeric: tabular-nums;
|
||||
letter-spacing: -0.3vmin;
|
||||
color: var(--clock-time);
|
||||
}
|
||||
|
||||
.clock-card-bar {
|
||||
height: 2vmin;
|
||||
margin-top: 0.8vmin;
|
||||
border-radius: 999px;
|
||||
overflow: hidden;
|
||||
background: oklch(30% 0.04 210 / 0.15);
|
||||
}
|
||||
|
||||
.clock-card-bar > div {
|
||||
height: 100%;
|
||||
border-radius: 999px;
|
||||
background: var(--clock-bar);
|
||||
transition: width 0.25s linear;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.clock-card[data-ringing] {
|
||||
animation: none;
|
||||
background: oklch(88% 0.09 345 / 0.92);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user