feat: 中文界面、键盘控制、车手名单、名次脚本与 OBS 输出

- 键盘控制:数字按名次选车、方向键移动光标、出/收字幕、圈数 +/-、计时器、
  名次脚本、快捷键总表;在输入框里打字时不触发,每次按键都有 Toast 反馈
- 车手名单编辑器(E):姓名/缩写/车号/国籍/车队/性能/黄T摄/头像均可改,
  支持调整发车顺位、单条重置、全部重置、JSON 导入导出,localStorage 持久化
- LAP 可手动 +/-,LAP 旁新增 mm:ss.mmm 计时器(零点=计时榜出现的瞬间)
- 名次脚本(J):JSON 预设,以计时器为零点,支持 swap/move/retire/restore/lap 与 order
  * 改脚本即时生效并从零重播,修掉"改完之后过期事件被一次性爆发"的问题
  * order 立即铺回赛道;写错会在状态条里报出具体原因,不再静默失败
  * localStorage 持久化,刷新不再丢失
- 合并 feature/standalone-output:OBS 透明输出页 /output 与 WebSocket 中继 server/relayServer.js
  * 修复中继晚连接的输出页只能收到最后一片补丁(缓存改为合并累加)
- 修复 react-spring 缺少 deps 导致进场动画被每次渲染重启
  (chyron、百叶窗、wipe、计时塔名次描边)
- 界面中文化(上屏的转播图形保持英文),F1 字体栈补 CJK 回退
- 新增「启动开发服务器.cmd」一键启动,.gitignore 排除本地工具目录
This commit is contained in:
DeepSeek Harness committed 2026-10-20 21:26:50 +08:00
1 parent ed5c6e752c
commit 9528307820
78 files changed
+5066 -438

No files matched your search

+6
View File
@@ -21,3 +21,9 @@
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local tooling scratch (agent browser profile, temp builds)
.cdp-headed/
.cdp-profile/
.dsh-tmp/
*.log
+180
View File
@@ -3,6 +3,73 @@ Hello! What you've stumbled upon is a personal practice web development project
I've probably written 98% of all the CSS I've ever written in my life in this project alone. While I'm not exactly a master (yet) I feel entirely capable of taking design directions from a designer and building the CSS that is needed to create it in the real world.
# 独立转播输出(给 OBS 用)
可以把广播画面推到**一个独立的透明输出页**上,通过一个 WebSocket 中继转发,这样 OBS
(或任何其它渲染器)可以直接把图形叠到画面上,而控制端继续在普通浏览器标签里操作。
## 运行
```bash
# 1. 启动前端(控制页和输出页都由它提供)
npm start
# 2. 另开一个终端,启动 WebSocket 中继(默认端口 8181)
npm run relay
```
然后打开:
* **控制端**:http://localhost:3000/broadcast (任何 UI 页面都可以)
* **输出端**:http://localhost:3000/output —— 透明、只有图形
## 在 OBS 里使用
添加一个 **浏览器(Browser)** 源:
* URL:`http://localhost:3000/output`
* 宽度 `1920`、高度 `1080`
* 透明度是自动的(这一页不画任何背景)。按需勾选「源不可见时关闭」
* 建议勾选「场景激活时刷新浏览器」,源重连后中继会把最后一次状态重放给它
## URL 参数
| 页面 | 参数 | 作用 |
| --- | --- | --- |
| `/output` | `?debug=1` | 画出 1920x1080 安全框和连接状态角标 |
| `/output` | `?ws=ws://host:port` | 指定中继地址(例如局域网另一台机器:`?ws=ws://192.168.1.20:8181`) |
| 控制端页面 | `?bridge=0` | 这个标签页不向中继发布状态 |
中继可以用 `RELAY_PORT` / `RELAY_HOST` 配置(默认 `8181` / `0.0.0.0`),
控制端也可以用 `REACT_APP_RELAY_URL` 指向别处。
> **同时只开一个控制端标签页。** 中继允许任意多个 controller 连接,但每个标签页都会发布自己的
> store,两个控制端会互相覆盖状态(输出页就会闪来闪去)。多余的标签页请关掉,或者加上
> `?bridge=0` 让它只当观众。
>
> 输出页显示不正常时,先看 `http://localhost:8181/health`:`controllers` 应该是 1、
> `hasState` 应该是 `true`;输出页加 `?debug=1` 会画出连接状态和「最后一次收到数据」的时间。
## 实现
* `src/components/Output/OutputRoute.tsx` —— 无外壳的输出页:只渲染计时榜、字幕和 logo,
按窗口等比缩放,背景透明。
* `src/components/Output/BroadcastBridge.tsx` —— 挂在外壳里;节流(约 20Hz)把广播相关的
Redux 切片推给中继。
* `src/features/outputChannel/` —— 自动重连的 WebSocket 客户端,以及用来把远端状态镜像进
本地 store 的 snapshot action。
* `server/relayServer.js` —— 极简 `ws` 中继:缓存最后一份状态、广播给所有输出端、
忽略输出端发来的状态。健康检查:`GET /health`。
## 快速开始(中文)
控制界面是中文的;上屏的转播图形保持英文,因为它们是在还原 F1 世界转播信号本身的样子。
**Windows 一键启动**:双击项目根目录里的 **`启动开发服务器.cmd`**。
**命令行启动**:
```bash
npm install # 第一次才需要
npm start
```
然后打开 [localhost:3000](http://localhost:3000)。日常操作都在 **转播控制台**(`/broadcast`)页,
进去以后按 <kbd>?</kbd> 就能看到全部快捷键。
# Demos
*Please note that animated images on this page are in WEBP format and may have performance issues (a lowered framerate) depending on your device. Animations are buttery smooth in practice! View the videos below if they're slow for you!*
@@ -170,6 +237,119 @@ I've learned a little bit about, say, using OBS to overlay websites as a transpa
If you somehow have the interest AND the skills to do such a thing I fully welcome you to reach out to me and tell me about it. If someone (or a group of people) could continue my work I'd not only give my permission but some of my support as well.
# Directing a broadcast
The broadcast can be driven without ever touching the mouse.
*The control interface is in Chinese. The on-air graphics are deliberately left
in English - they replicate the F1 world feed, so `LAP 1/44`, `Leader` and
`OUT` stay exactly as a viewer would see them. All interface text lives in the
components plus the shared label maps in `src/i18n/labels.ts`.*
## Keyboard control
Press `?` at any time (or click the keyboard button next to the chyron buttons)
to bring up the list inside the app itself.
| Keys | Action |
| --- | --- |
| `E` | Show / hide the driver roster editor |
| `?` | Show / hide the shortcut list |
| `Esc` | Close a panel, otherwise close the chyron |
| `↑` `↓` | Move the cursor along the running order |
| `Home` `End` | Jump the cursor to the leader or the last car |
| `Space` | Add or remove the cursor car from the selection |
| `1` … `9` `0` | Select the car running in P1 … P10 |
| `Shift` + `1` … `0` | Add that car as the second chyron driver |
| `X` | Clear the selection |
| `Enter` | Show a chyron for the selection, or the cursor car |
| `Shift` + `Enter` | Play the next step of the chyron animation |
| `Backspace` | Close the chyron |
| `[` `]` | Cycle the chyron mode |
| `,` `.` | Cycle the chyron sub mode |
| `F` | Cycle the flag: country, team, none |
| `P` | Toggle the position flag |
| `N` | Toggle the driver number |
| `O` | Toggle the portrait |
| `S` | Start / stop the event |
| `R` | Recalculate the running order |
| `Shift` + `P` | Send the selected car 200 m up the road |
| `Shift` + `O` | Send every car 100 m up the road |
| `Shift` + `F` | Award the fastest lap to the selected car |
| `D` | Retire / un-retire the selected car |
| `T` | Cycle the timing tower display mode |
| `I` | Switch between leader and interval splits |
| `+` `=` | Push the LAP counter one lap further on |
| `-` | Take the LAP counter one lap back |
| `C` | Start / pause the show clock beside LAP |
| `Shift` + `C` | Back to zero and replay the position script |
| `J` | Show / hide the JSON position script |
Shortcuts never fire while you are typing in a field, and every press answers
with a short toast at the bottom of the screen so you can tell what landed
without looking away from the video.
The whole list lives in `src/features/keyboard/shortcuts.ts`. The handler beside
it implements that same table and the help overlay renders it, so the on-screen
documentation cannot drift away from the real bindings.
## Driver roster editor
Press `E`, or use the roster button next to the chyron buttons.
* First name, last name, three letter code, car number, nationality, team,
performance and yellow T-Cam are editable, per car.
* The portrait can be pointed at any portrait bundled in
`src/public/images/drivers/front`.
* Edits are written straight into the event state, so the chyrons and the timing
tower redraw as you type - there is no apply step.
* `▲` / `▼` move a driver up or down the starting grid, `↺` restores a single
driver and `Reset all` restores the shipped 2021 lineup.
* The roster is kept in `localStorage` as you edit, and `Export JSON` /
`Import JSON` move a lineup between machines.
A driver whose fields are never touched behaves exactly as before: the portrait
still defaults to the driver's own id, so none of the stock data changed.
## The show clock and the LAP counter
The status indicator in the top left corner carries two extra readouts:
* **LAP** can be nudged by hand with `+` and `-`. The offset is remembered
separately from the lap the simulation derives from the leader's distance, so
the two never fight each other.
* **The show clock** sits beside it and counts `mm:ss.mmm` from the moment the
timing graphics appeared. `C` pauses it, `Shift` + `C` puts it back to zero.
## Position script
Press `J` (or the code button beside the chyron buttons) for a JSON schedule of
running order changes. Its zero *is* the show clock, so the same file replays
identically on every run.
```json
{
"autoStart": true,
"order": ["VER", "HAM", "BOT", "PER", "SAI", "NOR", "LEC", "RIC", "GAS", "ALO",
"OCO", "VET", "STR", "TSU", "RUS", "RAI", "LAT", "GIO", "MSC", "MAZ"],
"events": [
{ "at": "00:05.000", "action": "swap", "drivers": ["HAM", "VER"] },
{ "at": "00:12.000", "action": "move", "driver": "LEC", "to": 3 },
{ "at": "00:18.500", "action": "lap", "value": 1 },
{ "at": "00:24.000", "action": "retire", "driver": "MAZ" },
{ "at": "00:31.000", "action": "restore", "driver": "MAZ" }
]
}
```
* `at` is milliseconds or `"mm:ss.mmm"` after zero.
* `action` is `swap`, `move`, `retire`, `restore` or `lap`.
* A driver may be named by id (`verstappen`), code (`VER`), surname
(`Verstappen`) or car number (`33`).
* `order` is optional and is put back on the track every time the clock resets,
which is what makes "Reset & replay" reproduce the same show.
* Editing is live: a valid schedule takes effect immediately, an invalid one
reports itself and keeps the previous schedule running.
Reshuffling gives each car the track position of the rank it moves into, so the
gaps - and the interval column - survive untouched, and the timing tower plays
its position change animation exactly as it does during a real race.
# How to download and run
Here I'll do my best to guide you to try this project on your own
+3 -1
View File
@@ -46,10 +46,12 @@
"rooks": "^5.10.3",
"styled-components": "^5.3.3",
"typescript": "^4.4.2",
"web-vitals": "^2.1.0"
"web-vitals": "^2.1.0",
"ws": "^8.3.0"
},
"scripts": {
"start": "react-scripts start",
"relay": "node server/relayServer.js",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
+155
View File
@@ -0,0 +1,155 @@
/**
* SAB F1 UI - broadcast output relay.
*
* A tiny WebSocket relay that lets the controller app (the broadcast/workspaces
* UI) push its graphics state to one or more independent output pages, e.g. an
* OBS browser source running http://localhost:3000/output.
*
* Run with: npm run relay (or: node server/relayServer.js)
*
* Clients connect to ws://<host>:<port>/?role=controller|output
* Protocol (JSON):
* controller -> relay : { "type": "hello", "role": "controller" }
* { "type": "state", "payload": { ...redux slices... } }
* relay -> output : { "type": "welcome", "role": "output", ... }
* { "type": "state", "payload": { ... } }
* The relay caches the last state, so a browser source that (re)connects always
* gets a picture immediately, even if the controller is idle.
*/
const http = require("http");
const { WebSocketServer } = require("ws");
const PORT = Number(process.env.RELAY_PORT || 8181);
const HOST = process.env.RELAY_HOST || "0.0.0.0";
let lastState = null;
let controllerCount = 0;
let outputCount = 0;
function log(...args) {
console.log("[relay " + new Date().toISOString() + "]", ...args);
}
const server = http.createServer((req, res) => {
res.setHeader("access-control-allow-origin", "*");
if (req.url && req.url.split("?")[0] === "/health") {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({
ok: true,
controllers: controllerCount,
outputs: outputCount,
hasState: lastState != null,
}));
return;
}
res.writeHead(200, { "content-type": "text/plain" });
res.end(
"sab-f1-ui broadcast relay\n" +
"ws://<host>:" + PORT + "/?role=controller|output\n" +
"health: http://<host>:" + PORT + "/health\n",
);
});
const wss = new WebSocketServer({ server });
function send(ws, message) {
if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(message));
}
wss.on("connection", (ws, req) => {
const requestUrl = new URL(req.url || "/", "http://localhost");
ws.role = requestUrl.searchParams.get("role") === "controller" ? "controller" : "output";
ws.isAlive = true;
if (ws.role === "controller") controllerCount += 1;
else outputCount += 1;
log(ws.role + " connected from " + (req.socket.remoteAddress || "?") +
" (" + controllerCount + " controllers, " + outputCount + " outputs)");
send(ws, { type: "welcome", role: ws.role, controllers: controllerCount, outputs: outputCount });
// A freshly connected output gets the current picture right away.
if (ws.role === "output" && lastState != null) send(ws, lastState);
ws.on("message", (raw) => {
let message;
try {
message = JSON.parse(raw.toString());
} catch (error) {
return;
}
if (message == null || typeof message !== "object") return;
if (message.type === "hello") {
send(ws, { type: "welcome", role: ws.role, controllers: controllerCount, outputs: outputCount });
return;
}
if (message.type === "state") {
// Only a controller may drive the output.
if (ws.role !== "controller") return;
/**
* Cache the *merged* picture, not just this patch.
*
* The controller sends incremental patches (only the slices whose
* reference changed), so caching the raw message meant an output that
* connected later - OBS refreshing a browser source when its scene
* becomes active, or any reconnect - received only whichever slices
* happened to change in the very last transition. It would render the
* timing tower but no chyron, or the reverse, until the controller
* touched the missing slice again.
*/
lastState = {
type: "state",
payload: Object.assign({}, lastState && lastState.payload, message.payload),
};
// Live outputs still get the small patch; they merge it themselves.
const data = JSON.stringify(message);
wss.clients.forEach((client) => {
if (client !== ws && client.role === "output" && client.readyState === client.OPEN) {
client.send(data);
}
});
return;
}
if (message.type === "ping") {
send(ws, { type: "pong" });
}
});
ws.on("pong", () => { ws.isAlive = true; });
ws.on("close", () => {
if (ws.role === "controller") controllerCount -= 1;
else outputCount -= 1;
log(ws.role + " disconnected (" + controllerCount + " controllers, " + outputCount + " outputs)");
});
ws.on("error", (error) => log(ws.role + " error: " + error.message));
});
const heartbeat = setInterval(() => {
wss.clients.forEach((ws) => {
if (ws.isAlive === false) {
ws.terminate();
return;
}
ws.isAlive = false;
try {
ws.ping();
} catch (error) {
// Ignore, the close handler will clean up.
}
});
}, 30000);
wss.on("close", () => clearInterval(heartbeat));
server.listen(PORT, HOST, () => {
log("relay listening on ws://" + HOST + ":" + PORT + " (health http://" + HOST + ":" + PORT + "/health)");
});
+4
View File
@@ -9,6 +9,8 @@ import { MainMenu } from "./components/Menu";
import { useDispatch } from "react-redux";
import { useEffect } from "react";
import { EventLoop } from "./components/Broadcast/RaceDirectorUI/EventLoop/EventLoop";
import { BroadcastControlLayer } from "./components/BroadcastControlLayer";
import { BroadcastBridge } from "./components/Output";
function App() {
const dispatch = useDispatch();
@@ -42,6 +44,8 @@ function App() {
<MainMenu ref={mainMenuRef} />
<Outlet />
<EventLoop />
<BroadcastControlLayer />
<BroadcastBridge />
</div>
);
}
@@ -3,122 +3,104 @@ import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Stack } from "@bedrock-layout/stack";
import { Inline } from "@bedrock-layout/inline";
import { FaCheck, FaStepForward, FaTimes } from "react-icons/fa";
import { FaCheck, FaCode, FaKeyboard, FaStepForward, FaTimes, FaUserEdit } from "react-icons/fa";
import { broadcastGraphicsSelector } from "../../../../features/broadcast/graphics/broadcastGraphicsSelector";
import { broadcastDirectorSelector } from "../../../../features/broadcast/director/broadcastDirectorSelector";
import { eventSelector } from "../../../../features/event/eventSelector";
import { uiSelector } from "../../../../features/ui/uiSelector";
import {
incrementChyronsOpenState,
setChyrons,
setChyronsOpenState,
} from "../../../../features/broadcast/graphics/broadcastGraphicsSlice";
toggleDriverEditor,
togglePositionScript,
toggleShortcutHelp,
} from "../../../../features/ui/uiSlice";
import { updateChyronSettings } from "../../../../features/broadcast/director/broadcastDirectorSlice";
import { useChyronDirector } from "../../../../features/broadcast/director/useChyronDirector";
import { flagModeList, getChyronModesList, getChyronSubModesList } from "../../../../domain/data/broadcastGraphics";
import { BGChyronDriver, BGChyronMode, BGChyrons, BGChyronSubMode, FlagMode, GridSpot } from "../../../../types/state";
import { BGChyronMode, BGChyronSubMode, FlagMode } from "../../../../types/state";
import {
chyronModeLabels,
chyronSubModeLabels,
flagModeLabels,
labelOf,
} from "../../../../i18n/labels";
import { SlotSelector } from "../../../Common/Inputs/SlotSelector";
import { Button, CloseButton, OpenButton, Title } from "./styles";
import { Toggle } from "../../../Common/Inputs/Toggle";
import {
Button,
CloseButton,
OpenButton,
PanelButton,
ShortcutBar,
ShortcutItem,
ShortcutKey,
Title,
} from "./styles";
/**
* The chyron director's panel.
*
* Everything it sets lives in the store rather than in local state, so the
* keyboard layer can drive the exact same settings and the panel always shows
* what the next chyron will look like.
*/
export function ChyronsDirectorControls() {
// Use state to prevent unnecessary resetting on re-renders.
const [chyronModes] = useState<Array<BGChyronMode>>(getChyronModesList());
const [chyronSubModes, setChyronSubModes] = useState<Array<BGChyronSubMode>>([]);
// Interface states.
const [chyronMode, setChyronMode] = useState<BGChyronMode>("driver");
const [chyronSubMode, setChyronSubMode] = useState<BGChyronSubMode>("medium");
const [posFlag, setPosFlag] = useState(true);
const [driverNum, setDriverNum] = useState(true);
const [portrait, setPortrait] = useState(false);
const [flagMode, setFlagMode] = useState<FlagMode>("country");
// Central state.
const dispatch = useDispatch();
const { chyrons } = useSelector(broadcastGraphicsSelector);
const { selectedCars } = useSelector(broadcastDirectorSelector);
const { grid } = useSelector(eventSelector);
const { chyronSettings } = useSelector(broadcastDirectorSelector);
const { driverEditorOpen, shortcutHelpOpen, positionScriptOpen } = useSelector(uiSelector);
const chyron = useChyronDirector();
const {
mode: chyronMode,
subMode: chyronSubMode,
flagMode,
showPosFlag,
showDriverNumber,
showPortrait,
} = chyronSettings;
// Handle changes to the chyron mode so submodes can be changed accordingly.
useEffect(() => {
setChyronSubModes(getChyronSubModesList(chyronMode));
}, [chyronMode]);
const onOpen = () => {
buildDriver();
setTimeout(() => {
// Delay a short time and increment the open state so the animation can happen.
dispatch(incrementChyronsOpenState());
}, 50);
};
const onNext = () => {
dispatch(incrementChyronsOpenState());
};
const onClose = () => {
dispatch(setChyronsOpenState(-1));
};
const buildDriver = () => {
if (selectedCars.length === 0) return;
let primaryCarGridSpot = selectedCars[0];
let secondaryCarGridSpot = selectedCars[1] ?? -1;
// Auto-sort drivers by position so trailing car appears second on mounting.
if (chyronSubMode === "medium" && secondaryCarGridSpot != -1
&& grid[secondaryCarGridSpot].position < grid[primaryCarGridSpot].position) {
secondaryCarGridSpot = selectedCars[0];
primaryCarGridSpot = selectedCars[1];
}
const newChyrons: BGChyrons = {
openState: 0,
mode: chyronMode,
subMode: chyronSubMode,
driver: {
primary: buildDriverChyron(primaryCarGridSpot),
secondary: secondaryCarGridSpot !== -1
? buildDriverChyron(secondaryCarGridSpot) : null,
},
};
dispatch(setChyrons(newChyrons));
};
const buildDriverChyron = (carGridSpot: GridSpot): BGChyronDriver => ({
carGridSpot,
flagMode,
showPosFlag: posFlag,
showDriverNumber: driverNum,
showPortrait: chyronSubMode === "large" ? false : portrait,
});
const modeIndex = Math.max(0, chyronModes.indexOf(chyronMode));
const subModeIndex = Math.max(0, chyronSubModes.indexOf(chyronSubMode));
const flagModeIndex = Math.max(0, flagModeList.indexOf(flagMode));
const modeControls = (mode: BGChyronMode, subMode: BGChyronSubMode) => {
if (mode === "driver") {
return (
<InlineCluster gutter="md">
<Toggle
label="Pos. Flag"
toggled={posFlag}
onToggle={setPosFlag}
label="名次牌"
toggled={showPosFlag}
onToggle={value => dispatch(updateChyronSettings({ showPosFlag: value }))}
/>
<Toggle
label="Driver Num."
toggled={driverNum}
onToggle={setDriverNum}
label="车号"
toggled={showDriverNumber}
onToggle={value => dispatch(updateChyronSettings({ showDriverNumber: value }))}
/>
{subMode === "medium" && (
<Toggle
label="Portrait"
toggled={portrait}
onToggle={setPortrait}
label="头像"
toggled={showPortrait}
onToggle={value => dispatch(updateChyronSettings({ showPortrait: value }))}
/>
)}
<SlotSelector
label="Flag Mode"
label="旗帜模式"
items={flagModeList}
onChange={index => setFlagMode(flagModeList[index])}
slotWidth="12ch"
value={flagModeIndex}
formatter={value => labelOf(flagModeLabels, value as FlagMode)}
onChange={index => dispatch(updateChyronSettings({
flagMode: flagModeList[index] as FlagMode,
}))}
slotWidth="8ch"
/>
</InlineCluster>
);
@@ -130,39 +112,87 @@ export function ChyronsDirectorControls() {
return (
<Stack gutter="md">
<Inline gutter="md" stretch={1}>
<Title>Chyrons</Title>
<Title>车名字幕</Title>
<Inline gutter="md" stretch="all">
<SlotSelector
items={chyronModes}
onChange={index => setChyronMode(chyronModes[index])}
value={modeIndex}
formatter={value => labelOf(chyronModeLabels, value)}
onChange={index => dispatch(updateChyronSettings({
mode: chyronModes[index],
}))}
/>
<SlotSelector
items={chyronSubModes}
onChange={index => setChyronSubMode(chyronSubModes[index])}
value={subModeIndex}
formatter={value => labelOf(chyronSubModeLabels, value)}
onChange={index => dispatch(updateChyronSettings({
subMode: chyronSubModes[index],
}))}
/>
</Inline>
<Inline gutter="sm">
<OpenButton
onClick={onOpen}
disabled={chyrons != null}
onClick={() => chyron.open()}
disabled={!chyron.canOpen}
title="显示字幕(Enter)"
>
<FaCheck size="0.8em" />
</OpenButton>
<Button
onClick={onNext}
disabled={chyrons == null || chyrons.openState === -1}
onClick={chyron.next}
disabled={!chyron.canNext}
title="播放下一步动画(Shift+Enter)"
>
<FaStepForward size="0.8em" />
</Button>
<CloseButton
onClick={onClose}
disabled={chyrons == null || chyrons.openState <= 0}
onClick={chyron.close}
disabled={!chyron.canClose}
title="收起字幕(Backspace)"
>
<FaTimes size="0.8em" />
</CloseButton>
<PanelButton
onClick={() => dispatch(toggleDriverEditor())}
disabled={false}
title="车手名单编辑器(E)"
style={driverEditorOpen ? { backgroundColor: "#f4ae40" } : undefined}
>
<FaUserEdit size="0.8em" />
</PanelButton>
<PanelButton
onClick={() => dispatch(togglePositionScript())}
disabled={false}
title="JSON 名次脚本(J)"
style={positionScriptOpen ? { backgroundColor: "#f4ae40" } : undefined}
>
<FaCode size="0.8em" />
</PanelButton>
<PanelButton
onClick={() => dispatch(toggleShortcutHelp())}
disabled={false}
title="全部快捷键(?)"
style={shortcutHelpOpen ? { backgroundColor: "#f4ae40" } : undefined}
>
<FaKeyboard size="0.8em" />
</PanelButton>
</Inline>
</Inline>
{modeControls(chyronMode, chyronSubMode)}
<ShortcutBar>
<ShortcutItem><ShortcutKey>1…0</ShortcutKey>按名次选车</ShortcutItem>
<ShortcutItem><ShortcutKey>↑↓</ShortcutKey>移动光标</ShortcutItem>
<ShortcutItem><ShortcutKey>空格</ShortcutKey>加第二名车手</ShortcutItem>
<ShortcutItem><ShortcutKey>回车</ShortcutKey>出字幕</ShortcutItem>
<ShortcutItem><ShortcutKey>Esc</ShortcutKey>收起</ShortcutItem>
<ShortcutItem><ShortcutKey>S</ShortcutKey>开始 / 停止</ShortcutItem>
<ShortcutItem><ShortcutKey>+ / -</ShortcutKey>圈数</ShortcutItem>
<ShortcutItem><ShortcutKey>C</ShortcutKey>计时器</ShortcutItem>
<ShortcutItem><ShortcutKey>E</ShortcutKey>车手名单</ShortcutItem>
<ShortcutItem><ShortcutKey>J</ShortcutKey>名次脚本</ShortcutItem>
<ShortcutItem><ShortcutKey>?</ShortcutKey>全部快捷键</ShortcutItem>
</ShortcutBar>
</Stack>
);
}
@@ -35,3 +35,33 @@ export const CloseButton = styled(Button)<ButtonProps>`
background-color: ${({ disabled }) => disabled
? p => p.theme.colors.disabledRed : p => p.theme.colors.activeRed};
`;
export const PanelButton = styled(Button)<ButtonProps>`
background-color: white;
font-size: 0.9em;
`;
export const ShortcutBar = styled.div`
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 0.3em 1.4em;
margin-top: 0.5em;
font-family: ${p => p.theme.fonts.f1Regular};
font-size: 0.74em;
color: ${p => p.theme.colors.darkGrey};
`;
export const ShortcutItem = styled.span`
white-space: nowrap;
`;
export const ShortcutKey = styled.span`
font-family: ${p => p.theme.fonts.f1Bold};
color: ${p => p.theme.colors.darkGrey};
background-color: ${p => p.theme.colors.faintGrey};
border: 1px solid ${p => p.theme.colors.lightGrey};
border-radius: 0.2em;
padding: 0 0.35em;
margin-right: 0.35em;
`;
@@ -0,0 +1,139 @@
import { useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { eventSelector } from "../../../features/event/eventSelector";
import { uiSelector } from "../../../features/ui/uiSelector";
import { setDriverEditorOpen, pushToast } from "../../../features/ui/uiSlice";
import { applyRoster, resetRoster } from "../../../features/event/eventSlice";
import { driverToRosterEntry } from "../../../utils/roster";
import { DriverRow } from "./DriverRow";
import {
ActionButton,
Backdrop,
CloseButton,
DangerButton,
Header,
HeaderActions,
Heading,
Hint,
Panel,
ScrollArea,
Table,
Th,
} from "./styles";
/**
* The roster editor. Every field writes straight into the event state, so the
* chyrons and the timing tower redraw with the new name, number, team or
* portrait while you type - there is no apply step and no separate copy of the
* driver data to keep in sync.
*/
export function DriverEditor() {
const dispatch = useDispatch();
const { grid } = useSelector(eventSelector);
const { driverEditorOpen } = useSelector(uiSelector);
const fileInputRef = useRef<HTMLInputElement>(null);
if (!driverEditorOpen) return null;
const close = () => dispatch(setDriverEditorOpen(false));
const onExport = () => {
const roster = grid.map(car => driverToRosterEntry(car.driver));
const blob = new Blob([JSON.stringify(roster, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "f1-driver-roster.json";
link.click();
URL.revokeObjectURL(url);
dispatch(pushToast("名单已导出"));
};
const onImportFile = (file: File | undefined) => {
if (file == null) return;
const reader = new FileReader();
reader.onload = () => {
try {
const parsed = JSON.parse(String(reader.result));
if (!Array.isArray(parsed)) throw new Error("名单文件应该是一个数组。");
dispatch(applyRoster(parsed));
dispatch(pushToast(`已导入 ${parsed.length} 位车手`));
} catch (error) {
dispatch(pushToast("导入失败:这不是名单文件"));
console.warn("导入车手名单失败。", error);
}
};
reader.readAsText(file);
};
return (
<Backdrop onMouseDown={close}>
<Panel onMouseDown={event => event.stopPropagation()}>
<Header>
<Heading>车手名单</Heading>
<Hint>
改动即时生效。名单保存在本浏览器里,用「导出 JSON」就能把整套阵容搬到别的机器。
按 <strong>Esc</strong> 关闭。
</Hint>
<HeaderActions>
<ActionButton type="button" onClick={onExport}>导出 JSON</ActionButton>
<ActionButton type="button" onClick={() => fileInputRef.current?.click()}>
导入 JSON
</ActionButton>
<DangerButton
type="button"
onClick={() => {
dispatch(resetRoster());
dispatch(pushToast("名单已恢复为内置的 2021 赛季阵容"));
}}
>
全部重置
</DangerButton>
<CloseButton type="button" onClick={close} title="关闭(Esc)">✕</CloseButton>
</HeaderActions>
<input
ref={fileInputRef}
type="file"
accept="application/json,.json"
hidden
onChange={event => {
onImportFile(event.target.files?.[0]);
event.target.value = "";
}}
/>
</Header>
<ScrollArea>
<Table>
<thead>
<tr>
<Th>顺位</Th>
<Th>头像</Th>
<Th>名</Th>
<Th>姓</Th>
<Th>缩写</Th>
<Th>车号</Th>
<Th>国籍</Th>
<Th>车队</Th>
<Th>性能</Th>
<Th>黄 T 摄</Th>
<Th />
</tr>
</thead>
<tbody>
{grid.map((car, gridSpot) => (
<DriverRow
key={gridSpot}
gridSpot={gridSpot}
car={car}
carCount={grid.length}
/>
))}
</tbody>
</Table>
</ScrollArea>
</Panel>
</Backdrop>
);
}
@@ -0,0 +1,197 @@
import { useDispatch } from "react-redux";
import { DriverEditableField, swapDrivers, updateDriver, setDriverTeam, resetDriver } from "../../../features/event/eventSlice";
import { Car, GridSpot, TeamId } from "../../../types/state";
import { teams, teamIds } from "../../../domain/data/teams";
import { countryFlagCodes, driverPortraitNames, resolveDriverPortrait } from "../../../domain/data/assets";
import { deriveInitials } from "../../../utils/roster";
import { TextField } from "../../Common/Inputs/TextField";
import { SelectField, SelectOption } from "../../Common/Inputs/SelectField";
import {
Checkbox,
CheckboxCell,
InitialsCell,
MiniButton,
PortraitCell,
PortraitFallback,
PortraitImage,
RowActions,
SlotNumber,
SlotPosition,
Td,
Tr,
} from "./styles";
const teamOptions: SelectOption[] = teamIds.map(teamId => ({
value: teamId,
label: `${teams[teamId].shortName}(${teamId})`,
}));
const nationalityOptions: SelectOption[] = countryFlagCodes.map(code => ({
value: code,
label: code,
}));
const portraitOptions: SelectOption[] = [
{ value: "", label: "默认" },
...driverPortraitNames.map(name => ({ value: name, label: name })),
];
type DriverRowProps = {
gridSpot: GridSpot;
car: Car;
carCount: number;
};
export function DriverRow({ gridSpot, car, carCount }: DriverRowProps) {
const dispatch = useDispatch();
const { driver } = car;
const setField = (field: DriverEditableField) => (value: string) =>
dispatch(updateDriver({ gridSpot, field, value }));
// A driver whose nationality has no bundled flag keeps its own code so the
// select always has a matching option rather than silently rendering blank.
const nationalities = nationalityOptions.some(option => option.value === driver.nationality)
? nationalityOptions
: [...nationalityOptions, { value: driver.nationality, label: `${driver.nationality}(无国旗)` }];
const portraitSrc = resolveDriverPortrait(driver.portrait ?? driver.id);
return (
<Tr>
<Td>
<SlotNumber>{gridSpot + 1}</SlotNumber>
<SlotPosition>P{car.position}</SlotPosition>
</Td>
<Td>
<PortraitCell>
{portraitSrc != null
? <PortraitImage src={portraitSrc} alt={`${driver.firstName} ${driver.lastName}`} />
: <PortraitFallback>无头像</PortraitFallback>}
<SelectField
value={driver.portrait ?? ""}
options={portraitOptions}
onChange={setField("portrait")}
title="字幕里使用的头像"
/>
</PortraitCell>
</Td>
<Td>
<TextField
value={driver.firstName}
onChange={setField("firstName")}
title="名"
/>
</Td>
<Td>
<TextField
value={driver.lastName}
onChange={setField("lastName")}
title="姓"
/>
</Td>
<Td>
<InitialsCell>
<TextField
value={driver.initials}
onChange={setField("initials")}
title="计时塔上显示的三字母缩写"
/>
<MiniButton
type="button"
title="根据姓名自动生成缩写"
onClick={() => dispatch(updateDriver({
gridSpot,
field: "initials",
value: deriveInitials(driver.firstName, driver.lastName),
}))}
>
↻
</MiniButton>
</InitialsCell>
</Td>
<Td>
<TextField
value={driver.number}
onChange={setField("number")}
type="number"
min={0}
max={999}
title="车号"
/>
</Td>
<Td>
<SelectField
value={driver.nationality}
options={nationalities}
onChange={setField("nationality")}
title="决定字幕上出现的国旗"
/>
</Td>
<Td>
<SelectField
value={driver.team.id}
options={teamOptions}
onChange={(value: string) => dispatch(setDriverTeam({
gridSpot,
teamId: value as TeamId,
}))}
title="决定车队配色、队徽和车队旗帜"
/>
</Td>
<Td>
<TextField
value={driver.performance}
onChange={setField("performance")}
type="number"
min={0.5}
max={1.5}
step={0.001}
title="比赛模拟使用的性能系数"
/>
</Td>
<Td>
<CheckboxCell>
<Checkbox
type="checkbox"
checked={driver.yellowTCam}
title="黄色 T 摄"
onChange={event => dispatch(updateDriver({
gridSpot,
field: "yellowTCam",
value: event.target.checked,
}))}
/>
</CheckboxCell>
</Td>
<Td>
<RowActions>
<MiniButton
type="button"
title="发车顺位前移一位"
disabled={gridSpot === 0}
onClick={() => dispatch(swapDrivers({ a: gridSpot, b: gridSpot - 1 }))}
>
▲
</MiniButton>
<MiniButton
type="button"
title="发车顺位后移一位"
disabled={gridSpot === carCount - 1}
onClick={() => dispatch(swapDrivers({ a: gridSpot, b: gridSpot + 1 }))}
>
▼
</MiniButton>
<MiniButton
type="button"
title="恢复该车手的原始数据"
onClick={() => dispatch(resetDriver(gridSpot))}
>
↺
</MiniButton>
</RowActions>
</Td>
</Tr>
);
}
@@ -0,0 +1 @@
export { DriverEditor } from "./DriverEditor";
@@ -0,0 +1,207 @@
import styled from "styled-components/macro";
export const Backdrop = styled.div`
position: fixed;
inset: 0;
z-index: 50;
display: flex;
align-items: center;
justify-content: center;
padding: 2vh 2vw;
background-color: rgba(20, 20, 24, 0.55);
backdrop-filter: blur(2px);
`;
export const Panel = styled.div`
display: flex;
flex-direction: column;
width: min(1560px, 96vw);
max-height: 90vh;
overflow: hidden;
background-color: #fbfbfb;
border-radius: 0.5em;
box-shadow: 0 18px 50px -12px rgba(0, 0, 0, 0.6);
font-family: ${p => p.theme.fonts.basic};
`;
export const Header = styled.div`
display: flex;
align-items: center;
gap: 1.25em;
flex-wrap: wrap;
padding: 0.6em 1em;
border-bottom: 1px solid ${p => p.theme.colors.lightGrey};
background-color: white;
`;
export const Heading = styled.h2`
font-family: ${p => p.theme.fonts.f1Bold};
font-size: 1.05em;
letter-spacing: 0.02em;
text-transform: uppercase;
color: ${p => p.theme.colors.darkGrey};
white-space: nowrap;
`;
export const Hint = styled.span`
flex: 1;
min-width: 16ch;
font-size: 0.72em;
color: ${p => p.theme.colors.dimGrey};
`;
export const HeaderActions = styled.div`
display: flex;
align-items: center;
gap: 0.5em;
`;
export const ActionButton = styled.button`
padding: 0.35em 0.7em;
border: 1px solid ${p => p.theme.colors.lightGrey};
border-radius: 0.25em;
background-color: white;
color: ${p => p.theme.colors.darkGrey};
font-family: ${p => p.theme.fonts.f1Regular};
font-size: 0.72em;
cursor: pointer;
white-space: nowrap;
&:hover {
background-color: ${p => p.theme.colors.faintGrey};
}
`;
export const DangerButton = styled(ActionButton)`
color: ${p => p.theme.colors.activeRed};
border-color: ${p => p.theme.colors.disabledRed};
`;
export const CloseButton = styled(ActionButton)`
font-size: 0.9em;
padding: 0.2em 0.55em;
line-height: 1.2;
`;
export const ScrollArea = styled.div`
flex: 1;
overflow: auto;
padding: 0 1em 1em;
`;
export const Table = styled.table`
width: 100%;
border-collapse: collapse;
font-size: 0.9em;
`;
export const Th = styled.th`
position: sticky;
top: 0;
z-index: 1;
padding: 0.5em 0.4em;
background-color: #fbfbfb;
border-bottom: 2px solid ${p => p.theme.colors.lightGrey};
text-align: left;
font-family: ${p => p.theme.fonts.f1Bold};
font-size: 0.68em;
letter-spacing: 0.08em;
text-transform: uppercase;
color: ${p => p.theme.colors.dimGrey};
white-space: nowrap;
`;
export const Tr = styled.tr`
&:nth-child(even) {
background-color: rgba(0, 0, 0, 0.022);
}
&:hover {
background-color: rgba(56, 122, 245, 0.07);
}
`;
export const Td = styled.td`
padding: 0.3em 0.4em;
border-bottom: 1px solid #f0f0f0;
vertical-align: middle;
`;
export const SlotNumber = styled.div`
font-family: ${p => p.theme.fonts.f1Bold};
font-size: 0.95em;
text-align: center;
color: ${p => p.theme.colors.darkGrey};
`;
export const SlotPosition = styled.div`
font-family: ${p => p.theme.fonts.f1Regular};
font-size: 0.6em;
text-align: center;
color: ${p => p.theme.colors.dimGrey};
white-space: nowrap;
`;
export const PortraitCell = styled.div`
display: flex;
flex-direction: column;
align-items: center;
gap: 3px;
width: 12ch;
`;
export const PortraitImage = styled.img`
height: 42px;
width: auto;
max-width: 100%;
object-fit: contain;
`;
export const PortraitFallback = styled.div`
height: 42px;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.65em;
color: ${p => p.theme.colors.dimGrey};
`;
export const InitialsCell = styled.div`
display: flex;
align-items: flex-end;
gap: 3px;
width: 11ch;
`;
export const MiniButton = styled.button`
padding: 2px 4px;
border: 1px solid ${p => p.theme.colors.lightGrey};
border-radius: 0.25em;
background-color: white;
color: ${p => p.theme.colors.dimGrey};
font-size: 0.72em;
line-height: 1;
cursor: pointer;
&:hover {
background-color: ${p => p.theme.colors.faintGrey};
color: ${p => p.theme.colors.darkGrey};
}
`;
export const RowActions = styled.div`
display: flex;
gap: 3px;
justify-content: flex-end;
`;
export const Checkbox = styled.input`
width: 1.05em;
height: 1.05em;
cursor: pointer;
accent-color: ${p => p.theme.colors.activeGreen};
`;
export const CheckboxCell = styled.div`
display: flex;
justify-content: center;
`;
+2 -2
View File
@@ -18,7 +18,7 @@ export function Layout({ headerHeight }: LayoutProps) {
<MockupBlock
color="#f7aeae"
minWidth="200px"
>Timing Board UI</MockupBlock>
>计时榜 UI</MockupBlock>
</LayoutGridItem>
<LayoutGridItem column={2} row={1} columnSpan={5} rowSpan={8} >
@@ -28,7 +28,7 @@ export function Layout({ headerHeight }: LayoutProps) {
<LayoutGridItem column={1} row={7} rowSpan={3}>
<MockupBlock
color="#5576e2"
>Race Status UI</MockupBlock>
>比赛状态 UI</MockupBlock>
</LayoutGridItem>
<LayoutGridItem column={1} row={10}>
@@ -0,0 +1,238 @@
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { eventSelector } from "../../../features/event/eventSelector";
import {
adjustLap,
applyPositionScriptResult,
pauseShowClock,
resetShowClock,
setPositionScriptJson,
startShowClock,
} from "../../../features/event/eventSlice";
import { uiSelector } from "../../../features/ui/uiSelector";
import { setPositionScriptOpen } from "../../../features/ui/uiSlice";
import {
DEFAULT_POSITION_SCRIPT_JSON,
describeScriptEvent,
formatShowClock,
parsePositionScriptSafe,
serializePositionScript,
} from "../../../utils/positionScript";
import {
ActionButton,
Backdrop,
Body,
ClockReadout,
ClockRow,
ClockState,
CloseButton,
Column,
ColumnTitle,
EmptyNote,
Header,
HeaderActions,
Heading,
Hint,
LapReadout,
Legend,
Panel,
PrimaryButton,
Schedule,
ScheduleAction,
ScheduleFlag,
ScheduleItem,
ScriptArea,
ScriptStatus,
} from "./styles";
/** Long enough that typing does not reparse on every keystroke, short enough to feel live. */
const PARSE_DEBOUNCE_MS = 350;
const READOUT_TICK_MS = 100;
/**
* The JSON authored position script.
*
* Its zero is the show clock - the moment the timing graphics appeared - so the
* same file replays identically on every run. Editing is live: a valid schedule
* takes effect straight away, an invalid one reports itself and leaves the
* previous schedule running.
*/
export function PositionScriptEditor() {
const dispatch = useDispatch();
const { positionScript, showClock, eventProgress } = useSelector(eventSelector);
const { positionScriptOpen } = useSelector(uiSelector);
const [now, setNow] = useState(() => Date.now());
const running = showClock.startedAt != null;
useEffect(() => {
if (!running) return undefined;
setNow(Date.now());
const timer = window.setInterval(() => setNow(Date.now()), READOUT_TICK_MS);
return () => window.clearInterval(timer);
}, [running]);
// Parse whatever is in the textarea, debounced, without ever throwing away the
// schedule that is currently playing.
useEffect(() => {
const timer = window.setTimeout(() => {
const { file, error } = parsePositionScriptSafe(positionScript.json);
dispatch(applyPositionScriptResult({
events: file?.events ?? [],
initialOrder: file?.initialOrder ?? [],
autoStart: file?.autoStart ?? true,
error,
}));
}, PARSE_DEBOUNCE_MS);
return () => window.clearTimeout(timer);
}, [positionScript.json, dispatch]);
if (!positionScriptOpen) return null;
const elapsedMs = showClock.accumulatedMs
+ (showClock.startedAt != null ? now - showClock.startedAt : 0);
const { events, firedCount, error, orderError } = positionScript;
return (
<Backdrop onMouseDown={() => dispatch(setPositionScriptOpen(false))}>
<Panel onMouseDown={event => event.stopPropagation()}>
<Header>
<Heading>名次脚本</Heading>
<Hint>
零点就是计时榜出现的瞬间。改脚本会让计时器归零、从头重放,
<code>order</code> 也会立刻铺回赛道。脚本保存在本浏览器里,刷新不会丢。
</Hint>
<HeaderActions>
<ActionButton
type="button"
onClick={() => dispatch(setPositionScriptJson(
serializePositionScript({
autoStart: positionScript.autoStart,
initialOrder: positionScript.initialOrder,
events,
}),
))}
>
格式化
</ActionButton>
<ActionButton
type="button"
onClick={() => dispatch(setPositionScriptJson(DEFAULT_POSITION_SCRIPT_JSON))}
>
载入示例
</ActionButton>
<PrimaryButton
type="button"
onClick={() => {
dispatch(resetShowClock());
dispatch(setPositionScriptOpen(false));
}}
>
归零重播
</PrimaryButton>
<CloseButton
type="button"
title="关闭(Esc)"
onClick={() => dispatch(setPositionScriptOpen(false))}
>
✕
</CloseButton>
</HeaderActions>
</Header>
<Body>
<Column>
<ColumnTitle>脚本(JSON)</ColumnTitle>
<ScriptArea
name="position-script"
aria-label="名次脚本 JSON"
spellCheck={false}
value={positionScript.json}
onChange={event => dispatch(setPositionScriptJson(event.target.value))}
/>
<ScriptStatus bad={error != null || orderError != null}>
{error != null
? `脚本有误:${error}`
: orderError != null
? `order 没生效:${orderError}`
: `${events.length} 条事件已就绪 · 自动开始 ${positionScript.autoStart ? "开" : "关"} · 起始顺序 ${positionScript.initialOrder.length} 位`}
</ScriptStatus>
<Legend>
<code>at</code> 是从零点算起的毫秒数,或 &quot;mm:ss.mmm&quot;。{" "}
<code>action</code> 可选 <code>swap</code>(交换位置)、<code>move</code>(移动到某名次)、{" "}
<code>retire</code>(退赛)、<code>restore</code>(回到比赛)、<code>lap</code>(增减圈数)。
车手可以写 id(<code>verstappen</code>)、三字码(<code>VER</code>)、姓(<code>Verstappen</code>)
或车号(<code>33</code>)。{" "}
<code>order</code> 必须按顺序列出整个车阵,写错会在上面的状态条里说明原因。
改脚本会让计时器归零并从头播放。
</Legend>
</Column>
<Column>
<ColumnTitle>计时器</ColumnTitle>
<ClockRow>
<ClockReadout>{formatShowClock(elapsedMs)}</ClockReadout>
<ClockState running={running}>{running ? "运行中" : "已暂停"}</ClockState>
<ActionButton
type="button"
title={running ? "暂停(C)" : "启动(C)"}
onClick={() => dispatch(running ? pauseShowClock() : startShowClock())}
>
{running ? "暂停" : "启动"}
</ActionButton>
<ActionButton
type="button"
title="归零并从头上重播(Shift+C)"
onClick={() => dispatch(resetShowClock())}
>
归零
</ActionButton>
<LapReadout>
圈数 {eventProgress.lapCount}
{" / "}
{eventProgress.scheduledLaps}
{eventProgress.lapAdjust !== 0
? ` (${eventProgress.lapAdjust > 0 ? "+" : ""}${eventProgress.lapAdjust})`
: ""}
</LapReadout>
<ActionButton
type="button"
title="圈数 -1(-)"
onClick={() => dispatch(adjustLap(-1))}
>
圈数 −1
</ActionButton>
<ActionButton
type="button"
title="圈数 +1(+)"
onClick={() => dispatch(adjustLap(1))}
>
圈数 +1
</ActionButton>
</ClockRow>
<ColumnTitle>时间轴</ColumnTitle>
<Schedule>
{events.length === 0 && (
<EmptyNote>还没有事件,在左侧 JSON 里加一条吧。</EmptyNote>
)}
{events.map((event, index) => {
const done = index < firedCount;
const state = done ? "done" : (event.at <= elapsedMs ? "due" : "waiting");
return (
<ScheduleItem key={`${index}-${event.at}-${event.action}`} state={state}>
<span>{formatShowClock(event.at)}</span>
<ScheduleAction>{describeScriptEvent(event)}</ScheduleAction>
{done && <ScheduleFlag>已完成</ScheduleFlag>}
</ScheduleItem>
);
})}
</Schedule>
</Column>
</Body>
</Panel>
</Backdrop>
);
}
@@ -0,0 +1 @@
export { PositionScriptEditor } from "./PositionScriptEditor";
@@ -0,0 +1,265 @@
import styled from "styled-components/macro";
export const Backdrop = styled.div`
position: fixed;
inset: 0;
z-index: 45;
display: flex;
align-items: center;
justify-content: center;
padding: 2vh 2vw;
background-color: rgba(20, 20, 24, 0.55);
backdrop-filter: blur(2px);
`;
export const Panel = styled.div`
display: flex;
flex-direction: column;
width: min(1360px, 96vw);
height: min(820px, 90vh);
overflow: hidden;
background-color: #fbfbfb;
border-radius: 0.5em;
box-shadow: 0 18px 50px -12px rgba(0, 0, 0, 0.6);
font-family: ${p => p.theme.fonts.basic};
`;
export const Header = styled.div`
display: flex;
align-items: center;
gap: 1.25em;
flex-wrap: wrap;
padding: 0.6em 1em;
border-bottom: 1px solid ${p => p.theme.colors.lightGrey};
background-color: white;
`;
export const Heading = styled.h2`
font-family: ${p => p.theme.fonts.f1Bold};
font-size: 1.05em;
letter-spacing: 0.02em;
text-transform: uppercase;
color: ${p => p.theme.colors.darkGrey};
white-space: nowrap;
`;
export const Hint = styled.span`
flex: 1;
min-width: 18ch;
font-size: 0.72em;
color: ${p => p.theme.colors.dimGrey};
`;
export const HeaderActions = styled.div`
display: flex;
align-items: center;
gap: 0.5em;
`;
export const ActionButton = styled.button`
padding: 0.35em 0.7em;
border: 1px solid ${p => p.theme.colors.lightGrey};
border-radius: 0.25em;
background-color: white;
color: ${p => p.theme.colors.darkGrey};
font-family: ${p => p.theme.fonts.f1Regular};
font-size: 0.72em;
cursor: pointer;
white-space: nowrap;
&:hover {
background-color: ${p => p.theme.colors.faintGrey};
}
`;
export const PrimaryButton = styled(ActionButton)`
border-color: ${p => p.theme.colors.blue};
color: ${p => p.theme.colors.blue};
`;
export const CloseButton = styled(ActionButton)`
font-size: 0.9em;
padding: 0.2em 0.55em;
line-height: 1.2;
`;
export const Body = styled.div`
flex: 1;
display: grid;
grid-template-columns: minmax(0, 1.05fr) minmax(0, 1fr);
gap: 1em;
padding: 1em;
overflow: hidden;
@media (max-width: 900px) {
grid-template-columns: minmax(0, 1fr);
overflow: auto;
}
`;
export const Column = styled.div`
display: flex;
flex-direction: column;
gap: 0.5em;
min-height: 0;
`;
export const ColumnTitle = styled.h3`
font-family: ${p => p.theme.fonts.f1Bold};
font-size: 0.72em;
letter-spacing: 0.1em;
text-transform: uppercase;
color: ${p => p.theme.colors.blue};
border-bottom: 1px solid ${p => p.theme.colors.lightGrey};
padding-bottom: 0.25em;
`;
export const ScriptArea = styled.textarea`
flex: 1;
min-height: 260px;
width: 100%;
resize: none;
padding: 0.7em;
border: 1px solid ${p => p.theme.colors.lightGrey};
border-radius: 0.25em;
background-color: white;
color: ${p => p.theme.colors.darkGrey};
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.78em;
line-height: 1.5;
tab-size: 2;
&:focus {
outline: 2px solid ${p => p.theme.colors.blue};
outline-offset: -2px;
}
`;
type StatusProps = {
bad: boolean,
};
export const ScriptStatus = styled.div<StatusProps>`
padding: 0.35em 0.6em;
border-radius: 0.25em;
font-size: 0.74em;
background-color: ${({ bad }) => bad ? "#fdecec" : "#eef7ee"};
color: ${({ bad, theme }) => bad ? theme.colors.activeRed : "#2f7a33"};
border: 1px solid ${({ bad, theme }) => bad ? theme.colors.disabledRed : "#bfe0c0"};
`;
export const ClockRow = styled.div`
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.5em 0.8em;
padding: 0.6em 0.75em;
border-radius: 0.35em;
background-color: white;
border: 1px solid ${p => p.theme.colors.lightGrey};
`;
export const ClockReadout = styled.div`
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 1.5em;
line-height: 1;
color: ${p => p.theme.colors.darkGrey};
font-feature-settings: 'tnum' 1;
min-width: 8.4ch;
text-align: center;
`;
type ClockStateProps = {
running: boolean,
};
export const ClockState = styled.span<ClockStateProps>`
font-family: ${p => p.theme.fonts.f1Bold};
font-size: 0.66em;
letter-spacing: 0.12em;
text-transform: uppercase;
padding: 0.25em 0.5em;
border-radius: 1em;
color: white;
background-color: ${({ running, theme }) => running
? theme.colors.activeGreen : theme.colors.grey};
`;
export const LapReadout = styled.div`
margin-left: auto;
font-family: ${p => p.theme.fonts.f1Regular};
font-size: 0.8em;
color: ${p => p.theme.colors.darkGrey};
white-space: nowrap;
`;
export const Schedule = styled.ol`
list-style: none;
margin: 0;
padding: 0;
overflow-y: auto;
min-height: 0;
flex: 1;
border: 1px solid ${p => p.theme.colors.lightGrey};
border-radius: 0.25em;
background-color: white;
`;
type ScheduleItemProps = {
state: "done" | "due" | "waiting",
};
export const ScheduleItem = styled.li<ScheduleItemProps>`
display: flex;
align-items: baseline;
gap: 0.7em;
padding: 0.35em 0.6em;
border-bottom: 1px solid #f2f2f2;
font-size: 0.78em;
&:last-child {
border-bottom: none;
}
opacity: ${({ state }) => state === "waiting" ? 0.72 : 1};
background-color: ${({ state }) => state === "due" ? "#fff8e6" : "transparent"};
span:first-child {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-feature-settings: 'tnum' 1;
color: ${p => p.theme.colors.dimGrey};
white-space: nowrap;
}
`;
export const ScheduleAction = styled.span`
font-family: ${p => p.theme.fonts.f1Regular};
color: ${p => p.theme.colors.darkGrey};
`;
export const ScheduleFlag = styled.span`
margin-left: auto;
font-family: ${p => p.theme.fonts.f1Bold};
font-size: 0.66em;
letter-spacing: 0.1em;
text-transform: uppercase;
color: ${p => p.theme.colors.activeGreen};
`;
export const EmptyNote = styled.p`
padding: 0.8em;
font-size: 0.78em;
color: ${p => p.theme.colors.dimGrey};
max-inline-size: none;
`;
export const Legend = styled.p`
font-size: 0.7em;
color: ${p => p.theme.colors.dimGrey};
max-inline-size: none;
line-height: 1.55;
code {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
background-color: ${p => p.theme.colors.faintGrey};
border-radius: 0.2em;
padding: 0 0.25em;
}
`;
@@ -1,26 +1,73 @@
import { useDispatch, useSelector } from "react-redux";
import { InlineCluster } from "@bedrock-layout/inline-cluster";
import { PadBox } from "@bedrock-layout/padbox";
import { useDispatch, useSelector } from "react-redux";
import { eventSelector } from "../../../../../features/event/eventSelector";
import { ClickSpan } from "../../../../Common/Inputs/ClickSpan.styled";
import { EventStatus } from "../../../../../types/state";
import { setEventStatus } from "../../../../../features/event/eventSlice";
import { eventStatusLabels, labelOf } from "../../../../../i18n/labels";
import {
adjustLap,
pauseShowClock,
resetShowClock,
setEventStatus,
startShowClock,
} from "../../../../../features/event/eventSlice";
/**
* The always visible director strip: event state, the LAP counter and the show
* clock that the position script is timed against. Every entry carries the key
* that does the same thing.
*/
export function RaceDirectorControls() {
const dispatch = useDispatch();
const { eventStatus } = useSelector(eventSelector);
const { eventStatus, eventProgress, showClock } = useSelector(eventSelector);
const clockRunning = showClock.startedAt != null;
return (
<PadBox padding="md">
<ClickSpan onClick={() => {
if (eventStatus !== EventStatus.Running) {
dispatch(setEventStatus(EventStatus.Running));
} else {
dispatch(setEventStatus(EventStatus.Stopped));
}
}}>
EventStatus = {EventStatus[eventStatus]}
</ClickSpan>
<InlineCluster gutter="md">
<ClickSpan
title="开始或停止比赛(S)"
onClick={() => {
if (eventStatus !== EventStatus.Running) {
dispatch(setEventStatus(EventStatus.Running));
} else {
dispatch(setEventStatus(EventStatus.Stopped));
}
}}
>
比赛状态:{labelOf(eventStatusLabels, eventStatus)} [S]
</ClickSpan>
<ClickSpan
title="圈数 +1(+)"
onClick={() => dispatch(adjustLap(1))}
>
圈数 {eventProgress.lapCount}/{eventProgress.scheduledLaps} +1 [+]
</ClickSpan>
<ClickSpan
title="圈数 -1(-)"
onClick={() => dispatch(adjustLap(-1))}
>
圈数 -1 [-]
</ClickSpan>
<ClickSpan
title={clockRunning ? "暂停计时器(C)" : "启动计时器(C)"}
onClick={() => dispatch(clockRunning ? pauseShowClock() : startShowClock())}
>
计时器 {clockRunning ? "暂停" : "启动"} [C]
</ClickSpan>
<ClickSpan
title="计时器归零并重播名次脚本(Shift+C)"
onClick={() => dispatch(resetShowClock())}
>
计时器归零 [⇧C]
</ClickSpan>
</InlineCluster>
</PadBox>
);
}
@@ -0,0 +1,50 @@
import { useDispatch, useSelector } from "react-redux";
import { SHORTCUT_GROUPS } from "../../../features/keyboard/shortcuts";
import { uiSelector } from "../../../features/ui/uiSelector";
import { setShortcutHelpOpen } from "../../../features/ui/uiSlice";
import {
Backdrop,
Description,
Group,
GroupTitle,
Groups,
Heading,
Keys,
Lead,
Panel,
Row,
} from "./styles";
export function ShortcutHelp() {
const dispatch = useDispatch();
const { shortcutHelpOpen } = useSelector(uiSelector);
if (!shortcutHelpOpen) return null;
return (
<Backdrop onMouseDown={() => dispatch(setShortcutHelpOpen(false))}>
<Panel onMouseDown={event => event.stopPropagation()}>
<Heading>键盘控制</Heading>
<Lead>
所有页面都能用。在输入框里打字时快捷键不会触发,每次按键屏幕底部都会给出
一行提示,<strong>Esc</strong> 则关闭当前打开的面板。
</Lead>
<Groups>
{SHORTCUT_GROUPS.map(group => (
<Group key={group.title}>
<GroupTitle>{group.title}</GroupTitle>
{group.shortcuts.map(shortcut => (
<Row key={shortcut.keys}>
<Keys>{shortcut.keys}</Keys>
<Description>{shortcut.description}</Description>
</Row>
))}
</Group>
))}
</Groups>
</Panel>
</Backdrop>
);
}
@@ -0,0 +1 @@
export { ShortcutHelp } from "./ShortcutHelp";
@@ -0,0 +1,86 @@
import styled from "styled-components/macro";
export const Backdrop = styled.div`
position: fixed;
inset: 0;
z-index: 40;
display: flex;
align-items: center;
justify-content: center;
padding: 4vh 2vw;
background-color: rgba(20, 20, 24, 0.5);
`;
export const Panel = styled.div`
width: min(1180px, 94vw);
max-height: 86vh;
overflow: auto;
padding: 1.1em 1.4em 1.4em;
background-color: #fbfbfb;
border-radius: 0.5em;
box-shadow: 0 18px 50px -12px rgba(0, 0, 0, 0.6);
`;
export const Heading = styled.h2`
font-family: ${p => p.theme.fonts.f1Bold};
font-size: 1.05em;
letter-spacing: 0.02em;
text-transform: uppercase;
color: ${p => p.theme.colors.darkGrey};
margin-bottom: 0.2em;
`;
export const Lead = styled.p`
font-size: 0.76em;
color: ${p => p.theme.colors.dimGrey};
margin-bottom: 0.9em;
max-inline-size: none;
`;
export const Groups = styled.div`
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 0.9em 1.6em;
align-items: start;
`;
export const Group = styled.section`
break-inside: avoid;
`;
export const GroupTitle = styled.h3`
font-family: ${p => p.theme.fonts.f1Bold};
font-size: 0.72em;
letter-spacing: 0.1em;
text-transform: uppercase;
color: ${p => p.theme.colors.blue};
border-bottom: 1px solid ${p => p.theme.colors.lightGrey};
padding-bottom: 0.25em;
margin-bottom: 0.4em;
`;
export const Row = styled.div`
display: flex;
align-items: baseline;
gap: 0.7em;
padding: 0.16em 0;
`;
export const Keys = styled.kbd`
flex: 0 0 12ch;
font-family: ${p => p.theme.fonts.f1Regular};
font-size: 0.72em;
color: ${p => p.theme.colors.darkGrey};
background-color: white;
border: 1px solid ${p => p.theme.colors.lightGrey};
border-bottom-width: 2px;
border-radius: 0.25em;
padding: 0.1em 0.45em;
text-align: center;
white-space: nowrap;
`;
export const Description = styled.span`
font-size: 0.78em;
color: ${p => p.theme.colors.darkGrey};
`;
@@ -31,9 +31,9 @@ export default function VideoFeed() {
return (
<VideoFeedFrame centered ref={frameRef}>
<DimensionsSpan>
Frame: {Math.floor(frameWidth)} x {Math.floor(frameHeight)}px
画面 {Math.floor(frameWidth)} × {Math.floor(frameHeight)} px
<br />
Scaled: {Math.floor(layoutWidth)} x {Math.floor(layoutHeight)}px ({(layoutScale * 100).toFixed(1)}%)
缩放 {Math.floor(layoutWidth)} × {Math.floor(layoutHeight)} px({(layoutScale * 100).toFixed(1)}%)
</DimensionsSpan>
<BackgroundImageDiv src={bg} />
<BroadcastLayout width={broadcastWidth} height={broadcastHeight} scale={layoutScale} >
@@ -0,0 +1,29 @@
import { DriverEditor } from "../Broadcast/DriverEditor";
import { PositionScriptEditor } from "../Broadcast/PositionScriptEditor";
import { ShortcutHelp } from "../Broadcast/ShortcutHelp";
import { Toast } from "../Common/Toast";
import { useBroadcastShortcuts } from "../../features/keyboard/useBroadcastShortcuts";
import { usePositionScriptRunner } from "../../features/event/usePositionScriptRunner";
/**
* The keyboard layer and the panels it opens.
*
* Kept in its own component so the store subscriptions the shortcuts need stay
* inside this subtree - mounting it from the app shell means the shortcuts and
* the driver roster are reachable from every page without making the whole
* application re-render on every race tick.
*/
export function BroadcastControlLayer() {
useBroadcastShortcuts();
// Keeps the position script in step with the show clock wherever you are.
usePositionScriptRunner();
return (
<>
<DriverEditor />
<PositionScriptEditor />
<ShortcutHelp />
<Toast />
</>
);
}
@@ -0,0 +1 @@
export { BroadcastControlLayer } from "./BroadcastControlLayer";
@@ -64,7 +64,12 @@ export function ChyronDriver({
const { design: { chyronDriver: cdTheme } } = theme;
const teamColor = theme.colors.teams[car.driver.team.id];
const containerFadeAwaySpring = useSpring({
// `deps` = "only update this spring when these change". Without it
// react-spring re-runs ctrl.start() after every render, so an unrelated store
// update (an EventLoop tick, or a relayed snapshot on the output page)
// restarts the enter animation and re-arms its delays mid-flight - which is
// what made a chyron look like it was reloading instead of animating.
const [containerFadeAwaySpring] = useSpring({
opacity: openState == -1 ? 0 : 1,
config: { duration: cdTheme.containerFadeAwayDurationMs * DDM },
delay: 0,
@@ -73,13 +78,13 @@ export function ChyronDriver({
dispatch(clearChyrons());
}
},
});
}, [openState, DDM]);
const { outlineClipPathProgress } = useSpring({
const [{ outlineClipPathProgress }] = useSpring({
outlineClipPathProgress: openState !== 0 ? 1 : 0,
config: { duration: cdTheme.outlineClipPathDurationMs * DDM },
delay: 0,
});
}, [openState, DDM]);
return (
<AnimatedBaseContainer
@@ -248,6 +253,7 @@ export function ChyronDriver({
>
<DriverPortrait
driverId={car.driver.id}
portrait={car.driver.portrait}
height={baseHeight * 2.5}
verticalOffsetPercentage={18}
/>
@@ -2,6 +2,7 @@ import { ReactNode } from "react";
import { TeamId } from "../../../../types/state";
import { Px } from "../../../../types/style";
import { getTeamFlagStyle } from "../../../../utils/dataLookup";
import { resolveCountryFlag, resolveTeamLogo } from "../../../../domain/data/assets";
import {
Container,
Slant,
@@ -12,9 +13,6 @@ import {
TeamFlagDiv,
} from "./styles";
const countryFlags = require.context("../../../../public/images/countryFlags/angled", true);
const teamLogos = require.context("../../../../public/images/logos/team", true);
const FLAG_WIDTH_TEAM = 2.4;
const FLAG_WIDTH_COUNTRY = 2;
@@ -41,51 +39,59 @@ export function AngledFlag(props: AngledFlagProps) {
let bottomFlag: ReactNode = null;
if (flagProps.flagMode === "country") {
topFlag = (
<CountryFlagDiv
src={countryFlags(`./${flagProps.flag}.svg`)}
height={flagHeight}
width={flagHeight * FLAG_WIDTH_COUNTRY}
>
<FlagEdge
x={flagHeight / 2}
// The roster editor only offers bundled flags, but an imported roster can
// name anything - fall through to an empty flag instead of crashing.
const flagSrc = resolveCountryFlag(flagProps.flag);
if (flagSrc != null) {
topFlag = (
<CountryFlagDiv
src={flagSrc}
height={flagHeight}
girth={flagHeight * 0.07}
width={flagHeight * FLAG_WIDTH_COUNTRY}
>
<FlagEdge
x={flagHeight / 2}
height={flagHeight}
girth={flagHeight * 0.07}
/>
</CountryFlagDiv>
);
bottomFlag = (
<CountryFlagDiv
src={flagSrc}
height={flagHeight}
width={flagHeight * FLAG_WIDTH_COUNTRY}
xOffset={-flagHeight * 0.005}
/>
</CountryFlagDiv>
);
bottomFlag = (
<CountryFlagDiv
src={countryFlags(`./${flagProps.flag}.svg`)}
height={flagHeight}
width={flagHeight * FLAG_WIDTH_COUNTRY}
xOffset={-flagHeight * 0.005}
/>
);
);
}
} else if (flagProps.flagMode === "team") {
topFlag = (
<TeamFlagDiv
src={teamLogos(`./${flagProps.flag}.svg`)}
height={flagHeight}
width={flagHeight * FLAG_WIDTH_TEAM}
style={getTeamFlagStyle(flagProps.flag)}
>
<FlagEdge
x={flagHeight / 2}
const logoSrc = resolveTeamLogo(flagProps.flag);
if (logoSrc != null) {
topFlag = (
<TeamFlagDiv
src={logoSrc}
height={flagHeight}
girth={flagHeight * 0.04}
width={flagHeight * FLAG_WIDTH_TEAM}
style={getTeamFlagStyle(flagProps.flag)}
>
<FlagEdge
x={flagHeight / 2}
height={flagHeight}
girth={flagHeight * 0.04}
/>
</TeamFlagDiv>
);
bottomFlag = (
<TeamFlagDiv
src={logoSrc}
height={flagHeight}
width={flagHeight * FLAG_WIDTH_TEAM}
style={getTeamFlagStyle(flagProps.flag)}
bottomFlag
/>
</TeamFlagDiv>
);
bottomFlag = (
<TeamFlagDiv
src={teamLogos(`./${flagProps.flag}.svg`)}
height={flagHeight}
width={flagHeight * FLAG_WIDTH_TEAM}
style={getTeamFlagStyle(flagProps.flag)}
bottomFlag
/>
);
);
}
}
const flagModeWidth = flagProps.flagMode === "team" ? FLAG_WIDTH_TEAM : FLAG_WIDTH_COUNTRY;
@@ -1,23 +1,30 @@
import { DriverId } from "../../../../types/state";
import { Percent, Px } from "../../../../types/style";
import { resolveDriverPortrait } from "../../../../domain/data/assets";
import { PortraitDiv } from "./styles";
const driverPortraits = require.context("../../../../public/images/drivers/front", true);
type DriverPortraitProps = {
driverId: DriverId,
/** Optional override set in the driver roster editor. */
portrait?: string,
height: Px,
verticalOffsetPercentage?: Percent,
};
export function DriverPortrait({
driverId,
portrait,
height,
verticalOffsetPercentage = 0,
}: DriverPortraitProps) {
const src = resolveDriverPortrait(portrait) ?? resolveDriverPortrait(driverId);
// A driver can be pointed at a portrait that is not bundled. Drawing nothing
// is a far better failure than a webpack "cannot find module" at runtime.
if (src == null) return null;
return (
<PortraitDiv
src={driverPortraits(`./${driverId}.png`)}
src={src}
height={height}
verticalOffsetPercentage={verticalOffsetPercentage}
/>
@@ -1,26 +1,29 @@
import { TeamId } from "../../../../types/state";
import { Px } from "../../../../types/style";
import { getTeamGemStyle } from "../../../../utils/dataLookup";
import { resolveTeamLogo } from "../../../../domain/data/assets";
import { GemColorDiv, GemContainer, GemLogoDiv } from "./styles";
const teamLogos = require.context("../../../../public/images/logos/team", true);
type TeamGemProps = {
height: Px,
team: TeamId,
};
export function TeamGem({ height, team }: TeamGemProps) {
const logoSrc = resolveTeamLogo(team);
return (
<GemContainer height={height}>
<GemColorDiv
height={height}
gemStyle={getTeamGemStyle(team)}
/>
<GemLogoDiv
height={height}
src={teamLogos(`./${team}.svg`)}
gemStyle={getTeamGemStyle(team)}
/>
{logoSrc != null && (
<GemLogoDiv
height={height}
src={logoSrc}
gemStyle={getTeamGemStyle(team)}
/>
)}
</GemContainer>
);
}
@@ -44,11 +44,11 @@ export function VenetianBlindsTransition(
children,
}: React.PropsWithChildren<VenetianBlindsTransitionProps>,
) {
const blindsSpring = useSpring({
const [blindsSpring] = useSpring({
opacity: visible ? 1 : 0,
config: { duration: blindsOpenDuration },
delay: blindsOpenDelay + delay,
});
}, [visible, blindsOpenDuration, blindsOpenDelay, delay]);
return (
<WipeTransition
@@ -37,20 +37,20 @@ export function WipeTransition({
width: childWidth,
}] = useMeasure();
const { wipe } = useSpring({
const [{ wipe }] = useSpring({
wipe: visible ? 1 : 0,
config: {
duration: duration,
easing: easings.easeInOutQuint,
},
delay: 0 + delay,
});
}, [visible, duration, delay]);
const { opacity } = useSpring({
const [{ opacity }] = useSpring({
opacity: visible ? 1 : opacityStart,
config: { duration: opacityDuration },
delay: opacityDelay + delay,
});
}, [visible, opacityStart, opacityDuration, opacityDelay, delay]);
return (
<animated.div
@@ -8,6 +8,7 @@ import { DebugDurationProps, TransitionArgs } from "../../../../types/style";
import { orMatch } from "../../../../utils/common";
import { LapCount, LapLabel, LapLine, StatusIndicatorBase, StatusIndicatorLayout } from "./styles";
import { TimingClock } from "./TimingClock";
type StatusIndicatorProps = DebugDurationProps;
@@ -69,6 +70,7 @@ export function StatusIndicator({
</LapCount>
</>
)}
<TimingClock />
</StatusIndicatorLayout>
</StatusIndicatorBase>
);
@@ -0,0 +1,56 @@
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { eventSelector } from "../../../../features/event/eventSelector";
import { startShowClock } from "../../../../features/event/eventSlice";
import { formatShowClock } from "../../../../utils/positionScript";
import { ClockChip } from "./styles";
/** 20 updates a second is plenty to watch the milliseconds roll. */
const CLOCK_TICK_MS = 50;
/**
* Elapsed time since the timing graphics appeared, shown as mm:ss.mmm beside
* the LAP counter.
*
* The clock keeps its own fast tick so the rest of the broadcast does not have
* to re-render twenty times a second - only this chip does. Its zero is also
* the position script's zero.
*/
export function TimingClock() {
const dispatch = useDispatch();
const { showClock, positionScript: { autoStart } } = useSelector(eventSelector);
const [now, setNow] = useState(() => Date.now());
const running = showClock.startedAt != null;
useEffect(() => {
if (!running) return undefined;
setNow(Date.now());
const timer = window.setInterval(() => setNow(Date.now()), CLOCK_TICK_MS);
return () => window.clearInterval(timer);
}, [running]);
// The clock starts itself the first time the timing graphics are displayed,
// which is what makes "zero" mean the same thing on every reload.
useEffect(() => {
if (!autoStart || showClock.hasStarted) return;
dispatch(startShowClock());
}, [autoStart, showClock.hasStarted, dispatch]);
const elapsed = showClock.accumulatedMs
+ (showClock.startedAt != null ? now - showClock.startedAt : 0);
return (
<ClockChip
running={running}
title={running
? "计时榜出现至今的时间(C 暂停,Shift+C 归零)"
: "计时器已暂停(C 继续,Shift+C 归零)"}
>
{formatShowClock(elapsed)}
</ClockChip>
);
}
@@ -83,6 +83,41 @@ export const LapLabel = styled.span<LapLabelProps>`
`;
////// Show Clock //////
type ClockChipProps = {
running: boolean,
};
/**
* The stopwatch that hangs off the right edge of the LAP box. It is positioned
* against the status indicator rather than inside it so it never competes with
* the lap readout for space, whatever mode the indicator is in.
*/
export const ClockChip = styled.div<ClockChipProps>`
position: absolute;
left: 100%;
top: 23px;
margin-left: 8px;
padding: 4px 8px;
border-radius: 3px;
background-color: black;
font-family: ${p => p.theme.fonts.f1Regular};
font-size: 16px;
line-height: 1;
letter-spacing: 0.03em;
white-space: nowrap;
font-feature-settings: 'tnum' 1;
min-width: 8.4ch;
text-align: center;
color: ${({ running, theme }) => running
? theme.colors.textWhite : theme.colors.dimGrey};
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.12);
transition: color 250ms;
`;
type LapCountProps = DirectionalTransitionProps & IndicatorModeProps;
export const LapCount = styled.div<LapCountProps>`
position: absolute;
@@ -111,11 +111,13 @@ export function TimingTowerRow({
}
}, [displayMode]);
const { outlineClipPathProgress } = useSpring({
// Same reason as the chyron springs: without `deps` this row re-renders on
// every race tick, which restarts the position change outline mid wipe.
const [{ outlineClipPathProgress }] = useSpring({
outlineClipPathProgress: showOutline ? 1 : 0,
config: { duration: 333 * DDM },
delay: 0 * DDM,
});
}, [showOutline, DDM]);
const [leftHalfRef, {
height: leftHalfHeight,
@@ -0,0 +1,45 @@
import { useState } from "react";
import { FieldLabel, FieldWrapper, StyledSelect } from "./styles";
export type SelectOption = {
value: string,
label: string,
};
export type SelectFieldProps = {
value: string,
options: Array<SelectOption>,
onChange: (value: string) => void,
label?: string,
width?: string,
title?: string,
};
let fieldId = 0;
export function SelectField({
value,
options,
onChange,
label,
width,
title,
}: SelectFieldProps) {
// One stable name per mounted field keeps autofill and assistive tech happy.
const [name] = useState(() => `select-${++fieldId}`);
return (
<FieldWrapper width={width}>
{label != null && <FieldLabel>{label}</FieldLabel>}
<StyledSelect
name={name}
value={value}
title={title}
onChange={event => onChange(event.target.value)}
>
{options.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</StyledSelect>
</FieldWrapper>
);
}
@@ -0,0 +1,2 @@
export { SelectField } from "./SelectField";
export type { SelectFieldProps, SelectOption } from "./SelectField";
@@ -0,0 +1,40 @@
import styled from "styled-components/macro";
type FieldWrapperProps = {
width?: string,
};
export const FieldWrapper = styled.label<FieldWrapperProps>`
display: flex;
flex-direction: column;
gap: 2px;
width: ${({ width = "100%" }) => width};
min-width: 0;
`;
export const FieldLabel = styled.span`
font-family: ${p => p.theme.fonts.f1Regular};
font-size: 0.6em;
letter-spacing: 0.06em;
text-transform: uppercase;
color: ${p => p.theme.colors.dimGrey};
white-space: nowrap;
`;
export const StyledSelect = styled.select`
width: 100%;
min-width: 0;
padding: 3px 4px;
border: 1px solid ${p => p.theme.colors.lightGrey};
border-radius: 0.25em;
background-color: white;
color: ${p => p.theme.colors.darkGrey};
font-family: ${p => p.theme.fonts.f1Regular};
font-size: 0.82em;
line-height: 1.4;
cursor: pointer;
&:focus {
outline: 2px solid ${p => p.theme.colors.blue};
outline-offset: -2px;
}
`;
@@ -12,6 +12,12 @@ type SlotSelectorProps = {
removePrefix?: boolean,
formatter?: (value: string) => string,
initialIndex?: number,
/**
* Controlled index. Pass it when the selection also has to be changeable
* from somewhere else (a keyboard shortcut, for example) - the slot will
* then follow the value it is given instead of tracking its own.
*/
value?: number,
disabled?: boolean,
slotWidth?: string,
};
@@ -26,6 +32,7 @@ export function SlotSelector({
removePrefix = false,
formatter = (x) => x,
initialIndex = 0,
value,
disabled = false,
slotWidth = "6ch",
}: SlotSelectorProps) {
@@ -37,6 +44,10 @@ export function SlotSelector({
setIndex(initialIndex);
}, [items]);
useEffect(() => {
if (value != null) setIndex(value);
}, [value]);
// useMemo makes these functions only run once when mounting. Not every re-render.
useMemo(() => {
const tempFormattedItems = items.map(item => formatter(item));
@@ -45,9 +56,9 @@ export function SlotSelector({
}, [items]);
const onClick = () => {
if (disabled) return;
if (disabled || items.length === 0) return;
const nextIndex = (index + 1) % items.length;
setIndex(nextIndex);
if (value == null) setIndex(nextIndex);
onChange(nextIndex);
};
@@ -0,0 +1,73 @@
import { useState } from "react";
import { FieldLabel, FieldWrapper, StyledInput } from "./styles";
export type TextFieldProps = {
value: string | number,
onChange: (value: string) => void,
label?: string,
type?: "text" | "number",
width?: string,
min?: number,
max?: number,
step?: number,
placeholder?: string,
title?: string,
};
/**
* Small controlled text input.
*
* While the field has focus it keeps its own draft string, which is what makes
* it possible to clear a number field (or type a leading "-") without the store
* forcing a value straight back into the box. Every keystroke that parses is
* still pushed upstream immediately, so the broadcast updates as you type.
*/
let fieldId = 0;
export function TextField({
value,
onChange,
label,
type = "text",
width,
min,
max,
step,
placeholder,
title,
}: TextFieldProps) {
const [draft, setDraft] = useState<string | null>(null);
// One stable name per mounted field keeps autofill and assistive tech happy.
const [name] = useState(() => `field-${++fieldId}`);
const displayValue = draft ?? String(value);
return (
<FieldWrapper width={width}>
{label != null && <FieldLabel>{label}</FieldLabel>}
<StyledInput
type={type}
name={name}
value={displayValue}
min={min}
max={max}
step={step}
placeholder={placeholder}
title={title}
onFocus={() => setDraft(String(value))}
onBlur={() => setDraft(null)}
onChange={event => {
const next = event.target.value;
setDraft(next);
if (type === "number") {
// Do not commit a half typed value, but do commit every valid one.
if (next.trim() === "") return;
const parsed = Number(next);
if (Number.isFinite(parsed)) onChange(next);
} else {
onChange(next);
}
}}
/>
</FieldWrapper>
);
}
@@ -0,0 +1,2 @@
export { TextField } from "./TextField";
export type { TextFieldProps } from "./TextField";
@@ -0,0 +1,39 @@
import styled from "styled-components/macro";
type FieldWrapperProps = {
width?: string,
};
export const FieldWrapper = styled.label<FieldWrapperProps>`
display: flex;
flex-direction: column;
gap: 2px;
width: ${({ width = "100%" }) => width};
min-width: 0;
`;
export const FieldLabel = styled.span`
font-family: ${p => p.theme.fonts.f1Regular};
font-size: 0.6em;
letter-spacing: 0.06em;
text-transform: uppercase;
color: ${p => p.theme.colors.dimGrey};
white-space: nowrap;
`;
export const StyledInput = styled.input`
width: 100%;
min-width: 0;
padding: 3px 5px;
border: 1px solid ${p => p.theme.colors.lightGrey};
border-radius: 0.25em;
background-color: white;
color: ${p => p.theme.colors.darkGrey};
font-family: ${p => p.theme.fonts.f1Regular};
font-size: 0.82em;
line-height: 1.4;
&:focus {
outline: 2px solid ${p => p.theme.colors.blue};
outline-offset: -2px;
}
`;
+30
View File
@@ -0,0 +1,30 @@
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { uiSelector } from "../../../features/ui/uiSelector";
import { clearToast } from "../../../features/ui/uiSlice";
import { ToastBar } from "./styles";
const TOAST_DURATION_MS = 1600;
/**
* Transient confirmation for actions that have no visible button of their own -
* mostly the keyboard shortcuts, where otherwise nothing tells you the press
* landed.
*/
export function Toast() {
const dispatch = useDispatch();
const { toast } = useSelector(uiSelector);
const toastId = toast?.id;
useEffect(() => {
if (toastId == null) return;
const timeout = window.setTimeout(() => dispatch(clearToast()), TOAST_DURATION_MS);
return () => window.clearTimeout(timeout);
}, [toastId, dispatch]);
if (toast == null) return null;
return <ToastBar>{toast.text}</ToastBar>;
}
+1
View File
@@ -0,0 +1 @@
export { Toast } from "./Toast";
+19
View File
@@ -0,0 +1,19 @@
import styled from "styled-components/macro";
export const ToastBar = styled.div`
position: fixed;
left: 50%;
bottom: 1.6em;
z-index: 60;
transform: translateX(-50%);
padding: 0.45em 1.1em;
border-radius: 2em;
background-color: rgba(24, 24, 28, 0.9);
color: white;
font-family: ${p => p.theme.fonts.f1Regular};
font-size: 0.82em;
letter-spacing: 0.02em;
white-space: nowrap;
pointer-events: none;
box-shadow: 0 8px 24px -8px rgba(0, 0, 0, 0.7);
`;
+5 -5
View File
@@ -12,11 +12,11 @@ export const MainMenu = React.forwardRef<HTMLDivElement>(
(_, ref) => (
<Menu
ref={ref}
title="F1 World Broadcast Emulator Project"
title="F1 世界转播模拟器"
links={[
{ label: "Home", to: "/" },
{ label: "Broadcast Page", to: "/broadcast" },
{ label: "Workspaces", to: "/workspaces" },
{ label: "首页", to: "/" },
{ label: "转播控制台", to: "/broadcast" },
{ label: "图形工作台", to: "/workspaces" },
]}
/>
),
@@ -35,7 +35,7 @@ const Menu = React.forwardRef<HTMLDivElement, MenuProps>(
return (
<MenuBar ref={innerRef}>
<Link to="/">
<img src={f1Logo} alt="Formula One logo" height="20px" />
<img src={f1Logo} alt="F1 标志" height="20px" />
</Link>
<Title>{props.title}</Title>
<nav>
+65
View File
@@ -0,0 +1,65 @@
import { useEffect } from "react";
import { useStore } from "react-redux";
import { RootState } from "../../types/state";
import {
createOutputChannel,
createSnapshotCollector,
} from "../../features/outputChannel/outputChannel";
/**
* Controller-side publisher. Mounted once in the app shell, it mirrors the
* broadcast slices of the store to the relay (see server/relayServer.js) so any
* number of output pages stay in sync. Add "?bridge=0" to a URL to opt out.
*
* Two rules keep it from disturbing the UI it is mirroring:
* - nothing is read or sent while no relay is attached;
* - every state transition is flushed on a microtask so the output sees the
* same sequence of states the controller rendered. A time-based throttle
* would merge them (e.g. the chyron's "closed" and "open" states) and the
* output would mount already-open, skipping the enter animation entirely.
*/
export function BroadcastBridge() {
const store = useStore<RootState>();
useEffect(() => {
const params = new URLSearchParams(window.location.search);
if (params.get("bridge") === "0") return undefined;
const collector = createSnapshotCollector();
let scheduled = false;
const flush = () => {
scheduled = false;
if (channel.getStatus() !== "open") return;
const patch = collector.collect(store.getState());
if (patch != null) channel.sendState(patch);
};
const schedule = () => {
if (scheduled) return;
scheduled = true;
queueMicrotask(flush);
};
const channel = createOutputChannel({
role: "controller",
onStatus: (status) => {
// A fresh (or reconnected) output needs the whole picture.
if (status !== "open") return;
collector.reset();
schedule();
},
});
const unsubscribe = store.subscribe(schedule);
schedule();
return () => {
unsubscribe();
channel.close();
};
}, [store]);
return null;
}
+127
View File
@@ -0,0 +1,127 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useDispatch } from "react-redux";
import useMeasure from "react-use-measure";
import { applySnapshot } from "../../features/outputChannel/outputChannelActions";
import {
ChannelMessage,
ChannelStatus,
createOutputChannel,
} from "../../features/outputChannel/outputChannel";
import { theme } from "../../shared/theme";
import { calculateFitSize, calculateScale } from "../../utils/styling";
import { ChyronContainer } from "../BroadcastGraphics/Chyrons/Container";
import { TimingBoard } from "../BroadcastGraphics/TimingBoard";
import { Logo } from "../Broadcast/VideoFeed/styles";
import {
OutputGlobalStyle,
OutputRoot,
OutputStage,
SafeArea,
StatusBadge,
} from "./styles";
import f1Logo from "../../public/images/logos/f1-logo-white.svg";
const STATUS_LABEL: Record<ChannelStatus, string> = {
connecting: "connecting...",
open: "live",
closed: "offline (retrying)",
};
/**
* Standalone, chrome-less broadcast output page for OBS.
*
* "/output" (alias "/broadcast-output") renders only the broadcast graphics on
* a transparent background and mirrors whatever the controller sends over the
* WebSocket relay. Query parameters:
* - "?ws=ws://host:port" relay to connect to (defaults to the page host on
* the default relay port, 8181).
* - "?debug=1" draw the 1920x1080 safe area and a status badge.
*/
export function OutputRoute() {
const dispatch = useDispatch();
const [rootRef, { width: rootWidth, height: rootHeight }] = useMeasure();
const params = useMemo(() => new URLSearchParams(window.location.search), []);
const debug = useMemo(() => {
const value = params.get("debug");
return value !== null && value !== "0";
}, [params]);
const [status, setStatus] = useState<ChannelStatus>("connecting");
const lastMessageRef = useRef(0);
const [, setTick] = useState(0);
const {
dimensionsWidthPx: broadcastWidth,
dimensionsHeightPx: broadcastHeight,
logoHeightPx,
placement,
} = theme.broadcast;
// Keep the on-screen frame in sync with the relay.
useEffect(() => {
const channel = createOutputChannel({
role: "output",
onStatus: setStatus,
onMessage: (message: ChannelMessage) => {
lastMessageRef.current = Date.now();
if (message.type === "state") dispatch(applySnapshot(message.payload));
},
});
return () => channel.close();
}, [dispatch]);
// Only the debug badge needs a clock, so the graphics are not re-rendered.
useEffect(() => {
if (!debug) return undefined;
const timer = window.setInterval(() => setTick((value) => value + 1), 1000);
return () => window.clearInterval(timer);
}, [debug]);
const [layoutWidth, layoutHeight] = calculateFitSize(
rootWidth,
rootHeight,
[broadcastWidth, broadcastHeight],
);
const scale = rootWidth > 0 && rootHeight > 0
? calculateScale(layoutWidth, layoutHeight, [broadcastWidth, broadcastHeight])
: 1;
const offsetX = Math.max((rootWidth - layoutWidth) / 2, 0);
const offsetY = Math.max((rootHeight - layoutHeight) / 2, 0);
const lastMessageAgo = lastMessageRef.current === 0
? "never"
: Math.round((Date.now() - lastMessageRef.current) / 1000) + "s ago";
return (
<>
<OutputGlobalStyle />
<OutputRoot ref={rootRef}>
<OutputStage
width={broadcastWidth}
height={broadcastHeight}
scale={scale}
offsetX={offsetX}
offsetY={offsetY}
>
<TimingBoard placement={placement.timingBoard} />
<ChyronContainer placement={placement.chyrons} />
<Logo height={logoHeightPx} placement={placement.logo} src={f1Logo} />
{debug ? <SafeArea /> : null}
</OutputStage>
{debug ? (
<StatusBadge>
{STATUS_LABEL[status]}
{"\n"}
{Math.round(rootWidth)}x{Math.round(rootHeight)} @ {(scale * 100).toFixed(1)}%
{"\n"}
last state: {lastMessageAgo}
</StatusBadge>
) : null}
</OutputRoot>
</>
);
}
+2
View File
@@ -0,0 +1,2 @@
export { OutputRoute } from "./OutputRoute";
export { BroadcastBridge } from "./BroadcastBridge";
+78
View File
@@ -0,0 +1,78 @@
import styled, { createGlobalStyle } from "styled-components/macro";
import { Fraction, Px } from "../../types/style";
/**
* Makes the page fully transparent so it can be used directly as an OBS browser
* source (OBS composites the alpha channel).
*/
export const OutputGlobalStyle = createGlobalStyle`
html,
body,
#root {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: transparent !important;
background-color: transparent !important;
}
`;
export const OutputRoot = styled.div`
position: fixed;
inset: 0;
overflow: hidden;
background: transparent;
cursor: none;
`;
type OutputStageProps = {
width: Px,
height: Px,
scale: Fraction,
offsetX: Px,
offsetY: Px,
};
export const OutputStage = styled.div.attrs<OutputStageProps>(({
width,
height,
scale,
offsetX,
offsetY,
}) => ({
style: {
width,
height,
transform: `translate(${offsetX}px, ${offsetY}px) scale(${scale})`,
},
}))<OutputStageProps>`
position: absolute;
top: 0;
left: 0;
transform-origin: top left;
background: transparent;
`;
export const SafeArea = styled.div`
position: absolute;
inset: 0;
border: 2px dashed rgba(255, 74, 74, 0.7);
pointer-events: none;
`;
export const StatusBadge = styled.div`
position: fixed;
top: 8px;
left: 8px;
z-index: 1000;
padding: 4px 8px;
border-radius: 4px;
background: rgba(0, 0, 0, 0.65);
color: #fff;
font-family: monospace;
font-size: 12px;
line-height: 1.6;
white-space: pre;
pointer-events: none;
`;
@@ -40,7 +40,7 @@ export function OverlayControl() {
<Stack as={PadBox} gutter="md" padding="sm">
<Inline gutter="md" stretch="end">
<Toggle
label="Show Overlay"
label="显示叠加图"
toggled={visible}
onToggle={onToggleVisibility}
/>
@@ -2,7 +2,12 @@ import { InlineCluster } from "@bedrock-layout/inline-cluster";
import { useDispatch, useSelector } from "react-redux";
import { broadcastDirectorSelector } from "../../../../features/broadcast/director/broadcastDirectorSelector";
import { pushSelectedCars, clearSelectedCars, removeSelectedCars } from "../../../../features/broadcast/director/broadcastDirectorSlice";
import {
pushSelectedCars,
clearSelectedCars,
removeSelectedCars,
setCursorGridSpot,
} from "../../../../features/broadcast/director/broadcastDirectorSlice";
import { eventSelector } from "../../../../features/event/eventSelector";
import { GridSpot } from "../../../../types/state";
@@ -15,9 +20,13 @@ export function GridSelection() {
} = useSelector(eventSelector);
const {
selectedCars,
cursorGridSpot,
} = useSelector(broadcastDirectorSelector);
const carClick = (gridSpot: GridSpot, selected: boolean) => () => {
// Clicking also parks the keyboard cursor here, so the mouse and the
// arrow keys always agree on where "here" is.
dispatch(setCursorGridSpot(gridSpot));
if (selected) {
dispatch(removeSelectedCars(gridSpot));
} else {
@@ -25,6 +34,7 @@ export function GridSelection() {
}
};
const carDoubleClick = (gridSpot: GridSpot) => () => {
dispatch(setCursorGridSpot(gridSpot));
dispatch(clearSelectedCars(gridSpot));
};
@@ -37,8 +47,10 @@ export function GridSelection() {
const onDoubleClick = carDoubleClick(gridSpot);
return (
<GridItem
key={car.driver.id}
key={gridSpot}
selected={selected}
isCursor={cursorGridSpot === gridSpot}
title={`${car.driver.firstName} ${car.driver.lastName} · 第 ${car.position} 位`}
onClick={onClick}
onDoubleClick={onDoubleClick}
>
@@ -3,6 +3,8 @@ import styled from "styled-components/macro";
type GridItemProps = {
selected: boolean,
/** The car the keyboard cursor is parked on. */
isCursor: boolean,
};
export const GridItem = styled(PadBox).attrs(() => ({
padding: ["md", "xs"],
@@ -16,6 +18,10 @@ export const GridItem = styled(PadBox).attrs(() => ({
text-align: center;
user-select: none;
box-shadow: ${({ isCursor }) => isCursor
? p => `0 0 0 2px ${p.theme.colors.blue}`
: "none"};
background-color: ${({ selected }) => selected
? p => p.theme.colors.grey
: p => p.theme.colors.faintGrey};
@@ -10,6 +10,18 @@ import { eventSelector } from "../../../../features/event/eventSelector";
import { setTimingTowerDisplayMode, setTimingTowerSplitsMode } from "../../../../features/broadcast/graphics/broadcastGraphicsSlice";
import { awardFastestLap, increaseDistance, refreshRunningOrder, setCarStatus } from "../../../../features/event/eventSlice";
import { BGTimingTowerDisplayMode, BGTimingTowerSplitsMode, CarStatus } from "../../../../types/state";
import {
labelOf,
timingTowerDisplayModeLabels,
timingTowerSplitsModeLabels,
} from "../../../../i18n/labels";
const DISPLAY_MODES: BGTimingTowerDisplayMode[] = [
BGTimingTowerDisplayMode.Hidden,
BGTimingTowerDisplayMode.LeftOnly,
BGTimingTowerDisplayMode.LeftAndRight,
BGTimingTowerDisplayMode.FullLeft,
];
import { GridSelection } from "../GridSelection";
import { ClickSpan } from "../../../Common/Inputs/ClickSpan.styled";
@@ -27,7 +39,7 @@ export function TimingTowerPrototypeControls() {
<PadBox padding="md">
<InlineCluster gutter="md">
<ClickSpan onClick={() => dispatch(refreshRunningOrder())}>
Refresh Running Order
重算名次
</ClickSpan>
<ClickSpan
onClick={() => {
@@ -40,7 +52,7 @@ export function TimingTowerPrototypeControls() {
dispatch(refreshRunningOrder());
}}
>
+200m
+200 米
</ClickSpan>
<ClickSpan
onClick={() => {
@@ -53,7 +65,7 @@ export function TimingTowerPrototypeControls() {
dispatch(refreshRunningOrder());
}}
>
+100m performance to all
全场 +100 米
</ClickSpan>
<ClickSpan
onClick={() => {
@@ -66,7 +78,7 @@ export function TimingTowerPrototypeControls() {
dispatch(refreshRunningOrder());
}}
>
+1000m performance to all
全场 +1000 米
</ClickSpan>
<ClickSpan
onClick={() => {
@@ -77,7 +89,7 @@ export function TimingTowerPrototypeControls() {
dispatch(refreshRunningOrder());
}}
>
Retire
退赛
</ClickSpan>
<ClickSpan
onClick={() => {
@@ -88,7 +100,7 @@ export function TimingTowerPrototypeControls() {
dispatch(refreshRunningOrder());
}}
>
Un-retire
取消退赛
</ClickSpan>
<ClickSpan
onClick={() => {
@@ -97,7 +109,7 @@ export function TimingTowerPrototypeControls() {
}
}}
>
Award FL
授予最快圈
</ClickSpan>
</InlineCluster>
<hr />
@@ -111,21 +123,18 @@ export function TimingTowerPrototypeControls() {
}
}}
>
Splits Mode = {BGTimingTowerSplitsMode[splitsMode]}
计时模式:{labelOf(timingTowerSplitsModeLabels, splitsMode)}
</ClickSpan>
<ClickSpan onClick={() => dispatch(setTimingTowerDisplayMode(BGTimingTowerDisplayMode.Hidden))}>
{(displayMode === BGTimingTowerDisplayMode.Hidden ? "*" : "") + "Hidden"}
</ClickSpan>
<ClickSpan onClick={() => dispatch(setTimingTowerDisplayMode(BGTimingTowerDisplayMode.LeftOnly))}>
{(displayMode === BGTimingTowerDisplayMode.LeftOnly ? "*" : "") + "LeftOnly"}
</ClickSpan>
<ClickSpan onClick={() => dispatch(setTimingTowerDisplayMode(BGTimingTowerDisplayMode.LeftAndRight))}>
{(displayMode === BGTimingTowerDisplayMode.LeftAndRight ? "*" : "") + "LeftAndRight"}
</ClickSpan>
<ClickSpan onClick={() => dispatch(setTimingTowerDisplayMode(BGTimingTowerDisplayMode.FullLeft))}>
{(displayMode === BGTimingTowerDisplayMode.FullLeft ? "*" : "") + "FullLeft"}
</ClickSpan>
{DISPLAY_MODES.map(mode => (
<ClickSpan
key={mode}
title="计时塔显示模式"
onClick={() => dispatch(setTimingTowerDisplayMode(mode))}
>
{(displayMode === mode ? "*" : "")
+ labelOf(timingTowerDisplayModeLabels, mode)}
</ClickSpan>
))}
</InlineCluster>
</PadBox>
</Stack>
@@ -7,6 +7,7 @@ import { workspaceSelector } from "../../../../features/workspace/workspaceSelec
import { updateVenetianTransition } from "../../../../features/workspace/workspaceSlice";
import { DriverId } from "../../../../types/state";
import { Corner } from "../../../../types/style";
import { cornerLabels, labelOf, venetianModeLabels } from "../../../../i18n/labels";
import { SlotSelector } from "../../../Common/Inputs/SlotSelector";
import { Toggle } from "../../../Common/Inputs/Toggle";
@@ -56,25 +57,27 @@ export function VenetianBlindsPrototypeControls() {
<SlotSelector
items={modes}
onChange={changeMode}
label="Mode"
label="模式"
formatter={value => labelOf(venetianModeLabels, value)}
slotWidth="200px"
/>
<SlotSelector
items={subModes[modeIndex]}
onChange={changeSubMode}
label="SubMode"
label="子模式"
slotWidth="200px"
/>
<SlotSelector
items={corners}
onChange={onChangeStartingCorner}
label="Starting Corner"
label="起始角"
formatter={value => labelOf(cornerLabels, value as Corner)}
slotWidth="200px"
/>
<Toggle
toggled={prototypeState?.venetianTransition?.showBG ?? true}
onToggle={onToggle}
label="Show BG"
label="显示背景"
/>
</InlineCluster>
);
@@ -57,7 +57,7 @@ export const Workspace = ({
maxWidth="80%"
centerChildren
>
<H2>{workspaceId ? workspaceProperties.name : "Unknown"}</H2>
<H2>{workspaceId ? workspaceProperties.name : "未知"}</H2>
<PreviewWindow
dimensions={workspaceProperties.previewWindowDimensions}
animatedBG={animatedBG}
@@ -26,14 +26,14 @@ export const WorkspaceControls = (
<Split gutter="md">
<InlineCluster as={PadBox} padding="sm" gutter="md">
<Toggle
label="Animate BG"
label="动态背景"
toggled={animatedBG}
onToggle={(value: boolean) => {
dispatch(setAnimatedBG(value));
}}
/>
<Toggle
label="Dark BG"
label="深色背景"
toggled={darkBG}
onToggle={(value: boolean) => {
dispatch(setDarkBG(value));
@@ -41,7 +41,7 @@ export const WorkspaceControls = (
/>
{showAnimationSpeedSelector && (
<SlotSelector
label="Animation Duration"
label="动画时长"
items={debugMultipliers}
formatter={value => `x${value}`}
onChange={index =>
@@ -53,7 +53,7 @@ export default function Workspaces() {
widthCutoff={WORKSPACE_LIST_WIDTH}
>
<Routes>
<Route index element={<IndexHeading>Workspaces Home</IndexHeading>} />
<Route index element={<IndexHeading>图形工作台</IndexHeading>} />
<Route path="chyron" element={
<Workspace
workspaceId="chyron"
@@ -100,7 +100,7 @@ export default function Workspaces() {
showAnimationSpeedSelector
/>
} />
<Route path="*" element={<IndexHeading>Unknown Workspace</IndexHeading>} />
<Route path="*" element={<IndexHeading>未知工作台</IndexHeading>} />
</Routes>
</FullScreenContainer>
</LayoutGridItem>
+49
View File
@@ -0,0 +1,49 @@
/**
* Every image the broadcast graphics can render is bundled by webpack through
* require.context(). The lists below are the single source of truth for what
* the driver editor is allowed to offer, and the resolve* helpers make sure a
* missing file degrades into "draw nothing" instead of a webpack crash.
*
* Do not import these contexts anywhere else - always go through the resolver
* functions so validation stays in one place.
*/
const portraitContext = require.context("../../public/images/drivers/front", true);
const countryFlagContext = require.context("../../public/images/countryFlags/angled", true);
const teamLogoContext = require.context("../../public/images/logos/team", true);
type AssetContext = {
keys: () => string[],
(key: string): string,
};
function namesFrom(context: AssetContext, extension: string): string[] {
return context.keys()
.filter(key => key.endsWith(extension))
.map(key => key.replace("./", "").replace(extension, ""))
.sort((a, b) => a.localeCompare(b));
}
function resolve(context: AssetContext, name: string, extension: string): string | null {
const key = `./${name}${extension}`;
return context.keys().includes(key) ? context(key) : null;
}
/** Portrait names available in public/images/drivers/front (ex: "hamilton"). */
export const driverPortraitNames: string[] = namesFrom(portraitContext, ".png");
/** Country codes with a bundled angled flag (ex: "GBR"). */
export const countryFlagCodes: string[] = namesFrom(countryFlagContext, ".svg");
/** Team ids with a bundled logo (ex: "ferrari"). */
export const teamLogoIds: string[] = namesFrom(teamLogoContext, ".svg");
export function resolveDriverPortrait(name?: string | null): string | null {
return name ? resolve(portraitContext, name, ".png") : null;
}
export function resolveCountryFlag(code?: string | null): string | null {
return code ? resolve(countryFlagContext, code, ".svg") : null;
}
export function resolveTeamLogo(teamId?: string | null): string | null {
return teamId ? resolve(teamLogoContext, teamId, ".svg") : null;
}
+4 -1
View File
@@ -1,5 +1,5 @@
import { theme } from "../../shared/theme";
import { Driver, Team } from "../../types/state";
import { Driver, Team, TeamId } from "../../types/state";
import { Percent } from "../../types/style";
import { repeater } from "../../utils/strings";
@@ -80,6 +80,9 @@ export const teams: {[id: string]: Team} = {
},
};
/** Every team id, in the order the teams table declares them. */
export const teamIds: TeamId[] = Object.keys(teams) as TeamId[];
/**
* Do not grab directly!
* 2021 Driver lineup with 2022 newcomers included (Zhou and Albon)
+6 -6
View File
@@ -5,7 +5,7 @@ type WorkspaceObject = {
};
export const workspaces: WorkspaceObject = {
chyron: {
name: "Chyron",
name: "车名字幕",
overlayIds: [
"chyron-driver-medium-full-alo.png",
"chyron-driver-medium-full-lec.png",
@@ -31,7 +31,7 @@ export const workspaces: WorkspaceObject = {
},
},
chyronWide: {
name: "Chyron (Wide)",
name: "车名字幕(宽)",
overlayIds: [
"chyron-driver-medium-full-sai-ric.png",
],
@@ -41,7 +41,7 @@ export const workspaces: WorkspaceObject = {
},
},
angledFlagCountry: {
name: "Angled Flag (Country)",
name: "斜切旗帜(国旗)",
overlayIds: [
"angled-flag-gbr.png",
],
@@ -51,7 +51,7 @@ export const workspaces: WorkspaceObject = {
},
},
angledFlagTeam: {
name: "Angled Flag (Team)",
name: "斜切旗帜(车队)",
overlayIds: [
"angled-flag-alfaRomeo.png",
"angled-flag-alphaTauri.png",
@@ -70,7 +70,7 @@ export const workspaces: WorkspaceObject = {
},
},
venetianTransition: {
name: "Venetian Transition",
name: "百叶窗转场",
overlayIds: [
"venetian-pos-1.png",
"venetian-pos-2.png",
@@ -86,7 +86,7 @@ export const workspaces: WorkspaceObject = {
},
},
timingBoard: {
name: "Timing Board",
name: "计时榜",
overlayIds: [
"timing-board-leader-19.png",
"timing-board-leader-20-out-1.png",
@@ -1,10 +1,19 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { RootState, GridSpot } from "../../../types/state";
import { ChyronSettings, RootState, GridSpot } from "../../../types/state";
import { Optional } from "../../../types/util";
const initialState: RootState["broadcastDirector"] = {
selectedCars: [],
cursorGridSpot: null,
chyronSettings: {
mode: "driver",
subMode: "medium",
flagMode: "country",
showPosFlag: true,
showDriverNumber: true,
showPortrait: false,
},
};
export const broadcastDirectorSlice = createSlice({
@@ -35,6 +44,34 @@ export const broadcastDirectorSlice = createSlice({
state.selectedCars = [action.payload];
}
},
/** Replaces the whole selection in one go. Used by the keyboard layer. */
replaceSelectedCars: (state, action: PayloadAction<GridSpot[]>) => {
state.selectedCars = action.payload.filter(
(spot, index) => action.payload.indexOf(spot) === index,
);
},
/** Adds or removes a single car from the selection. Capped at two cars. */
toggleSelectedCar: (state, action: PayloadAction<GridSpot>) => {
const existing = state.selectedCars.indexOf(action.payload);
if (existing !== -1) {
state.selectedCars.splice(existing, 1);
} else {
state.selectedCars.push(action.payload);
if (state.selectedCars.length > 2) {
state.selectedCars.splice(0, state.selectedCars.length - 2);
}
}
},
/**
* Parks the keyboard cursor. Kept apart from the selection so the cursor
* can be moved around the running order without wiping a built selection.
*/
setCursorGridSpot: (state, action: PayloadAction<Optional<GridSpot>>) => {
state.cursorGridSpot = action.payload;
},
updateChyronSettings: (state, action: PayloadAction<Partial<ChyronSettings>>) => {
state.chyronSettings = { ...state.chyronSettings, ...action.payload };
},
},
});
@@ -43,5 +80,9 @@ export const {
setSelectedCars,
removeSelectedCars,
clearSelectedCars,
replaceSelectedCars,
toggleSelectedCar,
setCursorGridSpot,
updateChyronSettings,
} = broadcastDirectorSlice.actions;
export default broadcastDirectorSlice.reducer;
@@ -0,0 +1,102 @@
import { useCallback, useMemo } from "react";
import { useDispatch, useSelector } from "react-redux";
import { broadcastDirectorSelector } from "./broadcastDirectorSelector";
import { broadcastGraphicsSelector } from "../graphics/broadcastGraphicsSelector";
import { eventSelector } from "../../event/eventSelector";
import {
incrementChyronsOpenState,
setChyrons,
setChyronsOpenState,
} from "../graphics/broadcastGraphicsSlice";
import { BGChyronDriver, BGChyrons, GridSpot } from "../../../types/state";
/**
* The chyron animation needs a frame mounted at openState 0 before it is
* advanced, otherwise the whole transition is skipped.
*/
export const CHYRON_OPEN_DELAY_MS = 50;
/**
* One place that knows how to turn "the cars I have selected" into a chyron.
* Both the on screen Chyrons panel and the keyboard layer drive the chyrons
* through this hook, so the two can never drift apart.
*/
export function useChyronDirector() {
const dispatch = useDispatch();
const { chyrons } = useSelector(broadcastGraphicsSelector);
const { selectedCars, cursorGridSpot, chyronSettings } = useSelector(broadcastDirectorSelector);
const { grid } = useSelector(eventSelector);
/**
* The cars a chyron would be built from right now. An explicit selection
* wins, otherwise the chyron falls back to whatever the keyboard cursor is
* parked on so "arrow, Enter" works without a separate select step.
*/
const targetSpots: GridSpot[] = useMemo(() => {
if (selectedCars.length > 0) return selectedCars;
return cursorGridSpot == null ? [] : [cursorGridSpot];
}, [selectedCars, cursorGridSpot]);
const buildDriverChyron = useCallback(
(carGridSpot: GridSpot): BGChyronDriver => ({
carGridSpot,
flagMode: chyronSettings.flagMode,
showPosFlag: chyronSettings.showPosFlag,
showDriverNumber: chyronSettings.showDriverNumber,
showPortrait: chyronSettings.subMode === "large" ? false : chyronSettings.showPortrait,
}),
[chyronSettings],
);
const open = useCallback((overrideSpots?: GridSpot[]) => {
const spots = (overrideSpots ?? targetSpots).filter(spot => grid[spot] != null);
if (spots.length === 0) return;
let primaryCarGridSpot = spots[0];
let secondaryCarGridSpot = spots[1] ?? -1;
// Auto-sort drivers by position so trailing car appears second on mounting.
if (chyronSettings.subMode === "medium" && secondaryCarGridSpot !== -1
&& grid[secondaryCarGridSpot].position < grid[primaryCarGridSpot].position) {
secondaryCarGridSpot = spots[0];
primaryCarGridSpot = spots[1];
}
const newChyrons: BGChyrons = {
openState: 0,
mode: chyronSettings.mode,
subMode: chyronSettings.subMode,
driver: {
primary: buildDriverChyron(primaryCarGridSpot),
secondary: secondaryCarGridSpot !== -1
? buildDriverChyron(secondaryCarGridSpot) : null,
},
};
dispatch(setChyrons(newChyrons));
// Delay a short time and increment the open state so the animation can happen.
setTimeout(() => dispatch(incrementChyronsOpenState()), CHYRON_OPEN_DELAY_MS);
}, [dispatch, targetSpots, chyronSettings, buildDriverChyron, grid]);
const next = useCallback(() => {
dispatch(incrementChyronsOpenState());
}, [dispatch]);
const close = useCallback(() => {
dispatch(setChyronsOpenState(-1));
}, [dispatch]);
return {
open,
next,
close,
/** Cars an "open" press would use right now. */
targetSpots,
isOpen: chyrons != null,
isClosing: chyrons != null && chyrons.openState === -1,
canOpen: targetSpots.length > 0,
canNext: chyrons != null && chyrons.openState !== -1,
canClose: chyrons != null && chyrons.openState > 0,
};
}
+539 -195
View File
@@ -4,7 +4,10 @@ import { random } from "lodash";
import {
CourseFlag,
CarStatus,
DriverId,
Grid,
RootState,
TeamId,
Tyre,
TyreCompound,
CarNotice,
@@ -15,11 +18,24 @@ import {
GridSpot,
EventStatus,
Car,
PositionScriptEvent,
} from "../../types/state";
import { Meters } from "../../types/util";
import { Meters, Optional } from "../../types/util";
import { orMatch } from "../../utils/common";
import { cloneDriver, getTeam } from "../../utils/dataLookup";
import { cloneDriver, cloneTeam, getTeam } from "../../utils/dataLookup";
import { driverToGridMap, sortCarPosition } from "../../utils/event";
import {
DriverRosterEntry,
clampDriverNumber,
clampPerformance,
rosterEntryToDriver,
sanitizePortrait,
} from "../../utils/roster";
import {
DEFAULT_POSITION_SCRIPT_JSON,
findGridSpotByRef,
parsePositionScriptSafe,
} from "../../utils/positionScript";
const DEFAULT_TYRE: Tyre = {
compound: TyreCompound.Medium,
@@ -30,6 +46,44 @@ const DEFAULT_TYRE: Tyre = {
const GRID_POSITION_GAP: Meters = 8;
const POLE_TO_START: Meters = -10;
/**
* The starting grid, kept as a plain list of driver ids so the roster can be
* rebuilt (and reset) without twenty near identical object literals.
*/
const INITIAL_LINEUP: DriverId[] = [
"verstappen",
"hamilton",
"bottas",
"perez",
"sainz",
"norris",
"leclerc",
"ricciardo",
"gasly",
"alonso",
"ocon",
"vettel",
"stroll",
"tsunoda",
"russell",
"raikkonen",
"latifi",
"giovinazzi",
"schumacher",
"mazepin",
];
function buildInitialGrid(): Grid {
return INITIAL_LINEUP.map((driverId, index) => ({
position: index + 1,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: index === 0 ? [CarNotice.FastestLap] : [],
distance: POLE_TO_START - GRID_POSITION_GAP * index,
driver: cloneDriver(driverId),
}));
}
const initialState: RootState["event"] = {
trackName: "Circuit de Spa-Franchorchamps",
trackLength: 7004,
@@ -46,174 +100,98 @@ const initialState: RootState["event"] = {
startTime: Date.now(),
timeLimit: 60 * 60 * 2 * 1000,
lapCount: 1,
lapAdjust: 0,
scheduledLaps: 44,
},
grid: [
{
position: 1,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [CarNotice.FastestLap],
distance: POLE_TO_START - GRID_POSITION_GAP * 0,
driver: cloneDriver("verstappen"),
},
{
position: 2,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 1,
driver: cloneDriver("hamilton"),
},
{
position: 3,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 2,
driver: cloneDriver("bottas"),
},
{
position: 4,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 3,
driver: cloneDriver("perez"),
},
{
position: 5,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 4,
driver: cloneDriver("sainz"),
},
{
position: 6,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 5,
driver: cloneDriver("norris"),
},
{
position: 7,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 6,
driver: cloneDriver("leclerc"),
},
{
position: 8,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 7,
driver: cloneDriver("ricciardo"),
},
{
position: 9,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 8,
driver: cloneDriver("gasly"),
},
{
position: 10,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 9,
driver: cloneDriver("alonso"),
},
{
position: 11,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 10,
driver: cloneDriver("ocon"),
},
{
position: 12,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 11,
driver: cloneDriver("vettel"),
},
{
position: 13,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 12,
driver: cloneDriver("stroll"),
},
{
position: 14,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 13,
driver: cloneDriver("tsunoda"),
},
{
position: 15,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 14,
driver: cloneDriver("russell"),
},
{
position: 16,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 15,
driver: cloneDriver("raikkonen"),
},
{
position: 17,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 16,
driver: cloneDriver("latifi"),
},
{
position: 18,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 17,
driver: cloneDriver("giovinazzi"),
},
{
position: 19,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 18,
driver: cloneDriver("schumacher"),
},
{
position: 20,
status: CarStatus.Normal,
tyre: DEFAULT_TYRE,
notices: [],
distance: POLE_TO_START - GRID_POSITION_GAP * 19,
driver: cloneDriver("mazepin"),
},
],
sortedGridSpots: Array.from(Array(20).keys()),
grid: buildInitialGrid(),
sortedGridSpots: Array.from(Array(INITIAL_LINEUP.length).keys()),
lastUpdate: Date.now(),
showClock: {
startedAt: null,
accumulatedMs: 0,
hasStarted: false,
},
positionScript: buildInitialPositionScript(),
};
/**
* The shipped schedule is parsed once at start up so a broken default can never
* take the app down - it would simply report an error in the script panel.
*/
function buildInitialPositionScript(): RootState["event"]["positionScript"] {
const { file, error } = parsePositionScriptSafe(DEFAULT_POSITION_SCRIPT_JSON);
return {
json: DEFAULT_POSITION_SCRIPT_JSON,
events: file?.events ?? [],
initialOrder: file?.initialOrder ?? [],
autoStart: file?.autoStart ?? true,
error,
orderError: null,
firedCount: 0,
};
}
/**
* Gives every car the track position of the rank it now occupies. The set of
* distances is preserved, so the gaps between the cars - and therefore the
* interval column - survive a reshuffle untouched.
*/
function applyRunningOrder(
state: RootState["event"],
orderedGridSpots: GridSpot[],
): boolean {
const current = state.sortedGridSpots;
if (orderedGridSpots.length !== current.length) return false;
const seen: { [gridSpot: number]: true } = {};
for (const gridSpot of orderedGridSpots) {
if (state.grid[gridSpot] == null || seen[gridSpot]) return false;
seen[gridSpot] = true;
}
const distances = current.map(gridSpot => state.grid[gridSpot].distance);
orderedGridSpots.forEach((gridSpot, index) => {
state.grid[gridSpot].distance = distances[index];
});
state.sortedGridSpots = orderedGridSpots.slice();
orderedGridSpots.forEach((gridSpot, index) => {
state.grid[gridSpot].position = index + 1;
});
return true;
}
/**
* Puts the script's `order` list onto the track.
*
* Returns `null` on success, or a readable reason why it could not be applied.
* An unresolvable code used to fail silently, which made one typo in `order`
* look like the whole feature was broken.
*/
function applyInitialOrder(state: RootState["event"]): Optional<string> {
const { initialOrder } = state.positionScript;
if (initialOrder.length === 0) return null;
if (initialOrder.length !== state.grid.length) {
return `order 需要 ${state.grid.length} 位车手,现在给了 ${initialOrder.length} 位`;
}
const spots: GridSpot[] = [];
for (const reference of initialOrder) {
const gridSpot = findGridSpotByRef(state.grid, reference);
if (gridSpot == null) return `order 里的「${reference}」找不到对应车手`;
if (spots.includes(gridSpot)) return `order 里的「${reference}」重复了`;
spots.push(gridSpot);
}
if (!applyRunningOrder(state, spots)) return "order 无法套用到当前车阵";
recalculateRunningOrder(state);
return null;
}
interface IncreaseDistanceAction {
gridSpots: GridSpot[];
distance: Meters;
@@ -226,6 +204,92 @@ interface SetCarStatusAction {
status: CarStatus;
}
/** Every driver attribute the roster editor is allowed to touch. */
export type DriverEditableField =
| "firstName"
| "lastName"
| "initials"
| "number"
| "nationality"
| "performance"
| "yellowTCam"
| "portrait";
export interface UpdateDriverAction {
gridSpot: GridSpot;
field: DriverEditableField;
value: string | number | boolean;
}
export interface SetDriverTeamAction {
gridSpot: GridSpot;
teamId: TeamId;
}
export interface SwapDriversAction {
a: GridSpot;
b: GridSpot;
}
export interface PositionScriptResultAction {
events: PositionScriptEvent[];
initialOrder: string[];
autoStart: boolean;
error: Optional<string>;
}
/**
* The lap counter shown by the status indicator: whatever the simulation
* derives from the leader's distance, plus any laps the director added by hand.
*/
function recalculateLapCount(state: RootState["event"], leaderDistance: Meters) {
state.eventProgress.lapCount = Math.max(
1,
Math.floor((leaderDistance - state.trackStartFinishDelta) / state.trackLength)
+ 1
+ state.eventProgress.lapAdjust,
);
}
/**
* Re-sorts the field by distance and recomputes every derived value: positions,
* the running order and the lap counter. Extracted from the reducer of the same
* name because the position script needs to run it in the middle of its own
* reducer.
*/
function recalculateRunningOrder(state: RootState["event"]) {
const sortingGrid = state.grid.map((car, index): Car & {
gridSpot: GridSpot,
} => ({
gridSpot: index,
...car,
}));
sortingGrid.sort(sortCarPosition);
state.sortedGridSpots = sortingGrid.map(car => car.gridSpot);
const raceEndDistance = state.trackLength * state.eventProgress.scheduledLaps
+ state.trackStartFinishDelta;
sortingGrid.forEach((entry, sortedPosition) => {
// Don't update positions of cars who have crossed the finish line.
if (entry.distance < raceEndDistance) {
state.grid[entry.gridSpot].position = sortedPosition + 1;
}
});
/**
* Calculate which lap we're on by taking the leader's distance.
* Also must consider the fact that the race distance 0 is at the start
* line, but the race ends at the finish line, which is often (always?)
* behind the start line by some distance.
*
* Any laps the director added by hand are layered on top, so the counter can
* be pushed forward without rewriting the race itself.
*/
recalculateLapCount(state, sortingGrid[0].distance);
}
/**
* Note: Add `state.lastUpdate = Date.now();` to the end of every reducer to
* keep components up to date that watch for changes with useEffect() functions.
@@ -245,36 +309,7 @@ export const eventSlice = createSlice({
state.lastUpdate = Date.now();
},
refreshRunningOrder: (state) => {
const sortingGrid = state.grid.map((car, index): Car & {
gridSpot: GridSpot,
} => ({
gridSpot: index,
...car,
}));
sortingGrid.sort(sortCarPosition);
state.sortedGridSpots = sortingGrid.map(car => car.gridSpot);
const raceEndDistance = state.trackLength * state.eventProgress.scheduledLaps
+ state.trackStartFinishDelta;
sortingGrid.forEach((entry, sortedPosition) => {
// Don't update positions of cars who have crossed the finish line.
if (entry.distance < raceEndDistance) {
state.grid[entry.gridSpot].position = sortedPosition + 1;
}
});
/**
* Calculate which lap we're on by taking the leader's distance.
* Also must consider the fact that the race distance 0 is at the start
* line, but the race ends at the finish line, which is often (always?)
* behind the start line by some distance.
*/
state.eventProgress.lapCount =
Math.max(1, Math.floor(
(sortingGrid[0].distance - state.trackStartFinishDelta) / state.trackLength,
) + 1);
recalculateRunningOrder(state);
state.lastUpdate = Date.now();
},
@@ -334,6 +369,302 @@ export const eventSlice = createSlice({
state.lastUpdate = Date.now();
},
/**
* Driver roster editing.
*
* The grid holds the only copy of a driver that the broadcast ever renders,
* so an edit is written straight onto the car sitting in that grid slot and
* every graphic picks it up on the next render.
*/
updateDriver: (state, action: PayloadAction<UpdateDriverAction>) => {
const { gridSpot, field, value } = action.payload;
const driver = state.grid[gridSpot]?.driver;
if (driver == null) return;
switch (field) {
case "firstName":
driver.firstName = String(value);
break;
case "lastName":
driver.lastName = String(value);
break;
case "initials":
driver.initials = String(value).toUpperCase().slice(0, 4);
break;
case "number":
driver.number = clampDriverNumber(Number(value));
break;
case "nationality":
driver.nationality = String(value).toUpperCase();
break;
case "performance":
driver.performance = clampPerformance(Number(value));
break;
case "yellowTCam":
driver.yellowTCam = Boolean(value);
break;
case "portrait":
driver.portrait = sanitizePortrait(value);
break;
default:
return;
}
state.lastUpdate = Date.now();
},
setDriverTeam: (state, action: PayloadAction<SetDriverTeamAction>) => {
const { gridSpot, teamId } = action.payload;
const driver = state.grid[gridSpot]?.driver;
const team = cloneTeam(teamId);
if (driver == null || team == null) return;
driver.team = team;
state.lastUpdate = Date.now();
},
/** Exchanges two cars' drivers without disturbing the race they are running. */
swapDrivers: (state, action: PayloadAction<SwapDriversAction>) => {
const { a, b } = action.payload;
if (a === b || state.grid[a] == null || state.grid[b] == null) return;
const swapped = state.grid[a].driver;
state.grid[a].driver = state.grid[b].driver;
state.grid[b].driver = swapped;
state.lastUpdate = Date.now();
},
/** Restores a single driver to the stock record that ships with the app. */
resetDriver: (state, action: PayloadAction<GridSpot>) => {
const car = state.grid[action.payload];
const stock = car == null ? null : cloneDriver(car.driver.id);
if (car == null || stock == null) return;
car.driver = stock;
state.lastUpdate = Date.now();
},
/**
* Restores the starting lineup. Cars keep the distance they have covered -
* this puts the original drivers back into the slots they started in.
*/
resetRoster: (state) => {
state.grid.forEach((car, index) => {
const driverId = INITIAL_LINEUP[index];
const stock = driverId == null ? null : cloneDriver(driverId);
if (stock != null) car.driver = stock;
});
state.lastUpdate = Date.now();
},
/**
* Bulk replacement used by localStorage rehydration and by the editor's
* import button. Entries are matched to grid slots by index and every
* field is validated before it is allowed anywhere near the state.
*/
applyRoster: (state, action: PayloadAction<Array<Partial<DriverRosterEntry>>>) => {
const entries = action.payload;
if (!Array.isArray(entries)) return;
state.grid.forEach((car, index) => {
const entry = entries[index];
if (entry == null) return;
car.driver = rosterEntryToDriver(entry, car.driver);
});
state.lastUpdate = Date.now();
},
// --------------------------------------------------------------- lap count
/**
* Nudges the LAP counter. The offset is remembered separately from the lap
* the simulation derives from the leader's distance, so the two never fight
* each other: press +1 and the counter reads one lap further on for the rest
* of the race.
*/
adjustLap: (state, action: PayloadAction<number>) => {
state.eventProgress.lapAdjust += action.payload;
const leader = state.grid[state.sortedGridSpots[0]];
if (leader != null) recalculateLapCount(state, leader.distance);
state.lastUpdate = Date.now();
},
// -------------------------------------------------------------- show clock
/**
* The stopwatch beside the LAP counter. Its zero is the moment the timing
* graphics appeared, which is also the zero the position script is timed
* against.
*/
startShowClock: (state) => {
if (state.showClock.startedAt != null) return;
state.showClock.startedAt = Date.now();
if (!state.showClock.hasStarted) {
// First run: lay down the script's starting order and arm the schedule.
state.showClock.hasStarted = true;
state.positionScript.firedCount = 0;
state.positionScript.orderError = applyInitialOrder(state);
}
state.lastUpdate = Date.now();
},
pauseShowClock: (state) => {
if (state.showClock.startedAt == null) return;
state.showClock.accumulatedMs += Date.now() - state.showClock.startedAt;
state.showClock.startedAt = null;
state.lastUpdate = Date.now();
},
/**
* Back to zero and ready to replay the script from the top. The manual lap
* offset is rewound too, so a replay reproduces the run exactly.
*/
resetShowClock: (state) => {
state.showClock.accumulatedMs = 0;
state.showClock.startedAt = Date.now();
state.showClock.hasStarted = true;
state.positionScript.firedCount = 0;
state.eventProgress.lapAdjust = 0;
state.positionScript.orderError = applyInitialOrder(state);
recalculateRunningOrder(state);
state.lastUpdate = Date.now();
},
// ---------------------------------------------------------- position script
setPositionScriptJson: (state, action: PayloadAction<string>) => {
state.positionScript.json = action.payload;
},
/**
* Result of parsing whatever the user has typed. Nothing is thrown away on a
* bad edit: the error is stored and the last good schedule keeps running.
* A genuinely different schedule rewinds the run so it can play again.
*/
applyPositionScriptResult: (
state,
action: PayloadAction<PositionScriptResultAction>,
) => {
const { events, initialOrder, autoStart, error } = action.payload;
const previous = JSON.stringify({
events: state.positionScript.events,
initialOrder: state.positionScript.initialOrder,
});
const next = JSON.stringify({ events, initialOrder });
state.positionScript.events = events;
state.positionScript.initialOrder = initialOrder;
state.positionScript.autoStart = autoStart;
state.positionScript.error = error;
if (next !== previous) {
/**
* A changed schedule is meant to be watched. Rewinding the run is what
* makes editing the JSON feel like "press play": previously only
* `firedCount` was cleared, so an edit made after a few seconds put every
* earlier line into the past at once and they all fired together in a
* burst, which looked like the script had jumped or had not run at all.
*/
state.positionScript.firedCount = 0;
state.eventProgress.lapAdjust = 0;
if (state.showClock.hasStarted) {
state.showClock.accumulatedMs = 0;
state.showClock.startedAt = Date.now();
}
// `order` takes effect on the spot instead of waiting for a reset.
state.positionScript.orderError = applyInitialOrder(state);
}
state.lastUpdate = Date.now();
},
/**
* Fires every script line that has come due, in one go, so the running order
* is only reshuffled once per tick no matter how many lines are waiting.
*/
runPositionScript: (state, action: PayloadAction<{ elapsedMs: number }>) => {
const script = state.positionScript;
const { events } = script;
if (events.length === 0 || script.firedCount >= events.length) return;
const { elapsedMs } = action.payload;
let fired = script.firedCount;
const order = state.sortedGridSpots.slice();
let orderChanged = false;
let lapDelta = 0;
const statusChanges: Array<{ gridSpot: GridSpot; status: CarStatus }> = [];
while (fired < events.length && events[fired].at <= elapsedMs) {
const event = events[fired];
fired++;
const spots: GridSpot[] = [];
for (const reference of event.drivers) {
const gridSpot = findGridSpotByRef(state.grid, reference);
if (gridSpot != null && !spots.includes(gridSpot)) spots.push(gridSpot);
}
// An unresolvable name is skipped rather than stalling the schedule.
// "lap" is the one action that carries no driver to resolve.
if (spots.length === 0 && event.action !== "lap") continue;
switch (event.action) {
case "swap": {
if (spots.length < 2) break;
const a = order.indexOf(spots[0]);
const b = order.indexOf(spots[1]);
if (a === -1 || b === -1) break;
order[a] = spots[1];
order[b] = spots[0];
orderChanged = true;
break;
}
case "move": {
const target = Math.max(1, Math.min(order.length, event.to ?? 1)) - 1;
const from = order.indexOf(spots[0]);
if (from === -1) break;
order.splice(from, 1);
order.splice(target, 0, spots[0]);
orderChanged = true;
break;
}
case "retire":
statusChanges.push({ gridSpot: spots[0], status: CarStatus.Retired });
break;
case "restore":
statusChanges.push({ gridSpot: spots[0], status: CarStatus.Normal });
break;
case "lap":
lapDelta += event.value ?? 1;
break;
}
}
// Nothing came due: leave the state untouched so the 100ms tick does not
// ripple a re-render through the whole broadcast.
if (fired === script.firedCount) return;
script.firedCount = fired;
if (orderChanged) applyRunningOrder(state, order);
statusChanges.forEach(({ gridSpot, status }) => {
state.grid[gridSpot].status = status;
});
if (lapDelta !== 0) state.eventProgress.lapAdjust += lapDelta;
if (orderChanged || statusChanges.length > 0) {
recalculateRunningOrder(state);
} else if (lapDelta !== 0) {
const leader = state.grid[state.sortedGridSpots[0]];
if (leader != null) recalculateLapCount(state, leader.distance);
}
state.lastUpdate = Date.now();
},
},
});
@@ -344,5 +675,18 @@ export const {
increaseDistance,
awardFastestLap,
setCarStatus,
updateDriver,
setDriverTeam,
swapDrivers,
resetDriver,
resetRoster,
applyRoster,
adjustLap,
startShowClock,
pauseShowClock,
resetShowClock,
setPositionScriptJson,
applyPositionScriptResult,
runPositionScript,
} = eventSlice.actions;
export default eventSlice.reducer;
+64
View File
@@ -0,0 +1,64 @@
import { DriverRosterEntry } from "../../utils/roster";
/**
* Local persistence for the two things the user authors by hand: the driver
* roster and the position script.
*
* Only that user authored data is persisted - never the race state, which is
* rebuilt from scratch on every load.
*/
const STORAGE_KEY = "sab-f1-ui:driver-roster:v1";
const SCRIPT_STORAGE_KEY = "sab-f1-ui:position-script:v1";
export function loadStoredRoster(): DriverRosterEntry[] | null {
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (raw == null) return null;
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed as DriverRosterEntry[] : null;
} catch (error) {
console.warn("读取本地保存的车手名单失败。", error);
return null;
}
}
export function storeRoster(roster: DriverRosterEntry[]): void {
try {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(roster));
} catch (error) {
console.warn("保存车手名单失败。", error);
}
}
export function clearStoredRoster(): void {
try {
window.localStorage.removeItem(STORAGE_KEY);
} catch (error) {
console.warn("清除本地保存的车手名单失败。", error);
}
}
export { STORAGE_KEY as ROSTER_STORAGE_KEY, SCRIPT_STORAGE_KEY };
/**
* The position script is looked up as raw text: it is the user's own JSON, and
* keeping it verbatim (rather than re-serializing) preserves their formatting
* and any comments-in-progress.
*/
export function loadStoredScript(): string | null {
try {
const raw = window.localStorage.getItem(SCRIPT_STORAGE_KEY);
return raw != null && raw.trim() !== "" ? raw : null;
} catch (error) {
console.warn("读取本地保存的名次脚本失败。", error);
return null;
}
}
export function storeScript(json: string): void {
try {
window.localStorage.setItem(SCRIPT_STORAGE_KEY, json);
} catch (error) {
console.warn("保存名次脚本失败。", error);
}
}
@@ -0,0 +1,36 @@
import { useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { eventSelector } from "./eventSelector";
import { runPositionScript } from "./eventSlice";
const SCRIPT_TICK_MS = 100;
/**
* Drives the position script off the show clock.
*
* The interval is registered once and reads the latest state through a ref, so
* the race ticking along underneath never rebuilds it. When the clock is paused
* or the schedule has run out the tick becomes a no-op.
*/
export function usePositionScriptRunner() {
const dispatch = useDispatch();
const { showClock, positionScript } = useSelector(eventSelector);
const latest = useRef({ showClock, positionScript, dispatch });
latest.current = { showClock, positionScript, dispatch };
useEffect(() => {
const timer = window.setInterval(() => {
const current = latest.current;
if (current.showClock.startedAt == null) return;
if (current.positionScript.firedCount >= current.positionScript.events.length) return;
const elapsedMs = current.showClock.accumulatedMs
+ (Date.now() - current.showClock.startedAt);
current.dispatch(runPositionScript({ elapsedMs }));
}, SCRIPT_TICK_MS);
return () => window.clearInterval(timer);
}, []);
}
+77
View File
@@ -0,0 +1,77 @@
export type ShortcutDefinition = {
keys: string,
description: string,
};
export type ShortcutGroup = {
title: string,
shortcuts: ShortcutDefinition[],
};
/**
* The single description of what the keyboard can do. The handler in
* useBroadcastShortcuts implements exactly this list and the help overlay
* renders it, so the documentation cannot go stale.
*/
export const SHORTCUT_GROUPS: ShortcutGroup[] = [
{
title: "面板",
shortcuts: [
{ keys: "E", description: "打开 / 关闭车手名单编辑器" },
{ keys: "J", description: "打开 / 关闭 JSON 名次脚本" },
{ keys: "?", description: "打开 / 关闭这份快捷键列表" },
{ keys: "Esc", description: "关闭面板;没有面板时收起字幕" },
],
},
{
title: "选择车辆",
shortcuts: [
{ keys: "↑ ↓", description: "按名次在车阵里上下移动光标" },
{ keys: "Home End", description: "光标跳到领先车或最后一名" },
{ keys: "空格", description: "把光标所在车加入 / 移出已选" },
{ keys: "1 … 9 0", description: "选中正跑在 P1 … P10 的车" },
{ keys: "Shift + 1 … 0", description: "把该车加成第二名字幕车手" },
{ keys: "X", description: "清空已选" },
],
},
{
title: "车名字幕",
shortcuts: [
{ keys: "回车", description: "为已选车手出字幕,没选就用光标所在车" },
{ keys: "Shift + 回车", description: "播放字幕动画的下一步" },
{ keys: "Backspace", description: "收起字幕" },
{ keys: "[ ]", description: "切换字幕模式" },
{ keys: ", .", description: "切换字幕子模式" },
{ keys: "F", description: "切换旗帜:国旗 → 车队 → 无" },
{ keys: "P", description: "显示 / 隐藏名次牌" },
{ keys: "N", description: "显示 / 隐藏车号" },
{ keys: "O", description: "显示 / 隐藏头像" },
],
},
{
title: "圈数与计时器",
shortcuts: [
{ keys: "+ =", description: "圈数 +1" },
{ keys: "-", description: "圈数 -1" },
{ keys: "C", description: "启动 / 暂停 LAP 旁边的计时器" },
{ keys: "Shift + C", description: "计时器归零,从头重放名次脚本" },
],
},
{
title: "比赛控制",
shortcuts: [
{ keys: "S", description: "开始 / 停止比赛" },
{ keys: "R", description: "重算名次" },
{ keys: "Shift + P", description: "把已选车往前推 200 米" },
{ keys: "Shift + O", description: "全场往前推 100 米" },
{ keys: "Shift + F", description: "把最快圈授予已选车" },
{ keys: "D", description: "已选车退赛 / 取消退赛" },
],
},
{
title: "计时塔",
shortcuts: [
{ keys: "T", description: "循环切换计时塔显示模式" },
{ keys: "I", description: "在领先差与前车间隔之间切换" },
],
},
];
@@ -0,0 +1,466 @@
import { useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { broadcastDirectorSelector } from "../broadcast/director/broadcastDirectorSelector";
import { broadcastGraphicsSelector } from "../broadcast/graphics/broadcastGraphicsSelector";
import { eventSelector } from "../event/eventSelector";
import { uiSelector } from "../ui/uiSelector";
import {
clearSelectedCars,
replaceSelectedCars,
setCursorGridSpot,
toggleSelectedCar,
updateChyronSettings,
} from "../broadcast/director/broadcastDirectorSlice";
import {
setTimingTowerDisplayMode,
setTimingTowerSplitsMode,
} from "../broadcast/graphics/broadcastGraphicsSlice";
import {
adjustLap,
awardFastestLap,
increaseDistance,
pauseShowClock,
refreshRunningOrder,
resetShowClock,
setCarStatus,
setEventStatus,
startShowClock,
} from "../event/eventSlice";
import {
pushToast,
setDriverEditorOpen,
setPositionScriptOpen,
setShortcutHelpOpen,
toggleDriverEditor,
togglePositionScript,
toggleShortcutHelp,
} from "../ui/uiSlice";
import { useChyronDirector } from "../broadcast/director/useChyronDirector";
import {
flagModeList,
getChyronModesList,
getChyronSubModesList,
} from "../../domain/data/broadcastGraphics";
import {
BGTimingTowerDisplayMode,
BGTimingTowerSplitsMode,
CarStatus,
EventStatus,
FlagMode,
GridSpot,
} from "../../types/state";
import {
chyronModeLabels,
chyronSubModeLabels,
eventStatusLabels,
flagModeLabels,
labelOf,
timingTowerDisplayModeLabels,
timingTowerSplitsModeLabels,
} from "../../i18n/labels";
const EDITABLE_TAGS = ["INPUT", "TEXTAREA", "SELECT"];
const DISPLAY_MODES: BGTimingTowerDisplayMode[] = [
BGTimingTowerDisplayMode.Hidden,
BGTimingTowerDisplayMode.LeftOnly,
BGTimingTowerDisplayMode.LeftAndRight,
BGTimingTowerDisplayMode.FullLeft,
];
/** Typing into a form control must never fire a broadcast shortcut. */
function isTypingTarget(target: EventTarget | null): boolean {
const element = target as HTMLElement | null;
if (element == null || typeof element.tagName !== "string") return false;
if (element.isContentEditable) return true;
return EDITABLE_TAGS.includes(element.tagName);
}
/**
* Digits address cars by running position.
*
* The physical key is what is read first, because it is the only thing that
* stays stable when Shift turns "1" into "!" - the typed key is kept as a
* fallback for environments that do not report a code.
*/
function digitFromKeyboard(event: KeyboardEvent): number | null {
const fromCode = /^(?:Digit|Numpad)([0-9])$/.exec(event.code);
const raw = fromCode != null ? fromCode[1] : (/^[0-9]$/.test(event.key) ? event.key : null);
if (raw == null) return null;
// "0" is wired to P10, matching how the positions read on screen.
return raw === "0" ? 10 : Number(raw);
}
function cycle<T>(list: T[], current: T, delta: number): T | null {
if (list.length === 0) return null;
const index = list.indexOf(current);
if (index === -1) return list[0];
return list[(index + delta + list.length) % list.length];
}
/**
* The whole keyboard control surface of the broadcast page.
*
* The listener is registered once and reads the latest state through a ref, so
* the race ticking along every 600ms never tears down and rebuilds it.
*/
export function useBroadcastShortcuts() {
const dispatch = useDispatch();
const { grid, sortedGridSpots, eventStatus, showClock, eventProgress } =
useSelector(eventSelector);
const { selectedCars, cursorGridSpot, chyronSettings } = useSelector(broadcastDirectorSelector);
const { timingBoard } = useSelector(broadcastGraphicsSelector);
const ui = useSelector(uiSelector);
const chyron = useChyronDirector();
const handlerRef = useRef<(event: KeyboardEvent) => void>(() => undefined);
handlerRef.current = (event: KeyboardEvent) => {
// Leave the browser's own shortcuts alone.
if (event.ctrlKey || event.metaKey || event.altKey) return;
if (isTypingTarget(event.target)) return;
const { key } = event;
const shift = event.shiftKey;
// Shift changes the reported key ("p" becomes "P"), so letters are folded
// to lower case and Shift is tested explicitly instead.
const press = key.length === 1 ? key.toLowerCase() : key;
const consume = () => {
event.preventDefault();
event.stopPropagation();
};
const say = (text: string) => dispatch(pushToast(text));
// A panel always wins. While one is open only Escape (plus "?" for the help
// list itself) does anything, so a stray keystroke cannot fire the show.
if (ui.shortcutHelpOpen) {
if (key === "Escape" || key === "?") {
consume();
dispatch(setShortcutHelpOpen(false));
}
return;
}
if (ui.driverEditorOpen) {
if (key === "Escape") {
consume();
dispatch(setDriverEditorOpen(false));
}
return;
}
if (ui.positionScriptOpen) {
if (key === "Escape") {
consume();
dispatch(setPositionScriptOpen(false));
}
return;
}
if (key === "?") {
consume();
dispatch(toggleShortcutHelp());
return;
}
if (press === "e" && !shift) {
consume();
dispatch(toggleDriverEditor());
return;
}
if (press === "j" && !shift) {
consume();
dispatch(togglePositionScript());
return;
}
const gridSpotAtPosition = (position: number): GridSpot | null =>
sortedGridSpots[position - 1] ?? null;
const labelFor = (gridSpot: GridSpot | null | undefined): string =>
gridSpot == null ? "?" : (grid[gridSpot]?.driver.initials ?? "?");
const labelList = (spots: GridSpot[]) => spots.map(labelFor).join(" + ");
/** The cars the chyron and race commands act on: selection first, then cursor. */
const actionSpots = (): GridSpot[] => (
selectedCars.length > 0
? selectedCars
: (cursorGridSpot == null ? [] : [cursorGridSpot])
);
// Digits select a car by the position it is running in.
const digit = digitFromKeyboard(event);
if (digit != null) {
const spot = gridSpotAtPosition(digit);
if (spot == null) return;
consume();
dispatch(setCursorGridSpot(spot));
if (shift) {
const wasSelected = selectedCars.includes(spot);
dispatch(toggleSelectedCar(spot));
say(`已${wasSelected ? "移出" : "加入"} P${digit} ${labelFor(spot)}`);
} else {
dispatch(replaceSelectedCars([spot]));
say(`已选中 P${digit} ${labelFor(spot)}`);
}
return;
}
switch (press) {
// ---------------------------------------------------------------- cursor
case "ArrowUp":
case "ArrowDown": {
consume();
const order = sortedGridSpots;
if (order.length === 0) return;
const delta = press === "ArrowUp" ? -1 : 1;
const currentIndex = cursorGridSpot == null ? -1 : order.indexOf(cursorGridSpot);
const nextIndex = currentIndex === -1
? (delta > 0 ? 0 : order.length - 1)
: Math.min(order.length - 1, Math.max(0, currentIndex + delta));
dispatch(setCursorGridSpot(order[nextIndex]));
return;
}
case "Home":
case "End": {
consume();
if (sortedGridSpots.length === 0) return;
dispatch(setCursorGridSpot(
press === "Home" ? sortedGridSpots[0] : sortedGridSpots[sortedGridSpots.length - 1],
));
return;
}
case " ": {
consume();
const spot = cursorGridSpot ?? sortedGridSpots[0] ?? null;
if (spot == null) return;
const wasSelected = selectedCars.includes(spot);
dispatch(toggleSelectedCar(spot));
say(`已把 ${labelFor(spot)} ${wasSelected ? "移出" : "加入"}已选`);
return;
}
case "x": {
consume();
dispatch(clearSelectedCars(null));
say("已清空已选");
return;
}
// --------------------------------------------------------------- chyrons
case "Enter": {
consume();
if (shift) {
chyron.next();
say("字幕:下一步动画");
return;
}
if (chyron.targetSpots.length === 0) {
say("先选一辆车:数字 1-9、0,或上下方向键");
return;
}
chyron.open();
say(`字幕:${labelList(chyron.targetSpots)}`);
return;
}
case "Backspace": {
consume();
chyron.close();
say("字幕收起中");
return;
}
case "Escape": {
consume();
chyron.close();
return;
}
case "[":
case "]": {
consume();
const mode = cycle(getChyronModesList(), chyronSettings.mode, press === "]" ? 1 : -1);
if (mode == null) return;
const subModes = getChyronSubModesList(mode);
dispatch(updateChyronSettings({
mode,
subMode: subModes.includes(chyronSettings.subMode)
? chyronSettings.subMode
: (subModes[0] ?? chyronSettings.subMode),
}));
say(`字幕模式:${labelOf(chyronModeLabels, mode)}`);
return;
}
case ",":
case ".": {
consume();
const subMode = cycle(
getChyronSubModesList(chyronSettings.mode),
chyronSettings.subMode,
press === "." ? 1 : -1,
);
if (subMode == null) return;
dispatch(updateChyronSettings({ subMode }));
say(`字幕子模式:${labelOf(chyronSubModeLabels, subMode)}`);
return;
}
case "f": {
consume();
if (shift) {
// Shift+F - fastest lap.
const spot = actionSpots()[0] ?? null;
if (spot == null) {
say("先选一辆车");
return;
}
dispatch(awardFastestLap(spot));
say(`最快圈:${labelFor(spot)}`);
return;
}
const flagMode = cycle(flagModeList, chyronSettings.flagMode, 1);
if (flagMode == null) return;
dispatch(updateChyronSettings({ flagMode }));
say(`旗帜:${labelOf(flagModeLabels, flagMode as FlagMode)}`);
return;
}
case "p": {
consume();
if (shift) {
// Shift+P - nudge the selected cars up the road.
const spots = actionSpots();
if (spots.length === 0) {
say("先选一辆车");
return;
}
dispatch(increaseDistance({
gridSpots: spots,
distance: 200,
randomness: 0,
usePerformance: false,
}));
dispatch(refreshRunningOrder());
say(`${labelList(spots)} +200 米`);
return;
}
const showPosFlag = !chyronSettings.showPosFlag;
dispatch(updateChyronSettings({ showPosFlag }));
say(`名次牌:${showPosFlag ? "显示" : "隐藏"}`);
return;
}
case "o": {
consume();
if (shift) {
// Shift+O - nudge the whole field.
dispatch(increaseDistance({
gridSpots: Array.from(Array(grid.length).keys()),
distance: 100,
randomness: 0.05,
usePerformance: true,
}));
dispatch(refreshRunningOrder());
say("全场 +100 米");
return;
}
const showPortrait = !chyronSettings.showPortrait;
dispatch(updateChyronSettings({ showPortrait }));
say(`头像:${showPortrait ? "显示" : "隐藏"}`);
return;
}
case "n": {
consume();
const showDriverNumber = !chyronSettings.showDriverNumber;
dispatch(updateChyronSettings({ showDriverNumber }));
say(`车号:${showDriverNumber ? "显示" : "隐藏"}`);
return;
}
// -------------------------------------------------- laps and show clock
case "=":
case "+": {
consume();
dispatch(adjustLap(1));
say(`圈数 ${eventProgress.lapCount + 1}`);
return;
}
case "-":
case "_": {
consume();
dispatch(adjustLap(-1));
say(`圈数 ${Math.max(1, eventProgress.lapCount - 1)}`);
return;
}
case "c": {
consume();
if (shift) {
dispatch(resetShowClock());
say("计时器已归零,脚本从头重放");
return;
}
if (showClock.startedAt == null) {
dispatch(startShowClock());
say("计时器已启动");
} else {
dispatch(pauseShowClock());
say("计时器已暂停");
}
return;
}
// ------------------------------------------------------------ race state
case "s": {
consume();
const next = eventStatus === EventStatus.Running
? EventStatus.Stopped
: EventStatus.Running;
dispatch(setEventStatus(next));
say(`比赛${labelOf(eventStatusLabels, next)}`);
return;
}
case "r": {
consume();
dispatch(refreshRunningOrder());
say("名次已重算");
return;
}
case "d": {
consume();
const spots = actionSpots();
if (spots.length === 0) {
say("先选一辆车");
return;
}
const allRetired = spots.every(spot => grid[spot]?.status === CarStatus.Retired);
dispatch(setCarStatus({
gridSpots: spots,
status: allRetired ? CarStatus.Normal : CarStatus.Retired,
}));
dispatch(refreshRunningOrder());
say(allRetired ? "已取消退赛" : "已退赛");
return;
}
// --------------------------------------------------------- timing tower
case "t": {
consume();
const displayMode = cycle(DISPLAY_MODES, timingBoard.timingTower.displayMode, 1);
if (displayMode == null) return;
dispatch(setTimingTowerDisplayMode(displayMode));
say(`计时塔:${labelOf(timingTowerDisplayModeLabels, displayMode)}`);
return;
}
case "i": {
consume();
const splitsMode = timingBoard.timingTower.splitsMode === BGTimingTowerSplitsMode.Leader
? BGTimingTowerSplitsMode.Interval
: BGTimingTowerSplitsMode.Leader;
dispatch(setTimingTowerSplitsMode(splitsMode));
say(`计时模式:${labelOf(timingTowerSplitsModeLabels, splitsMode)}`);
return;
}
default:
return;
}
};
useEffect(() => {
const listener = (event: KeyboardEvent) => handlerRef.current(event);
window.addEventListener("keydown", listener);
return () => window.removeEventListener("keydown", listener);
}, []);
}
+231
View File
@@ -0,0 +1,231 @@
import { RootState } from "../../types/state";
/** Default port of the standalone relay (`npm run relay`). */
export const DEFAULT_RELAY_PORT = 8181;
export type ChannelRole = "controller" | "output";
export type ChannelStatus = "connecting" | "open" | "closed";
/**
* The slice of app state that the controller mirrors to output pages.
* Keep this serializable - it travels over the wire as JSON.
*/
export interface OutputSnapshot {
event: RootState["event"];
workspace: RootState["workspace"];
broadcastGraphics: RootState["broadcastGraphics"];
broadcastDirector: RootState["broadcastDirector"];
overlayTool: RootState["overlayTool"];
}
/** Slices that the output renders from. */
export const SNAPSHOT_KEYS = [
"event",
"workspace",
"broadcastGraphics",
"broadcastDirector",
"overlayTool",
] as const;
/**
* A patch carrying only the slices that changed. Untouched slices keep their
* identity on the receiving side, so e.g. a timing update never re-renders
* (and therefore never restarts the animations of) the chyron tree.
*/
export type SnapshotPatch = Partial<OutputSnapshot>;
export type ChannelMessage =
| { type: "hello"; role: ChannelRole }
| { type: "welcome"; role: ChannelRole; controllers: number; outputs: number }
| { type: "state"; payload: SnapshotPatch };
export interface SnapshotCollector {
/** Changed slices, or `null` when nothing the output renders has changed. */
collect: (state: RootState) => SnapshotPatch | null;
/** Forget what was sent, so the next `collect` ships everything (reconnect). */
reset: () => void;
}
export function createSnapshotCollector(): SnapshotCollector {
const previous: Record<string, unknown> = {};
return {
collect: (state) => {
const patch: SnapshotPatch = {};
let changed = false;
SNAPSHOT_KEYS.forEach((key) => {
const value = state[key];
// Redux slices are immutable, so a reference check is both exact and
// free - no serialization runs while the user is just driving the UI.
if (value === previous[key]) return;
previous[key] = value;
patch[key] = value as never;
changed = true;
});
return changed ? patch : null;
},
reset: () => {
SNAPSHOT_KEYS.forEach((key) => {
delete previous[key];
});
},
};
}
/**
* Resolve the relay URL. Precedence:
* 1. `?ws=ws://host:port` (or `?relay=`) on the page URL - handy for OBS.
* 2. `REACT_APP_RELAY_URL` environment variable.
* 3. Same host as the page, on the default relay port.
*/
export function resolveRelayUrl(): string {
const params = new URLSearchParams(window.location.search);
const override = params.get("ws") || params.get("relay");
if (override) return override;
const fromEnv = process.env.REACT_APP_RELAY_URL;
if (fromEnv) return fromEnv;
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
const host = window.location.hostname || "localhost";
return protocol + "//" + host + ":" + DEFAULT_RELAY_PORT;
}
export interface OutputChannel {
send: (message: ChannelMessage) => void;
sendState: (payload: SnapshotPatch) => void;
close: () => void;
getStatus: () => ChannelStatus;
}
export interface OutputChannelOptions {
role: ChannelRole;
url?: string;
onMessage?: (message: ChannelMessage) => void;
onStatus?: (status: ChannelStatus) => void;
}
/**
* A tiny auto-reconnecting WebSocket channel. While it is offline it remembers
* the latest state message only, so a burst of updates never plays back stale
* frames once the connection is back.
*/
export function createOutputChannel({
role,
url,
onMessage,
onStatus,
}: OutputChannelOptions): OutputChannel {
const baseUrl = url || resolveRelayUrl();
const target = baseUrl + (baseUrl.indexOf("?") === -1 ? "?" : "&") + "role=" + role;
let socket: WebSocket | null = null;
let closed = false;
let status: ChannelStatus = "connecting";
let retries = 0;
let retryTimer: number | null = null;
let queued: string | null = null;
let lastStateJson = "";
const setStatus = (next: ChannelStatus) => {
if (status === next) return;
status = next;
if (onStatus) onStatus(next);
};
const push = (data: string) => {
if (socket != null && socket.readyState === WebSocket.OPEN) {
socket.send(data);
return;
}
queued = data;
};
const connect = () => {
if (closed) return;
setStatus("connecting");
let next: WebSocket;
try {
next = new WebSocket(target);
} catch (error) {
scheduleRetry();
return;
}
socket = next;
next.onopen = () => {
retries = 0;
setStatus("open");
next.send(JSON.stringify({ type: "hello", role }));
if (queued != null) {
next.send(queued);
queued = null;
}
};
next.onmessage = (event: MessageEvent) => {
if (typeof event.data !== "string" || onMessage == null) return;
try {
onMessage(JSON.parse(event.data) as ChannelMessage);
} catch (error) {
// Ignore malformed frames.
}
};
next.onclose = () => {
if (socket === next) socket = null;
setStatus("closed");
scheduleRetry();
};
next.onerror = () => {
try {
next.close();
} catch (error) {
// Ignore.
}
};
};
const scheduleRetry = () => {
if (closed || retryTimer != null) return;
const delay = Math.min(500 * Math.pow(2, retries), 5000);
retries += 1;
retryTimer = window.setTimeout(() => {
retryTimer = null;
connect();
}, delay);
};
connect();
return {
send: (message) => push(JSON.stringify(message)),
sendState: (payload) => {
const data = JSON.stringify({ type: "state", payload });
if (data === lastStateJson && socket != null && socket.readyState === WebSocket.OPEN) return;
lastStateJson = data;
push(data);
},
close: () => {
closed = true;
if (retryTimer != null) {
window.clearTimeout(retryTimer);
retryTimer = null;
}
if (socket != null) {
socket.onclose = null;
try {
socket.close();
} catch (error) {
// Ignore.
}
socket = null;
}
setStatus("closed");
},
getStatus: () => status,
};
}
@@ -0,0 +1,10 @@
import { createAction } from "@reduxjs/toolkit";
import { SnapshotPatch } from "./outputChannel";
/**
* Replaces mirrored slices of the store with a snapshot received from the
* controller. Handled by the root reducer in `src/store.ts` - the output page
* never dispatches it, and a controller page never has it dispatched against it.
*/
export const applySnapshot = createAction<SnapshotPatch>("outputChannel/applySnapshot");
+3
View File
@@ -0,0 +1,3 @@
import { RootState } from "../../types/state";
export const uiSelector = (state: RootState) => state.ui;
+62
View File
@@ -0,0 +1,62 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { RootState } from "../../types/state";
const initialState: RootState["ui"] = {
driverEditorOpen: false,
shortcutHelpOpen: false,
positionScriptOpen: false,
toast: null,
};
let toastId = 0;
export const uiSlice = createSlice({
name: "ui",
initialState,
reducers: {
setDriverEditorOpen: (state, action: PayloadAction<boolean>) => {
state.driverEditorOpen = action.payload;
},
toggleDriverEditor: (state) => {
state.driverEditorOpen = !state.driverEditorOpen;
},
setShortcutHelpOpen: (state, action: PayloadAction<boolean>) => {
state.shortcutHelpOpen = action.payload;
},
toggleShortcutHelp: (state) => {
state.shortcutHelpOpen = !state.shortcutHelpOpen;
},
setPositionScriptOpen: (state, action: PayloadAction<boolean>) => {
state.positionScriptOpen = action.payload;
},
togglePositionScript: (state) => {
state.positionScriptOpen = !state.positionScriptOpen;
},
/** Closes every panel the shortcut layer knows about. */
closeAllPanels: (state) => {
state.driverEditorOpen = false;
state.shortcutHelpOpen = false;
state.positionScriptOpen = false;
},
pushToast: (state, action: PayloadAction<string>) => {
state.toast = { id: ++toastId, text: action.payload };
},
clearToast: (state) => {
state.toast = null;
},
},
});
export const {
setDriverEditorOpen,
toggleDriverEditor,
setShortcutHelpOpen,
toggleShortcutHelp,
setPositionScriptOpen,
togglePositionScript,
closeAllPanels,
pushToast,
clearToast,
} = uiSlice.actions;
export default uiSlice.reducer;
+155
View File
@@ -0,0 +1,155 @@
import {
BGTimingTowerDisplayMode,
BGTimingTowerSplitsMode,
BGStatusIndicatorModes,
CarNotice,
CarStatus,
CourseFlag,
EventMode,
EventStatus,
FlagMode,
PositionScriptAction,
SafetyCarStatus,
SectorFlag,
TyreCompound,
VirtualSafetyCarStatus,
} from "../types/state";
import { Corner } from "../types/style";
/**
* Chinese labels for the values the interface has to show.
*
* These are display names only - the underlying values in the store, in the
* position script JSON and in the URL all stay exactly as they were, so nothing
* that reads the state has to change.
*/
export function labelOf<T extends string | number>(
table: { [key in T]?: string },
value: T,
fallback?: string,
): string {
return table[value] ?? fallback ?? String(value);
}
// Chyrons
export const chyronModeLabels: { [mode: string]: string } = {
driver: "车手",
};
export const chyronSubModeLabels: { [subMode: string]: string } = {
medium: "中号",
large: "大号",
};
export const flagModeLabels: { [mode in FlagMode]?: string } = {
country: "国旗",
team: "车队",
none: "无",
};
// Timing tower
export const timingTowerDisplayModeLabels: { [mode in BGTimingTowerDisplayMode]?: string } = {
[BGTimingTowerDisplayMode.Hidden]: "隐藏",
[BGTimingTowerDisplayMode.LeftOnly]: "仅左栏",
[BGTimingTowerDisplayMode.LeftAndRight]: "左右双栏",
[BGTimingTowerDisplayMode.FullLeft]: "左栏全宽",
};
export const timingTowerSplitsModeLabels: { [mode in BGTimingTowerSplitsMode]?: string } = {
[BGTimingTowerSplitsMode.Leader]: "领先差",
[BGTimingTowerSplitsMode.Interval]: "前车间隔",
};
export const statusIndicatorModeLabels: { [mode in BGStatusIndicatorModes]?: string } = {
[BGStatusIndicatorModes.LapNarrow]: "窄",
[BGStatusIndicatorModes.LapWide]: "宽",
};
// Race state
export const eventStatusLabels: { [status in EventStatus]?: string } = {
[EventStatus.Waiting]: "等待开始",
[EventStatus.Running]: "进行中",
[EventStatus.Stopped]: "已结束",
[EventStatus.Suspended]: "暂停",
};
export const eventModeLabels: { [mode in EventMode]?: string } = {
[EventMode.Race]: "正赛",
[EventMode.Sprint]: "冲刺赛",
[EventMode.Practice1]: "练习赛一",
[EventMode.Practice2]: "练习赛二",
[EventMode.Practice3]: "练习赛三",
[EventMode.Qualifying1]: "排位赛一",
[EventMode.Qualifying2]: "排位赛二",
[EventMode.Qualifying3]: "排位赛三",
};
export const carStatusLabels: { [status in CarStatus]?: string } = {
[CarStatus.Normal]: "正常",
[CarStatus.OnGrid]: "发车格",
[CarStatus.Finished]: "完赛",
[CarStatus.Retired]: "退赛",
[CarStatus.InPit]: "维修区",
[CarStatus.OutLap]: "出场圈",
[CarStatus.InLap]: "回场圈",
[CarStatus.DidNotStart]: "未发车",
};
export const carNoticeLabels: { [notice in CarNotice]?: string } = {
[CarNotice.FastestLap]: "最快圈",
[CarNotice.BlueFlag]: "蓝旗",
[CarNotice.BlackAndWhiteFlag]: "黑白旗",
[CarNotice.BlackFlag]: "黑旗",
[CarNotice.BlackWithOrangeCircleFlag]: "黑橙旗",
[CarNotice.UnderInvestigation]: "调查中",
[CarNotice.PenaltyDriveThrough]: "通过维修区处罚",
[CarNotice.Penalty5Seconds]: "5 秒罚时",
[CarNotice.Penalty10Seconds]: "10 秒罚时",
[CarNotice.Penalty10SecondsStopGo]: "10 秒停走处罚",
};
export const courseFlagLabels: { [flag in CourseFlag]?: string } = {
[CourseFlag.Green]: "绿旗",
[CourseFlag.Yellow]: "黄旗",
[CourseFlag.Chequered]: "格子旗",
[CourseFlag.Red]: "红旗",
};
export const sectorFlagLabels: { [flag in SectorFlag]?: string } = {
[SectorFlag.Green]: "绿",
[SectorFlag.Yellow]: "黄",
[SectorFlag.DoubleYellow]: "双黄",
[SectorFlag.White]: "白",
[SectorFlag.RedYellow]: "红黄",
};
export const safetyCarLabels: { [status in SafetyCarStatus]?: string } = {
[SafetyCarStatus.Clear]: "无",
[SafetyCarStatus.Starting]: "准备出动",
[SafetyCarStatus.Out]: "已出动",
[SafetyCarStatus.Ending]: "准备回站",
};
export const virtualSafetyCarLabels: { [status in VirtualSafetyCarStatus]?: string } = {
[VirtualSafetyCarStatus.Clear]: "无",
[VirtualSafetyCarStatus.Active]: "生效中",
[VirtualSafetyCarStatus.Ending]: "准备结束",
};
export const tyreCompoundLabels: { [compound in TyreCompound]?: string } = {
[TyreCompound.Soft]: "软胎",
[TyreCompound.Medium]: "中性胎",
[TyreCompound.Hard]: "硬胎",
[TyreCompound.Wet]: "全雨胎",
[TyreCompound.Intermediate]: "半雨胎",
};
// Position script
export const positionScriptActionLabels: { [action in PositionScriptAction]?: string } = {
swap: "交换位置",
move: "移动名次",
retire: "退赛",
restore: "回到比赛",
lap: "圈数",
};
// Prototype controls
export const cornerLabels: { [corner in Corner]?: string } = {
topLeft: "左上",
topRight: "右上",
bottomRight: "右下",
bottomLeft: "左下",
};
export const venetianModeLabels: { [mode: string]: string } = {
positionFlag: "名次牌",
driverPortrait: "车手头像",
};
+6 -2
View File
@@ -9,6 +9,7 @@ import "./clear.css";
import App from "./App";
import Broadcast from "./components/Broadcast/BroadcastRoute";
import Workspaces from "./components/Workspaces/WorkspacesRoute";
import { OutputRoute } from "./components/Output";
import { GlobalStyle, theme } from "./shared/theme";
import { GlobalFonts } from "./fonts";
@@ -24,11 +25,14 @@ ReactDOM.render(
<GlobalFonts />
<BrowserRouter>
<Routes>
{/* OBS 用的独立透明输出页,页面上没有任何控制界面。 */}
<Route path="output" element={<OutputRoute />} />
<Route path="broadcast-output" element={<OutputRoute />} />
<Route path="/" element={<App />}>
<Route index element={<IndexHeading>Home</IndexHeading>} />
<Route index element={<IndexHeading>首页</IndexHeading>} />
<Route path="broadcast" element={<Broadcast />} />
<Route path="workspaces/*" element={<Workspaces />} />
<Route path="*" element={<IndexHeading>Page Not Found</IndexHeading>} />
<Route path="*" element={<IndexHeading>页面不存在</IndexHeading>} />
</Route>
</Routes>
</BrowserRouter>
+21 -7
View File
@@ -1,14 +1,28 @@
import { createGlobalStyle, ThemeProps } from "styled-components/macro";
/**
* The Formula1 webfonts carry no Chinese glyphs, so every stack ends with a
* stack of CJK faces. Latin text keeps the broadcast look and Chinese text
* falls through to a face that can actually draw it.
*/
const cjkFallback = [
"\"PingFang SC\"",
"\"Hiragino Sans GB\"",
"\"Microsoft YaHei\"",
"\"Noto Sans CJK SC\"",
"\"Source Han Sans SC\"",
"sans-serif",
].join(", ");
export const theme = {
fonts: {
basic: "Helvetica, sans-serif",
f1: "Formula1, sans-serif",
f1Regular: "\"Formula1 Regular\", sans-serif",
f1Bold: "\"Formula1 Bold\", sans-serif",
f1Italic: "\"Formula1 Italic\", sans-serif",
f1Black: "\"Formula1 Black\", sans-serif",
f1Wide: "\"Formula1 Wide\", sans-serif",
basic: `-apple-system, "Segoe UI", Helvetica, ${cjkFallback}`,
f1: `Formula1, ${cjkFallback}`,
f1Regular: `"Formula1 Regular", ${cjkFallback}`,
f1Bold: `"Formula1 Bold", ${cjkFallback}`,
f1Italic: `"Formula1 Italic", ${cjkFallback}`,
f1Black: `"Formula1 Black", ${cjkFallback}`,
f1Wide: `"Formula1 Wide", ${cjkFallback}`,
},
colors: {
orange: "#f4ae40",
+102 -10
View File
@@ -1,19 +1,111 @@
import { configureStore, combineReducers } from "@reduxjs/toolkit";
import { configureStore, combineReducers, AnyAction } from "@reduxjs/toolkit";
import pageDimensions from "./features/pageDimensions/pageDimensionsSlice";
import workspace from "./features/workspace/workspaceSlice";
import overlayTool from "./features/overlayTool/overlayToolSlice";
import event from "./features/event/eventSlice";
import event, {
applyPositionScriptResult,
applyRoster,
setPositionScriptJson,
} from "./features/event/eventSlice";
import broadcastDirector from "./features/broadcast/director/broadcastDirectorSlice";
import broadcastGraphics from "./features/broadcast/graphics/broadcastGraphicsSlice";
import ui from "./features/ui/uiSlice";
import { applySnapshot } from "./features/outputChannel/outputChannelActions";
import { RootState } from "./types/state";
import {
loadStoredRoster,
loadStoredScript,
storeRoster,
storeScript,
} from "./features/event/rosterStorage";
import { driverToRosterEntry } from "./utils/roster";
import { parsePositionScriptSafe } from "./utils/positionScript";
const appReducer = combineReducers({
pageDimensions,
workspace,
overlayTool,
event,
broadcastDirector,
broadcastGraphics,
ui,
});
/**
* Allows a whole group of slices to be swapped in one go. Only the broadcast
* output page uses this: it receives the controller's slices over the WebSocket
* relay and mirrors them locally.
*/
const rootReducer = (state: RootState | undefined, action: AnyAction): RootState => {
if (applySnapshot.match(action)) {
return appReducer({ ...state, ...action.payload } as RootState, { type: "@@output/snapshot" });
}
return appReducer(state, action);
};
export const store = configureStore({
reducer: combineReducers({
pageDimensions,
workspace,
overlayTool,
event,
broadcastDirector,
broadcastGraphics,
}),
reducer: rootReducer,
});
export type AppDispatch = typeof store.dispatch;
/**
* The transparent output page is born with a default roster and only mirrors
* what the relay sends it, so it must never write over the roster the
* controller saved.
*/
const isOutputPage = /^\/(output|broadcast-output)(\/|$)/.test(window.location.pathname);
if (!isOutputPage) {
/**
* Keeps a hand edited driver roster around between reloads. The subscription
* compares the serialized roster, so the race simulation ticking along every
* 600ms never triggers a write.
*/
let lastRosterJson = "";
store.subscribe(() => {
const roster = store.getState().event.grid.map(car => driverToRosterEntry(car.driver));
const json = JSON.stringify(roster);
if (json === lastRosterJson) return;
lastRosterJson = json;
storeRoster(roster);
});
const storedRoster = loadStoredRoster();
if (storedRoster != null) {
store.dispatch(applyRoster(storedRoster));
lastRosterJson = JSON.stringify(
store.getState().event.grid.map(car => driverToRosterEntry(car.driver)),
);
}
/**
* The position script is the same deal: it is hand written JSON, so losing it
* on a refresh is the worst possible outcome. It is restored (and parsed)
* before React mounts, so the very first render already has the schedule and
* the starting order in place.
*/
let lastScriptJson = "";
store.subscribe(() => {
const json = store.getState().event.positionScript.json;
if (json === lastScriptJson) return;
lastScriptJson = json;
storeScript(json);
});
const storedScript = loadStoredScript();
if (storedScript != null) {
const { file, error } = parsePositionScriptSafe(storedScript);
store.dispatch(setPositionScriptJson(storedScript));
store.dispatch(applyPositionScriptResult({
events: file?.events ?? [],
initialOrder: file?.initialOrder ?? [],
autoStart: file?.autoStart ?? true,
error,
}));
}
lastScriptJson = store.getState().event.positionScript.json;
}
+87
View File
@@ -8,6 +8,19 @@ export interface RootState {
event: Event,
broadcastDirector: BroadcastDirector;
broadcastGraphics: BroadcastGraphics;
ui: UI;
}
// User Interface (panels, overlays and transient feedback)
export interface UI {
driverEditorOpen: boolean;
shortcutHelpOpen: boolean;
positionScriptOpen: boolean;
toast: Optional<ToastMessage>;
}
export interface ToastMessage {
id: number;
text: string;
}
// Page Dimensions
@@ -79,13 +92,69 @@ export interface Event {
grid: Grid;
sortedGridSpots: GridSpot[];
lastUpdate: number;
/** Time elapsed since the timing graphics first appeared on screen. */
showClock: ShowClock;
/** A JSON authored schedule of running order changes. */
positionScript: PositionScript;
}
export interface EventProgress {
startTime: Milliseconds;
timeLimit: Milliseconds;
lapCount: number;
/**
* Laps added by hand on top of the lap the simulation derives from the
* leader's distance, so the director can push the counter forward (or back)
* without disturbing the race itself.
*/
lapAdjust: number;
scheduledLaps: number;
}
/**
* The stopwatch that runs alongside the LAP counter. Its zero is the moment the
* timing board appeared, which is also what the position script is timed
* against.
*/
export interface ShowClock {
/** Timestamp the clock was last started, or null while it is paused. */
startedAt: Optional<number>;
/** Milliseconds banked by the runs that came before. */
accumulatedMs: Milliseconds;
/** True once the clock has run at least once. */
hasStarted: boolean;
}
export type PositionScriptAction = "swap" | "move" | "retire" | "restore" | "lap";
export interface PositionScriptEvent {
/** Milliseconds after the clock's zero. */
at: Milliseconds;
action: PositionScriptAction;
/**
* Driver references. A reference may be a driver id ("verstappen"), a three
* letter code ("VER") or a car number ("33").
*/
drivers: string[];
/** Target position (1 based) for "move". */
to?: number;
/** Lap delta for "lap". */
value?: number;
}
export interface PositionScript {
/** Exactly what the user is editing, kept as text. */
json: string;
/** The last schedule that parsed, sorted by time. */
events: PositionScriptEvent[];
/** Drivers placed at the start of a run, in running order. */
initialOrder: string[];
autoStart: boolean;
error: Optional<string>;
/** Why the `order` list could not be put on track, if it could not. */
orderError: Optional<string>;
/** How many events of the current run have already fired. */
firedCount: number;
}
export enum EventStatus {
Waiting, // Event is waiting to start.
Running, // Event is running.
@@ -148,6 +217,12 @@ export interface Driver {
initials: string;
nationality: string; // ISO 3166-1 alpha-3 codes
performance: Fraction; // Versus teammate
/**
* Optional portrait override. Portraits are picked from the images bundled in
* public/images/drivers/front. When omitted the driver's own id is used, so
* any driver that never gets edited keeps behaving exactly as before.
*/
portrait?: string;
}
export type DriverId =
| "albon"
@@ -257,6 +332,18 @@ export type TeamFullName =
// Broadcast Director
export interface BroadcastDirector {
selectedCars: GridSpot[];
/** The car the keyboard cursor is parked on. Never changes on its own. */
cursorGridSpot: Optional<GridSpot>;
/** Everything the chyron director controls need to build a chyron. */
chyronSettings: ChyronSettings;
}
export interface ChyronSettings {
mode: BGChyronMode;
subMode: BGChyronSubMode;
flagMode: FlagMode;
showPosFlag: boolean;
showDriverNumber: boolean;
showPortrait: boolean;
}
// Broadcast Graphics
+9 -3
View File
@@ -7,8 +7,14 @@ import { DriverId, TeamId } from "../types/state";
* Why? Because we cannot use type literals (such as TeamId) as keys in an
* object in TypeScript. This allows me to enforce some type checking in a
* situation I wouldn't be able to normally
*
* Everything here is defensive about unknown ids: the driver editor lets the
* user rewire teams and drivers at runtime, so a stale id must never be able
* to take the broadcast down.
*/
const firstKey = <T>(table: { [id: string]: T }): T => table[Object.keys(table)[0]];
export function getDriver(driverId: DriverId) {
return drivers[driverId];
}
@@ -24,11 +30,11 @@ export function cloneTeam(teamId: TeamId) {
}
export function getTeamNumberStyle(teamId: TeamId) {
return teamNumberStyles[teamId];
return teamNumberStyles[teamId] ?? firstKey(teamNumberStyles);
}
export function getTeamFlagStyle(teamId: TeamId) {
return teamFlagStyles[teamId];
return teamFlagStyles[teamId] ?? firstKey(teamFlagStyles);
}
export function getTeamGemStyle(teamId: TeamId) {
return teamGemStyles[teamId];
return teamGemStyles[teamId] ?? firstKey(teamGemStyles);
}
+256
View File
@@ -0,0 +1,256 @@
import { Optional } from "../types/util";
import {
Grid,
GridSpot,
PositionScriptAction,
PositionScriptEvent,
} from "../types/state";
/**
* The position script is a small, JSON authored schedule of running order
* changes. Its zero is the show clock - the moment the timing graphics appeared
* on screen - so a script can be written as "five seconds in, VER and HAM swap
* places" and it will play out the same way on every run.
*
* The format is deliberately forgiving: times may be milliseconds or
* "mm:ss.mmm", and a driver may be named by id, by three letter code or by car
* number.
*/
export interface PositionScriptFile {
autoStart: boolean;
/** Starting running order, applied whenever the clock is reset to zero. */
initialOrder: string[];
events: PositionScriptEvent[];
}
export const POSITION_SCRIPT_ACTIONS: PositionScriptAction[] = [
"swap",
"move",
"retire",
"restore",
"lap",
];
export const DEFAULT_POSITION_SCRIPT: PositionScriptFile = {
autoStart: true,
initialOrder: [
"VER", "HAM", "BOT", "PER", "SAI", "NOR", "LEC", "RIC", "GAS", "ALO",
"OCO", "VET", "STR", "TSU", "RUS", "RAI", "LAT", "GIO", "MSC", "MAZ",
],
events: [
{ at: 5000, action: "swap", drivers: ["HAM", "VER"] },
{ at: 12000, action: "move", drivers: ["LEC"], to: 3 },
{ at: 18500, action: "lap", drivers: [], value: 1 },
{ at: 24000, action: "retire", drivers: ["MAZ"] },
{ at: 31000, action: "restore", drivers: ["MAZ"] },
],
};
export const DEFAULT_POSITION_SCRIPT_JSON = serializePositionScript(DEFAULT_POSITION_SCRIPT);
/** "mm:ss.mmm" for anything the clock or a script line shows. */
export function formatShowClock(milliseconds: number): string {
const safe = Math.max(0, milliseconds);
const totalSeconds = Math.floor(safe / 1000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
const millis = Math.floor(safe % 1000);
return `${String(minutes).padStart(2, "0")}:`
+ `${String(seconds).padStart(2, "0")}.`
+ String(millis).padStart(3, "0");
}
/** Accepts milliseconds, "ss.mmm" or "mm:ss.mmm". */
export function parseScriptTime(value: unknown): number {
if (typeof value === "number" && Number.isFinite(value)) {
return Math.max(0, value);
}
if (typeof value === "string") {
const parts = value.trim().split(":");
if (parts.length === 1) {
const seconds = Number(parts[0]);
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);
} else if (parts.length === 2) {
const minutes = Number(parts[0]);
const seconds = Number(parts[1]);
if (Number.isFinite(minutes) && Number.isFinite(seconds)) {
return Math.max(0, (minutes * 60 + seconds) * 1000);
}
}
}
const error = new Error(
`"at" 必须是毫秒数或 "mm:ss.mmm"(当前是 ${JSON.stringify(value)})`,
);
error.name = "PositionScriptError";
throw error;
}
/** Reads either the "driver" or the "drivers" form. "lap" needs neither. */
function readDrivers(raw: Record<string, unknown>): string[] {
const single = raw.driver;
const many = raw.drivers;
if (Array.isArray(many)) {
return many
.filter(value => value != null && typeof value !== "object")
.map(value => String(value).trim())
.filter(value => value !== "");
}
if (many != null && typeof many !== "object") {
return [String(many).trim()];
}
if (single != null && typeof single !== "object") {
return [String(single).trim()];
}
return [];
}
export function parsePositionScript(json: string): PositionScriptFile {
let raw: unknown;
try {
raw = JSON.parse(json);
} catch (error) {
throw new Error(`不是合法的 JSON:${(error as Error).message}`);
}
if (raw == null || typeof raw !== "object" || Array.isArray(raw)) {
throw new Error("脚本必须是一个 JSON 对象");
}
const source = raw as Record<string, unknown>;
const rawEvents = source.events;
if (rawEvents != null && !Array.isArray(rawEvents)) {
throw new Error("\"events\" 必须是数组");
}
const events: PositionScriptEvent[] = (rawEvents ?? []).map((entry, index) => {
if (entry == null || typeof entry !== "object" || Array.isArray(entry)) {
throw new Error(`events[${index}] 必须是对象`);
}
const item = entry as Record<string, unknown>;
const action = String(item.action ?? "").toLowerCase() as PositionScriptAction;
if (!POSITION_SCRIPT_ACTIONS.includes(action)) {
throw new Error(
`events[${index}].action 必须是 ${POSITION_SCRIPT_ACTIONS.join("、")} 之一`,
);
}
const drivers = readDrivers(item);
if (action === "swap" && drivers.length < 2) {
throw new Error(`events[${index}]:"swap" 需要两位车手`);
}
if (action === "move" && drivers.length < 1) {
throw new Error(`events[${index}]:"move" 需要指定车手`);
}
if (action === "move" && !Number.isFinite(Number(item.to))) {
throw new Error(`events[${index}]:"move" 的 "to" 必须是数字名次`);
}
if ((action === "retire" || action === "restore") && drivers.length < 1) {
throw new Error(`events[${index}]:"${action}" 需要指定车手`);
}
return {
at: parseScriptTime(item.at),
action,
drivers,
to: action === "move" ? Math.max(1, Math.round(Number(item.to))) : undefined,
value: action === "lap"
? (Number.isFinite(Number(item.value)) ? Math.round(Number(item.value)) : 1)
: undefined,
};
});
// The schedule runs in time order, which is also what lets a single counter
// track how far through the run we are.
events.sort((a, b) => a.at - b.at);
const rawOrder = source.order;
const initialOrder = Array.isArray(rawOrder)
? rawOrder.map(value => String(value).trim()).filter(value => value !== "")
: [];
return {
autoStart: source.autoStart == null ? true : Boolean(source.autoStart),
initialOrder,
events,
};
}
/**
* Parsing never throws here. A half typed script simply reports its error and
* the last good schedule keeps running.
*/
export function parsePositionScriptSafe(json: string): {
file: Optional<PositionScriptFile>,
error: Optional<string>,
} {
try {
return { file: parsePositionScript(json), error: null };
} catch (error) {
return { file: null, error: (error as Error).message };
}
}
export function serializePositionScript(file: PositionScriptFile): string {
const payload: Record<string, unknown> = { autoStart: file.autoStart };
if (file.initialOrder.length > 0) payload.order = file.initialOrder;
payload.events = file.events.map(event => {
const line: Record<string, unknown> = {
at: formatShowClock(event.at),
action: event.action,
};
if (event.drivers.length === 1) line.driver = event.drivers[0];
if (event.drivers.length > 1) line.drivers = event.drivers;
if (event.action === "move") line.to = event.to;
if (event.action === "lap") line.value = event.value ?? 1;
return line;
});
return JSON.stringify(payload, null, 2);
}
/**
* Resolves a driver reference against the current grid. Tried in order: driver
* id, three letter code, last name, car number - so a script keeps working
* whether it was written with names or with codes.
*/
export function findGridSpotByRef(grid: Grid, ref: string | number): GridSpot | null {
const text = String(ref).trim();
if (text === "") return null;
const lower = text.toLowerCase();
let index = grid.findIndex(car => car.driver.id.toLowerCase() === lower);
if (index !== -1) return index;
index = grid.findIndex(car => car.driver.initials.toUpperCase() === text.toUpperCase());
if (index !== -1) return index;
index = grid.findIndex(car => car.driver.lastName.toLowerCase() === lower);
if (index !== -1) return index;
if (/^\d+$/.test(text)) {
const number = Number(text);
index = grid.findIndex(car => car.driver.number === number);
if (index !== -1) return index;
}
return null;
}
/** Human readable summary of one script line, for the schedule list. */
export function describeScriptEvent(event: PositionScriptEvent): string {
switch (event.action) {
case "swap":
return `${event.drivers[0]} 与 ${event.drivers[1]} 交换位置`;
case "move":
return `${event.drivers[0]} 上升到第 ${event.to} 位`;
case "retire":
return `${event.drivers[0]} 退赛`;
case "restore":
return `${event.drivers[0]} 回到比赛`;
case "lap":
return `圈数 ${(event.value ?? 1) > 0 ? "+" : ""}${event.value ?? 1}`;
default:
return event.action;
}
}
+134
View File
@@ -0,0 +1,134 @@
import { Driver, DriverId, Team, TeamId } from "../types/state";
import { Fraction } from "../types/style";
import { driverPortraitNames, countryFlagCodes } from "../domain/data/assets";
import { getDriver, getTeam } from "./dataLookup";
/**
* A roster entry is the small, serializable description of a driver. The full
* Driver record carries a whole Team object around, which we never want to
* persist or hand-edit - a roster entry only keeps the team id and the editor
* rebuilds the Team reference from the data tables.
*/
export interface DriverRosterEntry {
id: DriverId;
firstName: string;
lastName: string;
initials: string;
number: number;
nationality: string;
teamId: TeamId;
yellowTCam: boolean;
performance: Fraction;
portrait?: string;
}
export const MIN_DRIVER_NUMBER = 0;
export const MAX_DRIVER_NUMBER = 999;
export const MIN_PERFORMANCE = 0.5;
export const MAX_PERFORMANCE = 1.5;
export function clampDriverNumber(value: number): number {
if (!Number.isFinite(value)) return MIN_DRIVER_NUMBER;
return Math.min(MAX_DRIVER_NUMBER, Math.max(MIN_DRIVER_NUMBER, Math.round(value)));
}
export function clampPerformance(value: number): Fraction {
if (!Number.isFinite(value)) return 1;
return Math.min(MAX_PERFORMANCE, Math.max(MIN_PERFORMANCE, value));
}
/** F1 style three letter code: first three letters of the last name. */
export function deriveInitials(firstName: string, lastName: string): string {
const source = lastName.trim() || firstName.trim();
return source.replace(/[^a-zA-Z]/g, "").slice(0, 3).toUpperCase();
}
export function sanitizeDriverId(value: unknown, fallback: DriverId): DriverId {
return typeof value === "string" && getDriver(value as DriverId) != null
? value as DriverId
: fallback;
}
export function sanitizeTeamId(value: unknown, fallback: TeamId): TeamId {
return typeof value === "string" && (value as TeamId) in TEAM_IDS
? value as TeamId
: fallback;
}
const TEAM_IDS: Record<string, true> = {
alfaRomeo: true,
alphaTauri: true,
alpine: true,
astonMartin: true,
ferrari: true,
haas: true,
mclaren: true,
mercedes: true,
redBull: true,
williams: true,
};
export function sanitizeNationality(value: unknown, fallback: string): string {
return typeof value === "string" && countryFlagCodes.includes(value.toUpperCase())
? value.toUpperCase()
: fallback;
}
export function sanitizePortrait(value: unknown): string | undefined {
return typeof value === "string" && driverPortraitNames.includes(value)
? value
: undefined;
}
export function driverToRosterEntry(driver: Driver): DriverRosterEntry {
return {
id: driver.id,
firstName: driver.firstName,
lastName: driver.lastName,
initials: driver.initials,
number: driver.number,
nationality: driver.nationality,
teamId: driver.team.id,
yellowTCam: driver.yellowTCam,
performance: driver.performance,
portrait: driver.portrait,
};
}
/**
* Rebuilds a Driver from untrusted input (a hand edited entry, an imported
* file or a value restored from localStorage). Anything that does not check
* out falls back to `fallback`, which is normally the driver that already sits
* in that grid slot.
*/
export function rosterEntryToDriver(
entry: Partial<DriverRosterEntry> | null | undefined,
fallback: Driver,
): Driver {
if (entry == null) return fallback;
const teamId = sanitizeTeamId(entry.teamId, fallback.team.id);
const team: Team = getTeam(teamId) ?? fallback.team;
const firstName = typeof entry.firstName === "string" ? entry.firstName : fallback.firstName;
const lastName = typeof entry.lastName === "string" ? entry.lastName : fallback.lastName;
return {
id: sanitizeDriverId(entry.id, fallback.id),
firstName,
lastName,
initials: typeof entry.initials === "string" && entry.initials.trim() !== ""
? entry.initials.trim().toUpperCase().slice(0, 4)
: deriveInitials(firstName, lastName),
number: clampDriverNumber(
typeof entry.number === "number" ? entry.number : fallback.number,
),
nationality: sanitizeNationality(entry.nationality, fallback.nationality),
team,
yellowTCam: typeof entry.yellowTCam === "boolean" ? entry.yellowTCam : fallback.yellowTCam,
performance: clampPerformance(
typeof entry.performance === "number" ? entry.performance : fallback.performance,
),
portrait: sanitizePortrait(entry.portrait),
};
}
+42
View File
@@ -0,0 +1,42 @@
@echo off
chcp 65001 >nul
title F1 世界转播模拟器 - 开发服务器
cd /d "%~dp0"
echo ==================================================
echo F1 世界转播模拟器 开发服务器
echo ==================================================
echo.
where node >nul 2>nul
if errorlevel 1 (
echo [错误] 没有找到 Node.js。
echo 请先安装 Node 16 或更高版本,再运行本脚本。
echo.
pause
exit /b 1
)
if not exist "node_modules" (
echo 检测到这是第一次运行,正在安装依赖,可能需要几分钟...
echo.
call npm install
if errorlevel 1 (
echo.
echo [错误] 依赖安装失败。
pause
exit /b 1
)
)
echo 正在启动开发服务器,编译完成后浏览器会自动打开。
echo 地址:http://localhost:3000
echo.
echo 关闭这个窗口即可停止服务器。
echo.
call npm start
echo.
echo 服务器已停止。
pause