Compare commits
No commits in common. "f69b9f401ae43f99b8b7315b635762952ff133f8" and "b88f4d67fec92dc58f78bc024084662699ca3a86" have entirely different histories.
f69b9f401a
...
b88f4d67fe
19 changed files with 330 additions and 1678 deletions
12
BUILD.bazel
12
BUILD.bazel
|
|
@ -1,12 +0,0 @@
|
||||||
load("@npm//:defs.bzl", "npm_link_all_packages")
|
|
||||||
|
|
||||||
# rules_js PoC: link the full npm dependency graph (from package-lock.json) via
|
|
||||||
# Bazel. `bazel build //walldash:node_modules` resolves all packages.
|
|
||||||
# A complete `next build` under Bazel is a further step (ts_project + next rule).
|
|
||||||
npm_link_all_packages(name = "node_modules")
|
|
||||||
|
|
||||||
filegroup(
|
|
||||||
name = "srcs",
|
|
||||||
srcs = glob(["src/**"], allow_empty = True),
|
|
||||||
visibility = ["//visibility:public"],
|
|
||||||
)
|
|
||||||
101
README.md
101
README.md
|
|
@ -1,108 +1,15 @@
|
||||||
# walldash
|
# walldash
|
||||||
|
|
||||||
A full-screen kiosk dashboard for a Raspberry Pi, showing public transit departures (SL and SBB), weather, Spotify now-playing, and system stats.
|
To install dependencies:
|
||||||
|
|
||||||
## Prerequisites
|
|
||||||
|
|
||||||
- [Bun](https://bun.sh) runtime
|
|
||||||
- Raspberry Pi running Raspberry Pi OS (tested on Bookworm/Lite + LXDE desktop)
|
|
||||||
- Chromium or chromium-browser installed
|
|
||||||
|
|
||||||
## Quick start (development)
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bun install
|
bun install
|
||||||
cp config.example.json config.json # then fill in your credentials
|
|
||||||
bun run start
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Open [http://localhost:3000](http://localhost:3000).
|
To run:
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
Copy `config.example.json` to `config.json` and fill in your values:
|
|
||||||
|
|
||||||
| Field | Description |
|
|
||||||
|---|---|
|
|
||||||
| `spotify.clientId` / `spotify.clientSecret` | Spotify app credentials from [developer.spotify.com](https://developer.spotify.com/dashboard) |
|
|
||||||
| `weather.plz` | Swiss postal code (PLZ) for MeteoSwiss forecasts |
|
|
||||||
| `sl.stationId` / `sl.stationName` | Stockholm Lokaltrafik site ID (find via Settings > Search) |
|
|
||||||
| `sbb.stationId` / `sbb.stationName` | Swiss Federal Railways station ID (find via Settings > Search) |
|
|
||||||
| `refreshRate` | Polling interval in milliseconds (default: `10000`) |
|
|
||||||
| `alwaysOn` | `true` reduces animations and refresh rates for burn-in prevention |
|
|
||||||
| `layout` | Maps widget zone names to widget IDs |
|
|
||||||
|
|
||||||
`config.json` and `tokens.json` are gitignored — never commit real credentials.
|
|
||||||
|
|
||||||
## Raspberry Pi deployment
|
|
||||||
|
|
||||||
### 1. Install the server as a systemd service
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bash scripts/setup-systemd.sh
|
bun run index.ts
|
||||||
```
|
```
|
||||||
|
|
||||||
This creates `/etc/systemd/system/walldash.service`, enables it, and starts it. The server auto-restarts on crash and starts on boot.
|
This project was created using `bun init` in bun v1.3.11. [Bun](https://bun.com) is a fast all-in-one JavaScript runtime.
|
||||||
|
|
||||||
```bash
|
|
||||||
systemctl status walldash.service
|
|
||||||
journalctl -u walldash.service -f
|
|
||||||
```
|
|
||||||
|
|
||||||
### 2. Set up the kiosk browser
|
|
||||||
|
|
||||||
```bash
|
|
||||||
bash scripts/setup-kiosk.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
This installs `unclutter` (hides the cursor), disables screen blanking, and adds a `~/.config/autostart/walldash-kiosk.desktop` entry that launches `scripts/start-kiosk.sh` on login.
|
|
||||||
|
|
||||||
`start-kiosk.sh` waits until the server is ready, then opens Chromium in kiosk mode. If Chromium crashes it restarts automatically.
|
|
||||||
|
|
||||||
### 3. Configure auto-login
|
|
||||||
|
|
||||||
Use `raspi-config` → **System Options → Boot / Auto Login → Desktop Autologin** so the kiosk browser starts without manual interaction.
|
|
||||||
|
|
||||||
### 4. Set credentials
|
|
||||||
|
|
||||||
Copy and edit `config.json` on the Pi:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cp config.example.json config.json
|
|
||||||
nano config.json
|
|
||||||
```
|
|
||||||
|
|
||||||
For Spotify, open `http://<pi-ip>:3000/settings` in a browser and follow the OAuth link.
|
|
||||||
|
|
||||||
## Uninstall
|
|
||||||
|
|
||||||
```bash
|
|
||||||
bash scripts/uninstall.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
Removes the systemd service and autostart entry. The project directory is left untouched.
|
|
||||||
|
|
||||||
## Build
|
|
||||||
|
|
||||||
To regenerate the bundled frontend:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
bun run build
|
|
||||||
```
|
|
||||||
|
|
||||||
Output goes to `public/main.js`.
|
|
||||||
|
|
||||||
## Widget zones
|
|
||||||
|
|
||||||
```
|
|
||||||
┌──────────────────────────────────────────┐
|
|
||||||
│ header-left header-right │
|
|
||||||
├────────────────────┬─────────────────────┤
|
|
||||||
│ main-1 │ main-2 │
|
|
||||||
│ │ │
|
|
||||||
├──────────┬─────────┴──────┬──────────────┤
|
|
||||||
│ footer-1 │ footer-2 │ footer-3 │
|
|
||||||
└──────────┴────────────────┴──────────────┘
|
|
||||||
```
|
|
||||||
|
|
||||||
Available widget IDs: `clock`, `weather`, `sl`, `sbb`, `spotify`, `system`, `spacer`.
|
|
||||||
|
|
|
||||||
|
|
@ -28,8 +28,5 @@
|
||||||
"react": "^19.2.5",
|
"react": "^19.2.5",
|
||||||
"react-dom": "^19.2.5",
|
"react-dom": "^19.2.5",
|
||||||
"react-router-dom": "^7.14.1"
|
"react-router-dom": "^7.14.1"
|
||||||
},
|
|
||||||
"pnpm": {
|
|
||||||
"onlyBuiltDependencies": []
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
1072
pnpm-lock.yaml
1072
pnpm-lock.yaml
File diff suppressed because it is too large
Load diff
220
public/main.js
220
public/main.js
File diff suppressed because one or more lines are too long
|
|
@ -1,43 +0,0 @@
|
||||||
#!/bin/bash
|
|
||||||
# Removes all walldash system integrations installed by setup-systemd.sh and setup-kiosk.sh.
|
|
||||||
# Does NOT delete the project directory itself.
|
|
||||||
|
|
||||||
set -e
|
|
||||||
|
|
||||||
SERVICE_NAME="walldash"
|
|
||||||
USER_NAME=$(whoami)
|
|
||||||
|
|
||||||
# Stop and remove the systemd service
|
|
||||||
if systemctl list-unit-files "${SERVICE_NAME}.service" &>/dev/null; then
|
|
||||||
echo "Stopping and disabling ${SERVICE_NAME} service..."
|
|
||||||
sudo systemctl stop "${SERVICE_NAME}.service" 2>/dev/null || true
|
|
||||||
sudo systemctl disable "${SERVICE_NAME}.service" 2>/dev/null || true
|
|
||||||
sudo rm -f "/etc/systemd/system/${SERVICE_NAME}.service"
|
|
||||||
sudo systemctl daemon-reload
|
|
||||||
echo "Systemd service removed."
|
|
||||||
else
|
|
||||||
echo "No systemd service found for ${SERVICE_NAME}, skipping."
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Remove the kiosk autostart entry
|
|
||||||
DESKTOP_FILE="/home/${USER_NAME}/.config/autostart/walldash-kiosk.desktop"
|
|
||||||
if [ -f "$DESKTOP_FILE" ]; then
|
|
||||||
rm -f "$DESKTOP_FILE"
|
|
||||||
echo "Autostart entry removed: $DESKTOP_FILE"
|
|
||||||
else
|
|
||||||
echo "No autostart entry found, skipping."
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Undo screen blanking changes in LXDE autostart
|
|
||||||
LXDE_AUTOSTART="/etc/xdg/lxsession/LXDE-pi/autostart"
|
|
||||||
if [ -f "$LXDE_AUTOSTART" ]; then
|
|
||||||
sudo sed -i '/^@xset s off$/d' "$LXDE_AUTOSTART"
|
|
||||||
sudo sed -i '/^@xset -dpms$/d' "$LXDE_AUTOSTART"
|
|
||||||
sudo sed -i '/^@xset s noblank$/d' "$LXDE_AUTOSTART"
|
|
||||||
sudo sed -i 's/^# @xscreensaver/@xscreensaver/' "$LXDE_AUTOSTART"
|
|
||||||
echo "LXDE autostart screen-blanking settings restored."
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo ""
|
|
||||||
echo "Uninstall complete. The project directory has not been touched."
|
|
||||||
echo "You can safely delete it manually if no longer needed."
|
|
||||||
|
|
@ -1,9 +1,5 @@
|
||||||
export const LineBadge = ({ designation }: {
|
export const LineBadge = ({ designation }: { designation: string; mode?: string; groupOfLines?: string }) => (
|
||||||
designation: string;
|
<span className="border border-white text-white px-2 py-0.5 font-bold min-w-[56px] text-center text-xl inline-block">
|
||||||
mode?: string;
|
|
||||||
groupOfLines?: string;
|
|
||||||
}) => (
|
|
||||||
<span className="border border-white text-white px-2 py-0.5 font-bold min-w-[56px] text-center text-xl inline-block shrink-0">
|
|
||||||
{designation}
|
{designation}
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
export const SBBLineBadge = ({ name }: { name: string; category?: string }) => (
|
export const SBBLineBadge = ({ name }: { name: string; category?: string }) => (
|
||||||
<span className="border border-white text-white px-2 py-0.5 font-bold min-w-[56px] text-center text-xl inline-block shrink-0">
|
<span className="border border-white text-white px-2 py-0.5 font-bold min-w-[56px] text-center text-xl inline-block">
|
||||||
{name}
|
{name}
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,8 @@
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { useAlwaysOn } from '../../contexts/AlwaysOnContext';
|
import { useAlwaysOn } from '../../contexts/AlwaysOnContext';
|
||||||
import { useSize } from '../../hooks/useSize';
|
|
||||||
|
|
||||||
export const Clock = () => {
|
export const Clock = () => {
|
||||||
const alwaysOn = useAlwaysOn();
|
const alwaysOn = useAlwaysOn();
|
||||||
const { h, ref } = useSize();
|
|
||||||
const [time, setTime] = useState(new Date());
|
const [time, setTime] = useState(new Date());
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
@ -12,6 +10,8 @@ export const Clock = () => {
|
||||||
const id = setInterval(() => setTime(new Date()), 1000);
|
const id = setInterval(() => setTime(new Date()), 1000);
|
||||||
return () => clearInterval(id);
|
return () => clearInterval(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sync to the next full minute, then tick every 60 s
|
||||||
let interval: ReturnType<typeof setInterval>;
|
let interval: ReturnType<typeof setInterval>;
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const msUntilNext = (60 - now.getSeconds()) * 1000 - now.getMilliseconds();
|
const msUntilNext = (60 - now.getSeconds()) * 1000 - now.getMilliseconds();
|
||||||
|
|
@ -19,47 +19,22 @@ export const Clock = () => {
|
||||||
setTime(new Date());
|
setTime(new Date());
|
||||||
interval = setInterval(() => setTime(new Date()), 60_000);
|
interval = setInterval(() => setTime(new Date()), 60_000);
|
||||||
}, msUntilNext);
|
}, msUntilNext);
|
||||||
|
|
||||||
return () => { clearTimeout(timeout); clearInterval(interval); };
|
return () => { clearTimeout(timeout); clearInterval(interval); };
|
||||||
}, [alwaysOn]);
|
}, [alwaysOn]);
|
||||||
|
|
||||||
const effectiveH = h || 80;
|
const timeStr = alwaysOn
|
||||||
|
? time.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', hour12: false })
|
||||||
|
: time.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });
|
||||||
|
|
||||||
// Show seconds when not in alwaysOn and there is enough vertical room
|
|
||||||
const showSeconds = !alwaysOn && effectiveH > 90;
|
|
||||||
// Stack time and date vertically when tall enough; otherwise inline
|
|
||||||
const stacked = effectiveH > 110;
|
|
||||||
// Show full weekday + month name when stacked, short otherwise
|
|
||||||
const longDate = stacked;
|
|
||||||
|
|
||||||
const timeStr = time.toLocaleTimeString('en-GB', {
|
|
||||||
hour: '2-digit', minute: '2-digit',
|
|
||||||
...(showSeconds ? { second: '2-digit' } : {}),
|
|
||||||
hour12: false,
|
|
||||||
});
|
|
||||||
const dateStr = time.toLocaleDateString('en-GB', {
|
const dateStr = time.toLocaleDateString('en-GB', {
|
||||||
weekday: longDate ? 'long' : 'short',
|
weekday: 'long', day: 'numeric', month: 'long',
|
||||||
day: 'numeric',
|
|
||||||
month: longDate ? 'long' : 'short',
|
|
||||||
...(effectiveH > 160 ? { year: 'numeric' } : {}),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div ref={ref} className="w-full h-full flex flex-col justify-center overflow-hidden">
|
<div className="flex items-baseline gap-6">
|
||||||
{stacked ? (
|
<div className={`text-7xl ${alwaysOn ? 'font-light' : 'font-bold'}`}>{timeStr}</div>
|
||||||
<>
|
<div className="text-2xl text-gray-400">{dateStr}</div>
|
||||||
<div className={`text-7xl tabular-nums leading-none ${alwaysOn ? 'font-light' : 'font-bold'}`}>
|
|
||||||
{timeStr}
|
|
||||||
</div>
|
|
||||||
<div className="text-2xl text-gray-400 mt-2">{dateStr}</div>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<div className="flex items-baseline gap-6 flex-wrap">
|
|
||||||
<div className={`text-7xl tabular-nums ${alwaysOn ? 'font-light' : 'font-bold'}`}>
|
|
||||||
{timeStr}
|
|
||||||
</div>
|
|
||||||
<div className="text-2xl text-gray-400">{dateStr}</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -4,21 +4,17 @@ import { useAlwaysOn } from '../../contexts/AlwaysOnContext';
|
||||||
|
|
||||||
export const DepartureItem = ({ departure }: { departure: Departure }) => {
|
export const DepartureItem = ({ departure }: { departure: Departure }) => {
|
||||||
const alwaysOn = useAlwaysOn();
|
const alwaysOn = useAlwaysOn();
|
||||||
const depTime = new Date(departure.scheduled);
|
const depTime = new Date(departure.scheduled);
|
||||||
const diffMin = Math.round((depTime.getTime() - Date.now()) / 60000);
|
const diffMin = Math.round((depTime.getTime() - Date.now()) / 60000);
|
||||||
const timeText = diffMin <= 0 ? 'Now' : `${diffMin} min`;
|
const timeText = diffMin <= 0 ? 'Now' : `${diffMin} min`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`flex justify-between items-center py-3 border-b border-zinc-700 text-2xl ${alwaysOn ? 'font-light' : ''}`}>
|
<div className={`flex justify-between items-center py-3 border-b border-zinc-700 text-2xl ${alwaysOn ? 'font-light' : ''}`}>
|
||||||
<div className="flex items-center gap-4 min-w-0 overflow-hidden">
|
<div className="flex items-center gap-4">
|
||||||
<LineBadge
|
<LineBadge designation={departure.line.designation} mode={departure.line.transport_mode} groupOfLines={departure.line.group_of_lines} />
|
||||||
designation={departure.line.designation}
|
<span>{departure.destination}</span>
|
||||||
mode={departure.line.transport_mode}
|
|
||||||
groupOfLines={departure.line.group_of_lines}
|
|
||||||
/>
|
|
||||||
<span className="truncate">{departure.destination}</span>
|
|
||||||
</div>
|
</div>
|
||||||
<span className={`shrink-0 ml-4 ${alwaysOn ? 'font-normal' : 'font-bold'}`}>{timeText}</span>
|
<span className={alwaysOn ? 'font-normal' : 'font-bold'}>{timeText}</span>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -2,32 +2,21 @@ import { SBBLineBadge } from '../atoms/SBBLineBadge';
|
||||||
import { SBBDeparture } from '../../types';
|
import { SBBDeparture } from '../../types';
|
||||||
import { useAlwaysOn } from '../../contexts/AlwaysOnContext';
|
import { useAlwaysOn } from '../../contexts/AlwaysOnContext';
|
||||||
|
|
||||||
export const SBBDepartureItem = ({
|
export const SBBDepartureItem = ({ departure }: { departure: SBBDeparture }) => {
|
||||||
departure,
|
|
||||||
showPlatform = false,
|
|
||||||
}: {
|
|
||||||
departure: SBBDeparture;
|
|
||||||
showPlatform?: boolean;
|
|
||||||
}) => {
|
|
||||||
const alwaysOn = useAlwaysOn();
|
const alwaysOn = useAlwaysOn();
|
||||||
const dep = departure.stop.departure ? new Date(departure.stop.departure) : null;
|
const dep = departure.stop.departure ? new Date(departure.stop.departure) : null;
|
||||||
const diffMin = dep ? Math.round((dep.getTime() - Date.now()) / 60000) : null;
|
const diffMin = dep ? Math.round((dep.getTime() - Date.now()) / 60000) : null;
|
||||||
const timeText = diffMin === null ? '—' : diffMin <= 0 ? 'Now' : `${diffMin} min`;
|
const timeText = diffMin === null ? '—' : diffMin <= 0 ? 'Now' : `${diffMin} min`;
|
||||||
const delay = departure.stop.delay;
|
const delay = departure.stop.delay;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`flex justify-between items-center py-3 border-b border-zinc-700 text-2xl ${alwaysOn ? 'font-light' : ''}`}>
|
<div className={`flex justify-between items-center py-3 border-b border-zinc-700 text-2xl ${alwaysOn ? 'font-light' : ''}`}>
|
||||||
<div className="flex items-center gap-4 min-w-0 overflow-hidden">
|
<div className="flex items-center gap-4">
|
||||||
<SBBLineBadge name={`${departure.category} ${departure.number}`} category={departure.category} />
|
<SBBLineBadge name={`${departure.category} ${departure.number}`} category={departure.category} />
|
||||||
<span className="truncate">{departure.to}</span>
|
<span>{departure.to}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className={`flex items-center gap-2 shrink-0 ml-4 ${alwaysOn ? 'font-normal' : 'font-bold'}`}>
|
<div className={`flex items-center gap-2 ${alwaysOn ? 'font-normal' : 'font-bold'}`}>
|
||||||
{showPlatform && departure.stop.platform && (
|
{delay != null && delay > 0 && <span className="text-lg font-normal">+{delay}'</span>}
|
||||||
<span className="text-sm text-gray-400 font-normal">Pl.{departure.stop.platform}</span>
|
|
||||||
)}
|
|
||||||
{delay != null && delay > 0 && (
|
|
||||||
<span className="text-lg text-orange-400 font-normal">+{delay}'</span>
|
|
||||||
)}
|
|
||||||
<span>{timeText}</span>
|
<span>{timeText}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,46 +1,14 @@
|
||||||
import { useSize } from '../../hooks/useSize';
|
|
||||||
import { DepartureItem } from '../molecules/DepartureItem';
|
import { DepartureItem } from '../molecules/DepartureItem';
|
||||||
import { Departure } from '../../types';
|
import { Departure } from '../../types';
|
||||||
import { useAlwaysOn } from '../../contexts/AlwaysOnContext';
|
|
||||||
|
|
||||||
// text-2xl (line-height 2rem = 32px) + py-3 (2 × 12px) = 56 px per row
|
|
||||||
const ROW_H = 56;
|
|
||||||
// text-xl header + pb-1 + a little breathing room
|
|
||||||
const HEADER_H = 38;
|
|
||||||
|
|
||||||
export const DepartureList = ({
|
|
||||||
departures,
|
|
||||||
loading,
|
|
||||||
stationName,
|
|
||||||
}: {
|
|
||||||
departures: Departure[];
|
|
||||||
loading: boolean;
|
|
||||||
stationName?: string;
|
|
||||||
}) => {
|
|
||||||
const alwaysOn = useAlwaysOn();
|
|
||||||
const { h, ref } = useSize();
|
|
||||||
const effectiveH = h || 300;
|
|
||||||
|
|
||||||
const listH = effectiveH - (stationName ? HEADER_H : 0);
|
|
||||||
const maxRows = Math.max(1, Math.floor(listH / ROW_H));
|
|
||||||
const visible = departures.slice(0, maxRows);
|
|
||||||
|
|
||||||
|
export const DepartureList = ({ departures, loading }: { departures: Departure[]; loading: boolean }) => {
|
||||||
|
if (loading && departures.length === 0) return <p className="text-gray-500 text-xl mt-4">Loading...</p>;
|
||||||
|
if (!loading && departures.length === 0) return <p className="text-gray-500 text-xl mt-4">No departures.</p>;
|
||||||
return (
|
return (
|
||||||
<div ref={ref} className="w-full h-full flex flex-col overflow-hidden">
|
<div className="flex-1 overflow-hidden">
|
||||||
{stationName && (
|
{departures.map((dep, i) => (
|
||||||
<h2 className={`text-xl uppercase tracking-wider shrink-0 pb-1 ${alwaysOn ? 'font-normal' : 'font-bold'}`}>
|
<DepartureItem key={`${dep.line.designation}-${i}`} departure={dep} />
|
||||||
{stationName}
|
))}
|
||||||
</h2>
|
|
||||||
)}
|
|
||||||
{loading && departures.length === 0 ? (
|
|
||||||
<p className="text-gray-500 text-xl mt-4">Loading…</p>
|
|
||||||
) : visible.length === 0 ? (
|
|
||||||
<p className="text-gray-500 text-xl mt-4">No departures</p>
|
|
||||||
) : (
|
|
||||||
visible.map((dep, i) => (
|
|
||||||
<DepartureItem key={`${dep.line.designation}-${dep.scheduled}-${i}`} departure={dep} />
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,50 +1,14 @@
|
||||||
import { useSize } from '../../hooks/useSize';
|
|
||||||
import { SBBDepartureItem } from '../molecules/SBBDepartureItem';
|
import { SBBDepartureItem } from '../molecules/SBBDepartureItem';
|
||||||
import { SBBDeparture } from '../../types';
|
import { SBBDeparture } from '../../types';
|
||||||
import { useAlwaysOn } from '../../contexts/AlwaysOnContext';
|
|
||||||
|
|
||||||
const ROW_H = 56;
|
|
||||||
const HEADER_H = 38;
|
|
||||||
|
|
||||||
export const SBBDepartureList = ({
|
|
||||||
departures,
|
|
||||||
loading,
|
|
||||||
stationName,
|
|
||||||
}: {
|
|
||||||
departures: SBBDeparture[];
|
|
||||||
loading: boolean;
|
|
||||||
stationName?: string;
|
|
||||||
}) => {
|
|
||||||
const alwaysOn = useAlwaysOn();
|
|
||||||
const { h, w, ref } = useSize();
|
|
||||||
const effectiveH = h || 300;
|
|
||||||
|
|
||||||
const listH = effectiveH - (stationName ? HEADER_H : 0);
|
|
||||||
const maxRows = Math.max(1, Math.floor(listH / ROW_H));
|
|
||||||
// Platform column only when the slot is wide enough to show it comfortably
|
|
||||||
const showPlatform = (w || 0) > 320;
|
|
||||||
const visible = departures.slice(0, maxRows);
|
|
||||||
|
|
||||||
|
export const SBBDepartureList = ({ departures, loading }: { departures: SBBDeparture[]; loading: boolean }) => {
|
||||||
|
if (loading && departures.length === 0) return <p className="text-gray-500 text-xl mt-4">Loading...</p>;
|
||||||
|
if (!loading && departures.length === 0) return <p className="text-gray-500 text-xl mt-4">No departures.</p>;
|
||||||
return (
|
return (
|
||||||
<div ref={ref} className="w-full h-full flex flex-col overflow-hidden">
|
<div className="flex-1 overflow-hidden">
|
||||||
{stationName && (
|
{departures.map((dep, i) => (
|
||||||
<h2 className={`text-xl uppercase tracking-wider shrink-0 pb-1 ${alwaysOn ? 'font-normal' : 'font-bold'}`}>
|
<SBBDepartureItem key={`${dep.name}-${i}`} departure={dep} />
|
||||||
{stationName}
|
))}
|
||||||
</h2>
|
|
||||||
)}
|
|
||||||
{loading && departures.length === 0 ? (
|
|
||||||
<p className="text-gray-500 text-xl mt-4">Loading…</p>
|
|
||||||
) : visible.length === 0 ? (
|
|
||||||
<p className="text-gray-500 text-xl mt-4">No departures</p>
|
|
||||||
) : (
|
|
||||||
visible.map((dep, i) => (
|
|
||||||
<SBBDepartureItem
|
|
||||||
key={`${dep.name}-${dep.stop.departure}-${i}`}
|
|
||||||
departure={dep}
|
|
||||||
showPlatform={showPlatform}
|
|
||||||
/>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import { useAlwaysOn } from '../../contexts/AlwaysOnContext';
|
import { useAlwaysOn } from '../../contexts/AlwaysOnContext';
|
||||||
import { useSize } from '../../hooks/useSize';
|
|
||||||
import { SpotifyNowPlaying } from '../../types';
|
import { SpotifyNowPlaying } from '../../types';
|
||||||
|
|
||||||
function fmtMs(ms: number) {
|
function fmtMs(ms: number) {
|
||||||
|
|
@ -10,51 +9,31 @@ function fmtMs(ms: number) {
|
||||||
|
|
||||||
export const SpotifyWidget = () => {
|
export const SpotifyWidget = () => {
|
||||||
const alwaysOn = useAlwaysOn();
|
const alwaysOn = useAlwaysOn();
|
||||||
const { w, h, ref } = useSize();
|
|
||||||
const { data } = useQuery<SpotifyNowPlaying>({
|
const { data } = useQuery<SpotifyNowPlaying>({
|
||||||
queryKey: ['spotify-now-playing'],
|
queryKey: ['spotify-now-playing'],
|
||||||
queryFn: () => fetch('/api/spotify/now-playing').then(r => r.json()),
|
queryFn: () => fetch('/api/spotify/now-playing').then(r => r.json()),
|
||||||
refetchInterval: alwaysOn ? 30_000 : 1_000,
|
refetchInterval: alwaysOn ? 30_000 : 1_000,
|
||||||
});
|
});
|
||||||
|
|
||||||
const effectiveH = h || 100;
|
|
||||||
const effectiveW = w || 300;
|
|
||||||
|
|
||||||
// Progressive disclosure — text sizes are fixed, only visibility changes
|
|
||||||
const showAlbum = effectiveH > 110 && effectiveW > 260;
|
|
||||||
const showProgress = !alwaysOn && effectiveH > 90 && effectiveW > 200;
|
|
||||||
const showTimes = showProgress && effectiveW > 280;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div ref={ref} className="w-full h-full flex flex-col justify-center overflow-hidden">
|
<div className="h-full flex flex-col justify-center">
|
||||||
<h2 className="text-sm uppercase tracking-wider text-gray-400 mb-1 font-normal">Now Playing</h2>
|
<h2 className="text-sm uppercase tracking-wider text-gray-400 mb-1 font-normal">Now Playing</h2>
|
||||||
{data?.playing && data.track ? (
|
{data?.playing && data.track ? (
|
||||||
<>
|
<>
|
||||||
<p className={`text-2xl leading-tight truncate ${alwaysOn ? 'font-normal' : 'font-bold'}`}>
|
<p className={`text-2xl leading-tight ${alwaysOn ? 'font-normal' : 'font-bold'}`}>{data.track.name}</p>
|
||||||
{data.track.name}
|
<p className="text-lg text-gray-300 mt-0.5">{data.track.artist}</p>
|
||||||
</p>
|
<p className="text-sm text-gray-500">{data.track.album}</p>
|
||||||
<p className="text-lg text-gray-300 mt-0.5 truncate">{data.track.artist}</p>
|
{!alwaysOn && (
|
||||||
{showAlbum && (
|
|
||||||
<p className="text-sm text-gray-500 truncate">{data.track.album}</p>
|
|
||||||
)}
|
|
||||||
{showProgress && (
|
|
||||||
<div className="mt-1.5 flex items-center gap-2">
|
<div className="mt-1.5 flex items-center gap-2">
|
||||||
{showTimes && (
|
<span className="text-xs text-gray-500 font-mono w-10 shrink-0">{fmtMs(data.track.progressMs)}</span>
|
||||||
<span className="text-xs text-gray-500 font-mono w-10 shrink-0">
|
|
||||||
{fmtMs(data.track.progressMs)}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
<div className="flex-1 h-1.5 bg-zinc-800 relative">
|
<div className="flex-1 h-1.5 bg-zinc-800 relative">
|
||||||
<div
|
<div
|
||||||
className="absolute inset-y-0 left-0 bg-white"
|
className="absolute inset-y-0 left-0 bg-white"
|
||||||
style={{ width: `${(data.track.progressMs / data.track.durationMs) * 100}%` }}
|
style={{ width: `${(data.track.progressMs / data.track.durationMs) * 100}%` }}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{showTimes && (
|
<span className="text-xs text-gray-500 font-mono w-10 shrink-0 text-right">{fmtMs(data.track.durationMs)}</span>
|
||||||
<span className="text-xs text-gray-500 font-mono w-10 shrink-0 text-right">
|
|
||||||
{fmtMs(data.track.durationMs)}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,10 @@
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import { useAlwaysOn } from '../../contexts/AlwaysOnContext';
|
import { useAlwaysOn } from '../../contexts/AlwaysOnContext';
|
||||||
import { useSize } from '../../hooks/useSize';
|
|
||||||
|
|
||||||
interface SystemData {
|
interface SystemData {
|
||||||
cpu: { percent: number; load: string[] };
|
cpu: { percent: number; load: string[] };
|
||||||
memory: { percent: number; usedGb: string; totalGb: string };
|
memory: { percent: number; usedGb: string; totalGb: string };
|
||||||
disk: { percent: number; usedGb: string; totalGb: string };
|
disk: { percent: number; usedGb: string; totalGb: string };
|
||||||
uptime: string;
|
uptime: string;
|
||||||
hostname: string;
|
hostname: string;
|
||||||
}
|
}
|
||||||
|
|
@ -27,40 +26,23 @@ const Row = ({ label, percent, detail }: { label: string; percent: number; detai
|
||||||
|
|
||||||
export const SystemWidget = () => {
|
export const SystemWidget = () => {
|
||||||
const alwaysOn = useAlwaysOn();
|
const alwaysOn = useAlwaysOn();
|
||||||
const { w, h, ref } = useSize();
|
|
||||||
const { data } = useQuery<SystemData>({
|
const { data } = useQuery<SystemData>({
|
||||||
queryKey: ['system'],
|
queryKey: ['system'],
|
||||||
queryFn: () => fetch('/api/system').then(r => r.json()),
|
queryFn: () => fetch('/api/system').then(r => r.json()),
|
||||||
refetchInterval: alwaysOn ? 60_000 : 2_000,
|
refetchInterval: alwaysOn ? 60_000 : 2_000,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!data) return <div ref={ref} className="w-full h-full" />;
|
if (!data) return null;
|
||||||
|
|
||||||
const effectiveH = h || 120;
|
|
||||||
const effectiveW = w || 300;
|
|
||||||
|
|
||||||
// Progressive disclosure — fixed text-sm rows, just show more when taller/wider
|
|
||||||
const showDisk = effectiveH > 95;
|
|
||||||
const showUptime = effectiveH > 110 || effectiveW > 450;
|
|
||||||
const showLoadDetail = effectiveH > 140 && effectiveW > 380;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div ref={ref} className="w-full h-full flex flex-col justify-center gap-3 overflow-hidden">
|
<div className="h-full flex flex-col justify-center gap-3">
|
||||||
<div className="flex justify-between items-baseline">
|
<div className="flex justify-between items-baseline">
|
||||||
<span className="font-bold text-lg">{data.hostname}</span>
|
<span className="font-bold text-lg">{data.hostname}</span>
|
||||||
{showUptime && (
|
<span className="text-gray-500 text-sm font-mono">up {data.uptime}</span>
|
||||||
<span className="text-gray-500 text-sm font-mono">up {data.uptime}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
<Row
|
<Row label="CPU" percent={data.cpu.percent} detail={`load ${data.cpu.load[0]} ${data.cpu.load[1]} ${data.cpu.load[2]}`} />
|
||||||
label="CPU"
|
|
||||||
percent={data.cpu.percent}
|
|
||||||
detail={showLoadDetail ? `load ${data.cpu.load.join(' ')}` : `load ${data.cpu.load[0]}`}
|
|
||||||
/>
|
|
||||||
<Row label="MEM" percent={data.memory.percent} detail={`${data.memory.usedGb} / ${data.memory.totalGb} GB`} />
|
<Row label="MEM" percent={data.memory.percent} detail={`${data.memory.usedGb} / ${data.memory.totalGb} GB`} />
|
||||||
{showDisk && (
|
<Row label="DISK" percent={data.disk.percent} detail={`${data.disk.usedGb} / ${data.disk.totalGb} GB`} />
|
||||||
<Row label="DISK" percent={data.disk.percent} detail={`${data.disk.usedGb} / ${data.disk.totalGb} GB`} />
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,42 +1,103 @@
|
||||||
import { useQuery } from '@tanstack/react-query';
|
import { useQuery } from '@tanstack/react-query';
|
||||||
import { useSize } from '../../hooks/useSize';
|
|
||||||
import { WeatherData } from '../../types';
|
import { WeatherData } from '../../types';
|
||||||
|
|
||||||
|
// 5-line ASCII art keyed by condition keyword
|
||||||
const ASCII: Record<string, string[]> = {
|
const ASCII: Record<string, string[]> = {
|
||||||
sunny: [' \\ / ', ' .-. ', ' ― ( ) ―', ' `-\' ', ' / \\ '],
|
sunny: [
|
||||||
partlycloudy: [' \\ / ', ' _ /"".--. ', ' \\_( { ) ', ' `-\'--\' ', ' '],
|
' \\ / ',
|
||||||
cloudy: [' ', ' .--. ', ' .-( ). ', '(___.__)__) ', ' '],
|
' .-. ',
|
||||||
overcast: [' ', ' .------. ', '.-( ).', '(__________.) ', ' '],
|
' ― ( ) ―',
|
||||||
rain: [' .--. ', ' .-( ). ', '(___.__)__) ', " ʻ ʻ ʻ ʻ ", " ʻ ʻ ʻ ʻ "],
|
' `-\' ',
|
||||||
drizzle: [' .--. ', ' .-( ). ', '(___.__)__) ', " , , , , ", " "],
|
' / \\ ',
|
||||||
snow: [' .--. ', ' .-( ). ', '(___.__)__) ', ' * * * ', '* * * * '],
|
],
|
||||||
thunder: [' .--. ', ' .-( ). ', '(___.__)__) ', ' / \\ ', ' / \\ '],
|
partlycloudy: [
|
||||||
fog: [' ', ' _ - _ - _ -', ' _ - _ - _ ', ' _ - _ - _ -', ' '],
|
' \\ / ',
|
||||||
sleet: [' .--. ', ' .-( ). ', '(___.__)__) ', " * ʻ * ʻ ", " ʻ * ʻ * "],
|
' _ /"".--. ',
|
||||||
|
' \\_( { ) ',
|
||||||
|
' `-\'--\' ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
cloudy: [
|
||||||
|
' ',
|
||||||
|
' .--. ',
|
||||||
|
' .-( ). ',
|
||||||
|
'(___.__)__) ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
overcast: [
|
||||||
|
' ',
|
||||||
|
' .------. ',
|
||||||
|
'.-( ).',
|
||||||
|
'(__________.) ',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
rain: [
|
||||||
|
' .--. ',
|
||||||
|
' .-( ). ',
|
||||||
|
'(___.__)__) ',
|
||||||
|
" ʻ ʻ ʻ ʻ ",
|
||||||
|
" ʻ ʻ ʻ ʻ ",
|
||||||
|
],
|
||||||
|
drizzle: [
|
||||||
|
' .--. ',
|
||||||
|
' .-( ). ',
|
||||||
|
'(___.__)__) ',
|
||||||
|
" , , , , ",
|
||||||
|
" ",
|
||||||
|
],
|
||||||
|
snow: [
|
||||||
|
' .--. ',
|
||||||
|
' .-( ). ',
|
||||||
|
'(___.__)__) ',
|
||||||
|
' * * * ',
|
||||||
|
'* * * * ',
|
||||||
|
],
|
||||||
|
thunder: [
|
||||||
|
' .--. ',
|
||||||
|
' .-( ). ',
|
||||||
|
'(___.__)__) ',
|
||||||
|
' / \\ ',
|
||||||
|
' / \\ ',
|
||||||
|
],
|
||||||
|
fog: [
|
||||||
|
' ',
|
||||||
|
' _ - _ - _ -',
|
||||||
|
' _ - _ - _ ',
|
||||||
|
' _ - _ - _ -',
|
||||||
|
' ',
|
||||||
|
],
|
||||||
|
sleet: [
|
||||||
|
' .--. ',
|
||||||
|
' .-( ). ',
|
||||||
|
'(___.__)__) ',
|
||||||
|
" * ʻ * ʻ ",
|
||||||
|
" ʻ * ʻ * ",
|
||||||
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
const MOON_CHAR: Record<string, string> = {
|
const MOON_CHAR: Record<string, string> = {
|
||||||
'New Moon': '🌑', 'Waxing Crescent': '🌒', 'First Quarter': '🌓', 'Waxing Gibbous': '🌔',
|
'New Moon': '🌑', 'Waxing Crescent': '🌒', 'First Quarter': '🌓',
|
||||||
'Full Moon': '🌕', 'Waning Gibbous': '🌖', 'Last Quarter': '🌗', 'Waning Crescent': '🌘',
|
'Waxing Gibbous': '🌔', 'Full Moon': '🌕', 'Waning Gibbous': '🌖',
|
||||||
|
'Last Quarter': '🌗', 'Waning Crescent': '🌘',
|
||||||
};
|
};
|
||||||
|
|
||||||
function getAsciiKey(desc: string): string {
|
function getAsciiKey(desc: string): string {
|
||||||
const d = desc.toLowerCase();
|
const d = desc.toLowerCase();
|
||||||
if (d.includes('thunder')) return 'thunder';
|
if (d.includes('thunder')) return 'thunder';
|
||||||
if (d.includes('snow')) return 'snow';
|
if (d.includes('snow')) return 'snow';
|
||||||
if (d.includes('sleet')) return 'sleet';
|
if (d.includes('sleet')) return 'sleet';
|
||||||
if (d.includes('drizzle')) return 'drizzle';
|
if (d.includes('drizzle')) return 'drizzle';
|
||||||
if (d.includes('rain')) return 'rain';
|
if (d.includes('rain')) return 'rain';
|
||||||
if (d.includes('fog') || d.includes('mist')) return 'fog';
|
if (d.includes('fog') || d.includes('mist') || d.includes('haze')) return 'fog';
|
||||||
if (d.includes('overcast')) return 'overcast';
|
if (d.includes('overcast')) return 'overcast';
|
||||||
if (d.includes('mostly cloudy') || d.includes('very')) return 'cloudy';
|
if (d.includes('mostly cloudy') || d.includes('very cloudy')) return 'cloudy';
|
||||||
if (d.includes('partly') || d.includes('mostly sunny')) return 'partlycloudy';
|
if (d.includes('partly cloudy') || d.includes('mostly sunny')) return 'partlycloudy';
|
||||||
if (d.includes('cloudy')) return 'cloudy';
|
if (d.includes('cloudy')) return 'cloudy';
|
||||||
return 'sunny';
|
if (d.includes('sunny') || d.includes('clear')) return 'sunny';
|
||||||
|
return 'cloudy';
|
||||||
}
|
}
|
||||||
|
|
||||||
export const WeatherWidget = () => {
|
export const WeatherWidget = () => {
|
||||||
const { w, h, ref } = useSize();
|
|
||||||
const { data, isError } = useQuery<WeatherData>({
|
const { data, isError } = useQuery<WeatherData>({
|
||||||
queryKey: ['weather'],
|
queryKey: ['weather'],
|
||||||
queryFn: () => fetch('/api/weather').then(r => r.json()),
|
queryFn: () => fetch('/api/weather').then(r => r.json()),
|
||||||
|
|
@ -44,50 +105,31 @@ export const WeatherWidget = () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
if (isError || !data || (data as any).error) {
|
if (isError || !data || (data as any).error) {
|
||||||
return (
|
return <div className="text-gray-500 text-sm">Weather unavailable</div>;
|
||||||
<div ref={ref} className="w-full h-full flex items-center">
|
|
||||||
<span className="text-gray-500 text-sm">Weather unavailable</span>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const effectiveH = h || 80;
|
const art = ASCII[getAsciiKey(data.description)] ?? ASCII.cloudy;
|
||||||
const effectiveW = w || 350;
|
|
||||||
|
|
||||||
// Progressive disclosure — everything is the same size, just more/less shown
|
|
||||||
const showAscii = effectiveH > 180 && effectiveW > 380;
|
|
||||||
const showHourly = effectiveH > 120 && effectiveW > 260;
|
|
||||||
const showSunMoon = effectiveH > 80 || effectiveW > 460;
|
|
||||||
const maxHours = effectiveW > 500 ? 6 : effectiveW > 380 ? 4 : 3;
|
|
||||||
|
|
||||||
const art = ASCII[getAsciiKey(data.description)] ?? ASCII.cloudy;
|
|
||||||
const moon = MOON_CHAR[data.moonPhase] ?? data.moonPhase;
|
const moon = MOON_CHAR[data.moonPhase] ?? data.moonPhase;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div ref={ref} className="w-full h-full flex items-center gap-4 overflow-hidden">
|
<div className="flex items-start gap-4">
|
||||||
{showAscii && (
|
<pre className="text-gray-300 text-[11px] leading-tight select-none font-mono">{art.join('\n')}</pre>
|
||||||
<pre className="text-gray-300 text-[11px] leading-tight select-none font-mono shrink-0">
|
<div className="flex flex-col gap-1">
|
||||||
{art.join('\n')}
|
<div className="flex items-baseline gap-3">
|
||||||
</pre>
|
|
||||||
)}
|
|
||||||
<div className="flex flex-col gap-1 min-w-0">
|
|
||||||
<div className="flex items-baseline gap-3 flex-wrap">
|
|
||||||
<span className="text-4xl font-bold">{data.temperature}°C</span>
|
<span className="text-4xl font-bold">{data.temperature}°C</span>
|
||||||
<span className="text-lg text-gray-300">{data.description}</span>
|
<span className="text-lg text-gray-300">{data.description}</span>
|
||||||
</div>
|
</div>
|
||||||
{showSunMoon && (
|
<div className="flex gap-4 text-sm text-gray-400 font-mono">
|
||||||
<div className="flex flex-wrap gap-4 text-sm text-gray-400 font-mono">
|
<span>↑ {data.sunrise}</span>
|
||||||
<span>↑ {data.sunrise}</span>
|
<span>↓ {data.sunset}</span>
|
||||||
<span>↓ {data.sunset}</span>
|
<span title={data.moonPhase}>{moon} {data.moonPhase}</span>
|
||||||
<span title={data.moonPhase}>{moon} {data.moonPhase}</span>
|
</div>
|
||||||
</div>
|
{data.hourly.length > 0 && (
|
||||||
)}
|
|
||||||
{showHourly && data.hourly.length > 0 && (
|
|
||||||
<div className="flex gap-3 mt-1">
|
<div className="flex gap-3 mt-1">
|
||||||
{data.hourly.slice(0, maxHours).map((entry, i) => (
|
{data.hourly.map((h, i) => (
|
||||||
<div key={i} className="text-center shrink-0">
|
<div key={i} className="text-center">
|
||||||
<div className="text-xs text-gray-500">{entry.time}</div>
|
<div className="text-xs text-gray-500">{h.time}</div>
|
||||||
<div className="text-sm font-bold">{entry.temp}°</div>
|
<div className="text-sm font-bold">{h.temp}°</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { createContext, useContext } from "react";
|
import { createContext, useContext } from 'react';
|
||||||
|
|
||||||
export const AlwaysOnContext = createContext(false);
|
export const AlwaysOnContext = createContext(false);
|
||||||
export const useAlwaysOn = () => useContext(AlwaysOnContext);
|
export const useAlwaysOn = () => useContext(AlwaysOnContext);
|
||||||
|
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
import { useCallback, useRef, useState } from 'react';
|
|
||||||
|
|
||||||
/** Measures a div's content box via ResizeObserver. Attach `ref` to the element. */
|
|
||||||
export function useSize() {
|
|
||||||
const [size, setSize] = useState({ w: 0, h: 0 });
|
|
||||||
const roRef = useRef<ResizeObserver | null>(null);
|
|
||||||
|
|
||||||
const ref = useCallback((el: HTMLDivElement | null) => {
|
|
||||||
roRef.current?.disconnect();
|
|
||||||
if (!el) return;
|
|
||||||
roRef.current = new ResizeObserver(([entry]) => {
|
|
||||||
const { width, height } = entry.contentRect;
|
|
||||||
setSize({ w: Math.round(width), h: Math.round(height) });
|
|
||||||
});
|
|
||||||
roRef.current.observe(el);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
return { ...size, ref };
|
|
||||||
}
|
|
||||||
|
|
@ -11,10 +11,8 @@ import { Config, Departure, SBBDeparture, WidgetId, ZoneId } from '../types';
|
||||||
|
|
||||||
const fetchJson = (url: string) => fetch(url).then(r => r.json());
|
const fetchJson = (url: string) => fetch(url).then(r => r.json());
|
||||||
|
|
||||||
const FOOTER_ZONES: ZoneId[] = ['footer-1', 'footer-2', 'footer-3'];
|
const FOOTER_ZONES: ZoneId[] = ['footer-1', 'footer-2', 'footer-3'];
|
||||||
const DEPARTURE_IDS: WidgetId[] = ['sl', 'sbb'];
|
const DEPARTURE_WIDGETS: WidgetId[] = ['sl', 'sbb'];
|
||||||
|
|
||||||
// ── Dashboard ─────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
export const Dashboard = () => {
|
export const Dashboard = () => {
|
||||||
const { data: config } = useQuery<Config>({
|
const { data: config } = useQuery<Config>({
|
||||||
|
|
@ -23,110 +21,121 @@ export const Dashboard = () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
const alwaysOn = !!config?.alwaysOn;
|
const alwaysOn = !!config?.alwaysOn;
|
||||||
const layout = config?.layout ?? {};
|
const layout = config?.layout ?? {};
|
||||||
|
|
||||||
const inLayout = (id: WidgetId) => Object.values(layout).includes(id);
|
const inLayout = (id: WidgetId) => Object.values(layout).includes(id);
|
||||||
|
|
||||||
// In alwaysOn mode, tick once per minute to keep departure times current
|
|
||||||
const [, tick] = useReducer(x => x + 1, 0);
|
const [, tick] = useReducer(x => x + 1, 0);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!alwaysOn) return;
|
if (!alwaysOn) return;
|
||||||
let interval: ReturnType<typeof setInterval>;
|
let id: ReturnType<typeof setInterval>;
|
||||||
const now = new Date();
|
const schedule = () => {
|
||||||
const msUntilNext = (60 - now.getSeconds()) * 1000 - now.getMilliseconds();
|
const now = new Date();
|
||||||
const timeout = setTimeout(() => { tick(); interval = setInterval(tick, 60_000); }, msUntilNext);
|
const msUntilNext = (60 - now.getSeconds()) * 1000 - now.getMilliseconds();
|
||||||
return () => { clearTimeout(timeout); clearInterval(interval); };
|
return setTimeout(() => { tick(); id = setInterval(tick, 60_000); }, msUntilNext);
|
||||||
|
};
|
||||||
|
const timeout = schedule();
|
||||||
|
return () => { clearTimeout(timeout); clearInterval(id); };
|
||||||
}, [alwaysOn]);
|
}, [alwaysOn]);
|
||||||
|
|
||||||
// Data fetching — only enabled when the widget is actually in the layout
|
const { data: slData, isLoading: slLoading } = useQuery<{ departures: Departure[] }>({
|
||||||
const { data: slData, isLoading: slLoading } = useQuery<{ departures: Departure[] }>({
|
|
||||||
queryKey: ['sl-departures', config?.sl?.stationId],
|
queryKey: ['sl-departures', config?.sl?.stationId],
|
||||||
queryFn: () => fetchJson(`/api/sl/departures/${config!.sl.stationId}`),
|
queryFn: () => fetchJson(`/api/sl/departures/${config!.sl.stationId}`),
|
||||||
enabled: inLayout('sl') && !!config?.sl?.stationId,
|
enabled: inLayout('sl') && !!config?.sl?.stationId,
|
||||||
refetchInterval: alwaysOn ? 60_000 : (config?.refreshRate ?? 30_000),
|
refetchInterval: alwaysOn ? 60_000 : (config?.refreshRate ?? 30_000),
|
||||||
});
|
});
|
||||||
|
|
||||||
const { data: sbbData, isLoading: sbbLoading } = useQuery<{ stationboard: SBBDeparture[] }>({
|
const { data: sbbData, isLoading: sbbLoading } = useQuery<{ stationboard: SBBDeparture[] }>({
|
||||||
queryKey: ['sbb-departures', config?.sbb?.stationId],
|
queryKey: ['sbb-departures', config?.sbb?.stationId],
|
||||||
queryFn: () => fetchJson(`/api/sbb/departures/${config!.sbb.stationId}`),
|
queryFn: () => fetchJson(`/api/sbb/departures/${config!.sbb.stationId}`),
|
||||||
enabled: inLayout('sbb') && !!config?.sbb?.stationId,
|
enabled: inLayout('sbb') && !!config?.sbb?.stationId,
|
||||||
refetchInterval: alwaysOn ? 60_000 : (config?.refreshRate ?? 30_000),
|
refetchInterval: alwaysOn ? 60_000 : (config?.refreshRate ?? 30_000),
|
||||||
});
|
});
|
||||||
|
|
||||||
const slName = slData?.departures[0]?.stop_area?.name || config?.sl?.stationName || 'SL';
|
|
||||||
const sbbName = config?.sbb?.stationName || 'SBB';
|
|
||||||
|
|
||||||
// ── Widget factory ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const renderWidget = (id: WidgetId | undefined) => {
|
const renderWidget = (id: WidgetId | undefined) => {
|
||||||
if (!id || id === 'spacer') return null;
|
if (!id || id === 'spacer') return null;
|
||||||
switch (id) {
|
switch (id) {
|
||||||
case 'clock': return <Clock />;
|
case 'clock': return <div className="h-full flex items-center"><Clock /></div>;
|
||||||
case 'weather': return <WeatherWidget />;
|
case 'weather': return <div className="h-full flex items-center"><WeatherWidget /></div>;
|
||||||
case 'spotify': return <SpotifyWidget />;
|
case 'spotify': return <SpotifyWidget />;
|
||||||
case 'system': return <SystemWidget />;
|
case 'system': return <SystemWidget />;
|
||||||
case 'sl': return <DepartureList departures={slData?.departures ?? []} loading={slLoading} stationName={slName} />;
|
case 'sl':
|
||||||
case 'sbb': return <SBBDepartureList departures={sbbData?.stationboard ?? []} loading={sbbLoading} stationName={sbbName} />;
|
return (
|
||||||
|
<div className="h-full flex flex-col">
|
||||||
|
<h2 className={`text-xl uppercase tracking-wider shrink-0 pb-1 ${alwaysOn ? 'font-normal' : 'font-bold'}`}>
|
||||||
|
{slData?.departures[0]?.stop_area?.name || config?.sl?.stationName || 'SL'}
|
||||||
|
</h2>
|
||||||
|
<DepartureList departures={slData?.departures ?? []} loading={slLoading} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
case 'sbb':
|
||||||
|
return (
|
||||||
|
<div className="h-full flex flex-col">
|
||||||
|
<h2 className={`text-xl uppercase tracking-wider shrink-0 pb-1 ${alwaysOn ? 'font-normal' : 'font-bold'}`}>
|
||||||
|
{config?.sbb?.stationName || 'SBB'}
|
||||||
|
</h2>
|
||||||
|
<SBBDepartureList departures={sbbData?.stationboard ?? []} loading={sbbLoading} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// ── Layout derivations ───────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const headerLeft = layout['header-left'];
|
const headerLeft = layout['header-left'];
|
||||||
const headerRight = layout['header-right'];
|
const headerRight = layout['header-right'];
|
||||||
const main1 = layout['main-1'];
|
const main1 = layout['main-1'];
|
||||||
const main2 = layout['main-2'];
|
const main2 = layout['main-2'];
|
||||||
const footerWidgets = FOOTER_ZONES.map(z => layout[z]).filter((w): w is WidgetId => w != null);
|
// Keep spacers — they hold intentional empty slots, only collapse truly unset zones
|
||||||
|
const footerWidgets = FOOTER_ZONES.map(z => layout[z]).filter(w => w != null) as WidgetId[];
|
||||||
|
|
||||||
const hasHeader = !!(headerLeft || headerRight);
|
const hasHeader = headerLeft || headerRight;
|
||||||
const hasMain = !!(main1 && main1 !== 'spacer') || !!(main2 && main2 !== 'spacer');
|
// spacer alone doesn't count as real content
|
||||||
const hasFooter = footerWidgets.some(w => w !== 'spacer');
|
const hasMain = (main1 && main1 !== 'spacer') || (main2 && main2 !== 'spacer');
|
||||||
const footerHasDeps = footerWidgets.some(w => DEPARTURE_IDS.includes(w));
|
const hasFooter = footerWidgets.filter(w => w !== 'spacer').length > 0;
|
||||||
|
|
||||||
// Zone class: fills its grid/flex cell and prevents content from overflowing
|
const footerHasDeps = footerWidgets.some(w => DEPARTURE_WIDGETS.includes(w));
|
||||||
const zone = 'h-full min-h-0 min-w-0 overflow-hidden';
|
|
||||||
|
|
||||||
// Footer height: departure lists need more room; info-only widgets get 20 vh
|
// Footer sizing: takes 40% of viewport when holding departure lists so rows are visible.
|
||||||
|
// When only info widgets: auto-height. When no main: expands to fill.
|
||||||
const footerStyle: React.CSSProperties = !hasMain
|
const footerStyle: React.CSSProperties = !hasMain
|
||||||
? { flex: '1 1 0', minHeight: 0 }
|
? { flex: '1 1 0', minHeight: 0 }
|
||||||
: footerHasDeps
|
: footerHasDeps
|
||||||
? { flex: '0 0 40%', minHeight: 0 }
|
? { flex: '0 0 40%', minHeight: 0 }
|
||||||
: { flex: '0 0 20%', minHeight: '120px' };
|
: { flex: '0 0 auto', minHeight: '140px' };
|
||||||
|
|
||||||
// ── Render ───────────────────────────────────────────────────────────────────
|
// Zone wrapper: min-h-0 prevents a child from inflating beyond the slot
|
||||||
|
const zoneClass = 'min-h-0 min-w-0 overflow-hidden';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AlwaysOnContext.Provider value={alwaysOn}>
|
<AlwaysOnContext.Provider value={alwaysOn}>
|
||||||
<div className="flex flex-col h-screen w-screen p-6 gap-4 overflow-hidden">
|
<div className="flex flex-col h-screen w-screen p-6 gap-4 overflow-hidden">
|
||||||
|
|
||||||
{hasHeader && (
|
{hasHeader && (
|
||||||
<div
|
<div className="flex items-center justify-between border-b border-white pb-4 shrink-0">
|
||||||
className="flex items-stretch justify-between border-b border-white pb-4 shrink-0"
|
<div className={`flex-1 ${zoneClass}`}>{renderWidget(headerLeft)}</div>
|
||||||
style={{ minHeight: '72px' }}
|
{headerRight && <div className={`flex-shrink-0 ml-8 ${zoneClass}`}>{renderWidget(headerRight)}</div>}
|
||||||
>
|
|
||||||
<div className={`flex-1 ${zone}`}>{renderWidget(headerLeft)}</div>
|
|
||||||
{headerRight && (
|
|
||||||
<div className={`flex-shrink-0 ml-8 ${zone}`}>{renderWidget(headerRight)}</div>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{hasMain && (
|
{hasMain && (
|
||||||
<div
|
<div
|
||||||
className={main1 && main2 ? 'grid grid-cols-2 gap-6' : 'flex'}
|
className={`${main1 && main2 ? 'grid grid-cols-2 gap-6' : 'flex'}`}
|
||||||
style={{ flex: '1 1 0', minHeight: 0 }}
|
style={{ flex: '1 1 0', minHeight: 0 }}
|
||||||
>
|
>
|
||||||
{main1 && <div className={`${!main2 ? 'flex-1' : ''} ${zone}`}>{renderWidget(main1)}</div>}
|
{main1 && <div className={`${main1 && main2 ? '' : 'flex-1'} ${zoneClass}`}>{renderWidget(main1)}</div>}
|
||||||
{main2 && <div className={zone}>{renderWidget(main2)}</div>}
|
{main2 && <div className={zoneClass}>{renderWidget(main2)}</div>}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{hasFooter && (
|
{hasFooter && (
|
||||||
<div
|
<div
|
||||||
className="border-t border-white pt-4 grid gap-6"
|
className="border-t border-white pt-4 grid gap-6"
|
||||||
style={{ ...footerStyle, gridTemplateColumns: `repeat(${footerWidgets.length}, 1fr)` }}
|
style={{
|
||||||
|
...footerStyle,
|
||||||
|
gridTemplateColumns: `repeat(${footerWidgets.length}, 1fr)`,
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{footerWidgets.map((w, i) => (
|
{footerWidgets.map((w, i) => (
|
||||||
<div key={`${w}-${i}`} className={zone}>{renderWidget(w)}</div>
|
<div key={`${w}-${i}`} className={`${zoneClass} h-full`}>{renderWidget(w)}</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue