diff --git a/.gitignore b/.gitignore index 4d29575..59cd9f0 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/README.md b/README.md index 64c1b4a..cb501c3 100644 --- a/README.md +++ b/README.md @@ -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`)页, +进去以后按 ? 就能看到全部快捷键。 + # 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 diff --git a/package.json b/package.json index cbbe916..2ed6875 100644 --- a/package.json +++ b/package.json @@ -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" diff --git a/server/relayServer.js b/server/relayServer.js new file mode 100644 index 0000000..58786c3 --- /dev/null +++ b/server/relayServer.js @@ -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://:/?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://:" + PORT + "/?role=controller|output\n" + + "health: http://:" + 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)"); +}); diff --git a/src/App.tsx b/src/App.tsx index d35ba53..24428f7 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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() { + + ); } diff --git a/src/components/Broadcast/BroadcastDirectorUI/Chyrons/ChyronsDirectorControls.tsx b/src/components/Broadcast/BroadcastDirectorUI/Chyrons/ChyronsDirectorControls.tsx index 3288e6e..d894800 100644 --- a/src/components/Broadcast/BroadcastDirectorUI/Chyrons/ChyronsDirectorControls.tsx +++ b/src/components/Broadcast/BroadcastDirectorUI/Chyrons/ChyronsDirectorControls.tsx @@ -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>(getChyronModesList()); const [chyronSubModes, setChyronSubModes] = useState>([]); - // Interface states. - const [chyronMode, setChyronMode] = useState("driver"); - const [chyronSubMode, setChyronSubMode] = useState("medium"); - const [posFlag, setPosFlag] = useState(true); - const [driverNum, setDriverNum] = useState(true); - const [portrait, setPortrait] = useState(false); - const [flagMode, setFlagMode] = useState("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 ( dispatch(updateChyronSettings({ showPosFlag: value }))} /> dispatch(updateChyronSettings({ showDriverNumber: value }))} /> {subMode === "medium" && ( dispatch(updateChyronSettings({ showPortrait: value }))} /> )} 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" /> ); @@ -130,39 +112,87 @@ export function ChyronsDirectorControls() { return ( - Chyrons + 车名字幕 setChyronMode(chyronModes[index])} + value={modeIndex} + formatter={value => labelOf(chyronModeLabels, value)} + onChange={index => dispatch(updateChyronSettings({ + mode: chyronModes[index], + }))} /> setChyronSubMode(chyronSubModes[index])} + value={subModeIndex} + formatter={value => labelOf(chyronSubModeLabels, value)} + onChange={index => dispatch(updateChyronSettings({ + subMode: chyronSubModes[index], + }))} /> chyron.open()} + disabled={!chyron.canOpen} + title="显示字幕(Enter)" > + dispatch(toggleDriverEditor())} + disabled={false} + title="车手名单编辑器(E)" + style={driverEditorOpen ? { backgroundColor: "#f4ae40" } : undefined} + > + + + dispatch(togglePositionScript())} + disabled={false} + title="JSON 名次脚本(J)" + style={positionScriptOpen ? { backgroundColor: "#f4ae40" } : undefined} + > + + + dispatch(toggleShortcutHelp())} + disabled={false} + title="全部快捷键(?)" + style={shortcutHelpOpen ? { backgroundColor: "#f4ae40" } : undefined} + > + + {modeControls(chyronMode, chyronSubMode)} + + 1…0按名次选车 + ↑↓移动光标 + 空格加第二名车手 + 回车出字幕 + Esc收起 + S开始 / 停止 + + / -圈数 + C计时器 + E车手名单 + J名次脚本 + ?全部快捷键 + ); } diff --git a/src/components/Broadcast/BroadcastDirectorUI/Chyrons/styles.ts b/src/components/Broadcast/BroadcastDirectorUI/Chyrons/styles.ts index eb0c5d3..5e75e85 100644 --- a/src/components/Broadcast/BroadcastDirectorUI/Chyrons/styles.ts +++ b/src/components/Broadcast/BroadcastDirectorUI/Chyrons/styles.ts @@ -35,3 +35,33 @@ export const CloseButton = styled(Button)` background-color: ${({ disabled }) => disabled ? p => p.theme.colors.disabledRed : p => p.theme.colors.activeRed}; `; + +export const PanelButton = styled(Button)` + 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; +`; diff --git a/src/components/Broadcast/DriverEditor/DriverEditor.tsx b/src/components/Broadcast/DriverEditor/DriverEditor.tsx new file mode 100644 index 0000000..1b2ea98 --- /dev/null +++ b/src/components/Broadcast/DriverEditor/DriverEditor.tsx @@ -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(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 ( + + event.stopPropagation()}> +
+ 车手名单 + + 改动即时生效。名单保存在本浏览器里,用「导出 JSON」就能把整套阵容搬到别的机器。 + 按 Esc 关闭。 + + + 导出 JSON + fileInputRef.current?.click()}> + 导入 JSON + + { + dispatch(resetRoster()); + dispatch(pushToast("名单已恢复为内置的 2021 赛季阵容")); + }} + > + 全部重置 + + ✕ + + { + onImportFile(event.target.files?.[0]); + event.target.value = ""; + }} + /> +
+ + + + + + + + + + + + + + + + + + {grid.map((car, gridSpot) => ( + + ))} + +
顺位头像名姓缩写车号国籍车队性能黄 T 摄 +
+
+
+
+ ); +} diff --git a/src/components/Broadcast/DriverEditor/DriverRow.tsx b/src/components/Broadcast/DriverEditor/DriverRow.tsx new file mode 100644 index 0000000..b16a836 --- /dev/null +++ b/src/components/Broadcast/DriverEditor/DriverRow.tsx @@ -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 ( + + + {gridSpot + 1} + P{car.position} + + + + {portraitSrc != null + ? + : 无头像} + + + + + + + + + + + + + dispatch(updateDriver({ + gridSpot, + field: "initials", + value: deriveInitials(driver.firstName, driver.lastName), + }))} + > + ↻ + + + + + + + + + + + dispatch(setDriverTeam({ + gridSpot, + teamId: value as TeamId, + }))} + title="决定车队配色、队徽和车队旗帜" + /> + + + + + + + dispatch(updateDriver({ + gridSpot, + field: "yellowTCam", + value: event.target.checked, + }))} + /> + + + + + dispatch(swapDrivers({ a: gridSpot, b: gridSpot - 1 }))} + > + ▲ + + dispatch(swapDrivers({ a: gridSpot, b: gridSpot + 1 }))} + > + ▼ + + dispatch(resetDriver(gridSpot))} + > + ↺ + + + + + ); +} diff --git a/src/components/Broadcast/DriverEditor/index.ts b/src/components/Broadcast/DriverEditor/index.ts new file mode 100644 index 0000000..8759007 --- /dev/null +++ b/src/components/Broadcast/DriverEditor/index.ts @@ -0,0 +1 @@ +export { DriverEditor } from "./DriverEditor"; diff --git a/src/components/Broadcast/DriverEditor/styles.ts b/src/components/Broadcast/DriverEditor/styles.ts new file mode 100644 index 0000000..4c64d26 --- /dev/null +++ b/src/components/Broadcast/DriverEditor/styles.ts @@ -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; +`; diff --git a/src/components/Broadcast/Layout/Layout.tsx b/src/components/Broadcast/Layout/Layout.tsx index 0e333c8..3d310f3 100644 --- a/src/components/Broadcast/Layout/Layout.tsx +++ b/src/components/Broadcast/Layout/Layout.tsx @@ -18,7 +18,7 @@ export function Layout({ headerHeight }: LayoutProps) { Timing Board UI + >计时榜 UI @@ -28,7 +28,7 @@ export function Layout({ headerHeight }: LayoutProps) { Race Status UI + >比赛状态 UI diff --git a/src/components/Broadcast/PositionScriptEditor/PositionScriptEditor.tsx b/src/components/Broadcast/PositionScriptEditor/PositionScriptEditor.tsx new file mode 100644 index 0000000..20e6bbd --- /dev/null +++ b/src/components/Broadcast/PositionScriptEditor/PositionScriptEditor.tsx @@ -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 ( + dispatch(setPositionScriptOpen(false))}> + event.stopPropagation()}> +
+ 名次脚本 + + 零点就是计时榜出现的瞬间。改脚本会让计时器归零、从头重放, + order 也会立刻铺回赛道。脚本保存在本浏览器里,刷新不会丢。 + + + dispatch(setPositionScriptJson( + serializePositionScript({ + autoStart: positionScript.autoStart, + initialOrder: positionScript.initialOrder, + events, + }), + ))} + > + 格式化 + + dispatch(setPositionScriptJson(DEFAULT_POSITION_SCRIPT_JSON))} + > + 载入示例 + + { + dispatch(resetShowClock()); + dispatch(setPositionScriptOpen(false)); + }} + > + 归零重播 + + dispatch(setPositionScriptOpen(false))} + > + ✕ + + +
+ + + + 脚本(JSON) + dispatch(setPositionScriptJson(event.target.value))} + /> + + {error != null + ? `脚本有误:${error}` + : orderError != null + ? `order 没生效:${orderError}` + : `${events.length} 条事件已就绪 · 自动开始 ${positionScript.autoStart ? "开" : "关"} · 起始顺序 ${positionScript.initialOrder.length} 位`} + + + at 是从零点算起的毫秒数,或 "mm:ss.mmm"。{" "} + action 可选 swap(交换位置)、move(移动到某名次)、{" "} + retire(退赛)、restore(回到比赛)、lap(增减圈数)。 + 车手可以写 id(verstappen)、三字码(VER)、姓(Verstappen) + 或车号(33)。{" "} + order 必须按顺序列出整个车阵,写错会在上面的状态条里说明原因。 + 改脚本会让计时器归零并从头播放。 + + + + + 计时器 + + {formatShowClock(elapsedMs)} + {running ? "运行中" : "已暂停"} + dispatch(running ? pauseShowClock() : startShowClock())} + > + {running ? "暂停" : "启动"} + + dispatch(resetShowClock())} + > + 归零 + + + 圈数 {eventProgress.lapCount} + {" / "} + {eventProgress.scheduledLaps} + {eventProgress.lapAdjust !== 0 + ? ` (${eventProgress.lapAdjust > 0 ? "+" : ""}${eventProgress.lapAdjust})` + : ""} + + dispatch(adjustLap(-1))} + > + 圈数 −1 + + dispatch(adjustLap(1))} + > + 圈数 +1 + + + + 时间轴 + + {events.length === 0 && ( + 还没有事件,在左侧 JSON 里加一条吧。 + )} + {events.map((event, index) => { + const done = index < firedCount; + const state = done ? "done" : (event.at <= elapsedMs ? "due" : "waiting"); + return ( + + {formatShowClock(event.at)} + {describeScriptEvent(event)} + {done && 已完成} + + ); + })} + + + +
+
+ ); +} diff --git a/src/components/Broadcast/PositionScriptEditor/index.ts b/src/components/Broadcast/PositionScriptEditor/index.ts new file mode 100644 index 0000000..d14b1cf --- /dev/null +++ b/src/components/Broadcast/PositionScriptEditor/index.ts @@ -0,0 +1 @@ +export { PositionScriptEditor } from "./PositionScriptEditor"; diff --git a/src/components/Broadcast/PositionScriptEditor/styles.ts b/src/components/Broadcast/PositionScriptEditor/styles.ts new file mode 100644 index 0000000..bbd95b2 --- /dev/null +++ b/src/components/Broadcast/PositionScriptEditor/styles.ts @@ -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` + 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` + 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` + 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; + } +`; diff --git a/src/components/Broadcast/RaceDirectorUI/EventLoop/RaceDirectorControls/RaceDirectorControls.tsx b/src/components/Broadcast/RaceDirectorUI/EventLoop/RaceDirectorControls/RaceDirectorControls.tsx index 10686f4..c538bbf 100644 --- a/src/components/Broadcast/RaceDirectorUI/EventLoop/RaceDirectorControls/RaceDirectorControls.tsx +++ b/src/components/Broadcast/RaceDirectorUI/EventLoop/RaceDirectorControls/RaceDirectorControls.tsx @@ -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 ( - { - if (eventStatus !== EventStatus.Running) { - dispatch(setEventStatus(EventStatus.Running)); - } else { - dispatch(setEventStatus(EventStatus.Stopped)); - } - }}> - EventStatus = {EventStatus[eventStatus]} - + + { + if (eventStatus !== EventStatus.Running) { + dispatch(setEventStatus(EventStatus.Running)); + } else { + dispatch(setEventStatus(EventStatus.Stopped)); + } + }} + > + 比赛状态:{labelOf(eventStatusLabels, eventStatus)} [S] + + + dispatch(adjustLap(1))} + > + 圈数 {eventProgress.lapCount}/{eventProgress.scheduledLaps} +1 [+] + + + dispatch(adjustLap(-1))} + > + 圈数 -1 [-] + + + dispatch(clockRunning ? pauseShowClock() : startShowClock())} + > + 计时器 {clockRunning ? "暂停" : "启动"} [C] + + + dispatch(resetShowClock())} + > + 计时器归零 [⇧C] + + ); } diff --git a/src/components/Broadcast/ShortcutHelp/ShortcutHelp.tsx b/src/components/Broadcast/ShortcutHelp/ShortcutHelp.tsx new file mode 100644 index 0000000..454c08a --- /dev/null +++ b/src/components/Broadcast/ShortcutHelp/ShortcutHelp.tsx @@ -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 ( + dispatch(setShortcutHelpOpen(false))}> + event.stopPropagation()}> + 键盘控制 + + 所有页面都能用。在输入框里打字时快捷键不会触发,每次按键屏幕底部都会给出 + 一行提示,Esc 则关闭当前打开的面板。 + + + {SHORTCUT_GROUPS.map(group => ( + + {group.title} + {group.shortcuts.map(shortcut => ( + + {shortcut.keys} + {shortcut.description} + + ))} + + ))} + + + + ); +} diff --git a/src/components/Broadcast/ShortcutHelp/index.ts b/src/components/Broadcast/ShortcutHelp/index.ts new file mode 100644 index 0000000..ff91c3a --- /dev/null +++ b/src/components/Broadcast/ShortcutHelp/index.ts @@ -0,0 +1 @@ +export { ShortcutHelp } from "./ShortcutHelp"; diff --git a/src/components/Broadcast/ShortcutHelp/styles.ts b/src/components/Broadcast/ShortcutHelp/styles.ts new file mode 100644 index 0000000..fd8578d --- /dev/null +++ b/src/components/Broadcast/ShortcutHelp/styles.ts @@ -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}; +`; diff --git a/src/components/Broadcast/VideoFeed/VideoFeed.tsx b/src/components/Broadcast/VideoFeed/VideoFeed.tsx index c8fd11c..ac24ba6 100644 --- a/src/components/Broadcast/VideoFeed/VideoFeed.tsx +++ b/src/components/Broadcast/VideoFeed/VideoFeed.tsx @@ -31,9 +31,9 @@ export default function VideoFeed() { return ( - Frame: {Math.floor(frameWidth)} x {Math.floor(frameHeight)}px + 画面 {Math.floor(frameWidth)} × {Math.floor(frameHeight)} px
- Scaled: {Math.floor(layoutWidth)} x {Math.floor(layoutHeight)}px ({(layoutScale * 100).toFixed(1)}%) + 缩放 {Math.floor(layoutWidth)} × {Math.floor(layoutHeight)} px({(layoutScale * 100).toFixed(1)}%)
diff --git a/src/components/BroadcastControlLayer/BroadcastControlLayer.tsx b/src/components/BroadcastControlLayer/BroadcastControlLayer.tsx new file mode 100644 index 0000000..fcfbbd4 --- /dev/null +++ b/src/components/BroadcastControlLayer/BroadcastControlLayer.tsx @@ -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 ( + <> + + + + + + ); +} diff --git a/src/components/BroadcastControlLayer/index.ts b/src/components/BroadcastControlLayer/index.ts new file mode 100644 index 0000000..85eb01f --- /dev/null +++ b/src/components/BroadcastControlLayer/index.ts @@ -0,0 +1 @@ +export { BroadcastControlLayer } from "./BroadcastControlLayer"; diff --git a/src/components/BroadcastGraphics/Chyrons/Driver/ChyronDriver.tsx b/src/components/BroadcastGraphics/Chyrons/Driver/ChyronDriver.tsx index fda3df7..7f1309c 100644 --- a/src/components/BroadcastGraphics/Chyrons/Driver/ChyronDriver.tsx +++ b/src/components/BroadcastGraphics/Chyrons/Driver/ChyronDriver.tsx @@ -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 ( diff --git a/src/components/BroadcastGraphics/Common/AngledFlag/AngledFlag.tsx b/src/components/BroadcastGraphics/Common/AngledFlag/AngledFlag.tsx index fe062e2..af360ec 100644 --- a/src/components/BroadcastGraphics/Common/AngledFlag/AngledFlag.tsx +++ b/src/components/BroadcastGraphics/Common/AngledFlag/AngledFlag.tsx @@ -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 = ( - - + + + ); + bottomFlag = ( + - - ); - bottomFlag = ( - - ); + ); + } } else if (flagProps.flagMode === "team") { - topFlag = ( - - + + + ); + bottomFlag = ( + - - ); - bottomFlag = ( - - ); + ); + } } const flagModeWidth = flagProps.flagMode === "team" ? FLAG_WIDTH_TEAM : FLAG_WIDTH_COUNTRY; diff --git a/src/components/BroadcastGraphics/Common/DriverPortrait/DriverPortrait.tsx b/src/components/BroadcastGraphics/Common/DriverPortrait/DriverPortrait.tsx index ac235fe..da561dd 100644 --- a/src/components/BroadcastGraphics/Common/DriverPortrait/DriverPortrait.tsx +++ b/src/components/BroadcastGraphics/Common/DriverPortrait/DriverPortrait.tsx @@ -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 ( diff --git a/src/components/BroadcastGraphics/Common/TeamGem/TeamGem.tsx b/src/components/BroadcastGraphics/Common/TeamGem/TeamGem.tsx index c567b1a..0bc9af8 100644 --- a/src/components/BroadcastGraphics/Common/TeamGem/TeamGem.tsx +++ b/src/components/BroadcastGraphics/Common/TeamGem/TeamGem.tsx @@ -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 ( - + {logoSrc != null && ( + + )} ); } diff --git a/src/components/BroadcastGraphics/Common/VenetianBlindsTransition/VenetianBlindsTransition.tsx b/src/components/BroadcastGraphics/Common/VenetianBlindsTransition/VenetianBlindsTransition.tsx index 1acfae1..0536700 100644 --- a/src/components/BroadcastGraphics/Common/VenetianBlindsTransition/VenetianBlindsTransition.tsx +++ b/src/components/BroadcastGraphics/Common/VenetianBlindsTransition/VenetianBlindsTransition.tsx @@ -44,11 +44,11 @@ export function VenetianBlindsTransition( children, }: React.PropsWithChildren, ) { - const blindsSpring = useSpring({ + const [blindsSpring] = useSpring({ opacity: visible ? 1 : 0, config: { duration: blindsOpenDuration }, delay: blindsOpenDelay + delay, - }); + }, [visible, blindsOpenDuration, blindsOpenDelay, delay]); return ( )} + ); diff --git a/src/components/BroadcastGraphics/TimingBoard/StatusIndicator/TimingClock.tsx b/src/components/BroadcastGraphics/TimingBoard/StatusIndicator/TimingClock.tsx new file mode 100644 index 0000000..0d3cdaa --- /dev/null +++ b/src/components/BroadcastGraphics/TimingBoard/StatusIndicator/TimingClock.tsx @@ -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 ( + + {formatShowClock(elapsed)} + + ); +} diff --git a/src/components/BroadcastGraphics/TimingBoard/StatusIndicator/styles.ts b/src/components/BroadcastGraphics/TimingBoard/StatusIndicator/styles.ts index 1da5712..ede3f92 100644 --- a/src/components/BroadcastGraphics/TimingBoard/StatusIndicator/styles.ts +++ b/src/components/BroadcastGraphics/TimingBoard/StatusIndicator/styles.ts @@ -83,6 +83,41 @@ export const LapLabel = styled.span` `; +////// 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` + 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` position: absolute; diff --git a/src/components/BroadcastGraphics/TimingBoard/TimingTower/TimingTowerRow.tsx b/src/components/BroadcastGraphics/TimingBoard/TimingTower/TimingTowerRow.tsx index e867d16..e499e3b 100644 --- a/src/components/BroadcastGraphics/TimingBoard/TimingTower/TimingTowerRow.tsx +++ b/src/components/BroadcastGraphics/TimingBoard/TimingTower/TimingTowerRow.tsx @@ -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, diff --git a/src/components/Common/Inputs/SelectField/SelectField.tsx b/src/components/Common/Inputs/SelectField/SelectField.tsx new file mode 100644 index 0000000..057517c --- /dev/null +++ b/src/components/Common/Inputs/SelectField/SelectField.tsx @@ -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, + 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 ( + + {label != null && {label}} + onChange(event.target.value)} + > + {options.map(option => ( + + ))} + + + ); +} diff --git a/src/components/Common/Inputs/SelectField/index.ts b/src/components/Common/Inputs/SelectField/index.ts new file mode 100644 index 0000000..ab533eb --- /dev/null +++ b/src/components/Common/Inputs/SelectField/index.ts @@ -0,0 +1,2 @@ +export { SelectField } from "./SelectField"; +export type { SelectFieldProps, SelectOption } from "./SelectField"; diff --git a/src/components/Common/Inputs/SelectField/styles.ts b/src/components/Common/Inputs/SelectField/styles.ts new file mode 100644 index 0000000..c515fa0 --- /dev/null +++ b/src/components/Common/Inputs/SelectField/styles.ts @@ -0,0 +1,40 @@ +import styled from "styled-components/macro"; + +type FieldWrapperProps = { + width?: string, +}; +export const FieldWrapper = styled.label` + 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; + } +`; diff --git a/src/components/Common/Inputs/SlotSelector/SlotSelector.tsx b/src/components/Common/Inputs/SlotSelector/SlotSelector.tsx index 0686e83..362ca23 100644 --- a/src/components/Common/Inputs/SlotSelector/SlotSelector.tsx +++ b/src/components/Common/Inputs/SlotSelector/SlotSelector.tsx @@ -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); }; diff --git a/src/components/Common/Inputs/TextField/TextField.tsx b/src/components/Common/Inputs/TextField/TextField.tsx new file mode 100644 index 0000000..0d7d370 --- /dev/null +++ b/src/components/Common/Inputs/TextField/TextField.tsx @@ -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(null); + // One stable name per mounted field keeps autofill and assistive tech happy. + const [name] = useState(() => `field-${++fieldId}`); + const displayValue = draft ?? String(value); + + return ( + + {label != null && {label}} + 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); + } + }} + /> + + ); +} diff --git a/src/components/Common/Inputs/TextField/index.ts b/src/components/Common/Inputs/TextField/index.ts new file mode 100644 index 0000000..87e51e5 --- /dev/null +++ b/src/components/Common/Inputs/TextField/index.ts @@ -0,0 +1,2 @@ +export { TextField } from "./TextField"; +export type { TextFieldProps } from "./TextField"; diff --git a/src/components/Common/Inputs/TextField/styles.ts b/src/components/Common/Inputs/TextField/styles.ts new file mode 100644 index 0000000..b6c3e1e --- /dev/null +++ b/src/components/Common/Inputs/TextField/styles.ts @@ -0,0 +1,39 @@ +import styled from "styled-components/macro"; + +type FieldWrapperProps = { + width?: string, +}; +export const FieldWrapper = styled.label` + 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; + } +`; diff --git a/src/components/Common/Toast/Toast.tsx b/src/components/Common/Toast/Toast.tsx new file mode 100644 index 0000000..ec43c86 --- /dev/null +++ b/src/components/Common/Toast/Toast.tsx @@ -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 {toast.text}; +} diff --git a/src/components/Common/Toast/index.ts b/src/components/Common/Toast/index.ts new file mode 100644 index 0000000..c22e0ff --- /dev/null +++ b/src/components/Common/Toast/index.ts @@ -0,0 +1 @@ +export { Toast } from "./Toast"; diff --git a/src/components/Common/Toast/styles.ts b/src/components/Common/Toast/styles.ts new file mode 100644 index 0000000..67f948e --- /dev/null +++ b/src/components/Common/Toast/styles.ts @@ -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); +`; diff --git a/src/components/Menu/Menu.tsx b/src/components/Menu/Menu.tsx index d5c68f3..8ae415e 100644 --- a/src/components/Menu/Menu.tsx +++ b/src/components/Menu/Menu.tsx @@ -12,11 +12,11 @@ export const MainMenu = React.forwardRef( (_, ref) => ( ), @@ -35,7 +35,7 @@ const Menu = React.forwardRef( return ( - Formula One logo + F1 标志 {props.title}