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:
1 parent
ed5c6e752c
commit
9528307820
78 files changed
+5066
-438
No files matched your search
@@ -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
@@ -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;
|
||||
@@ -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);
|
||||
}, []);
|
||||
}
|
||||
@@ -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);
|
||||
}, []);
|
||||
}
|
||||
@@ -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");
|
||||
@@ -0,0 +1,3 @@
|
||||
import { RootState } from "../../types/state";
|
||||
|
||||
export const uiSelector = (state: RootState) => state.ui;
|
||||
@@ -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;
|
||||
Reference in new issue
Block a user