diff --git a/app.py b/app.py index 53fae39..b835a37 100644 --- a/app.py +++ b/app.py @@ -30,7 +30,7 @@ from ui_builder import install_ui_builder from khl_site.khl_data_center import APP as khl_site_app BASE_DIR = Path(__file__).resolve().parent -BUILD_VERSION = "2026.09.23.5" +BUILD_VERSION = "2026.09.23.6" # compatibility: BUILD_VERSION = "2026.08.26.1" # compatibility: BUILD_VERSION = "2026.08.25.1" # compatibility: BUILD_VERSION = "2026.08.24.15" diff --git a/hockey_data/service.py b/hockey_data/service.py index ff11b82..94c45a6 100644 --- a/hockey_data/service.py +++ b/hockey_data/service.py @@ -7056,6 +7056,7 @@ class HockeyDataService: "current_ms": default_ms, "running": False, "paused": True, + "started_once": False, "finished": False, "reached": {}, }, @@ -7089,6 +7090,10 @@ class HockeyDataService: current_ms = max(-12 * 60 * 60 * 1000, min(12 * 60 * 60 * 1000, current_ms)) finished = bool(source_main.get("finished", False)) running = bool(source_main.get("running", False)) and not finished + started_once = bool(source_main.get( + "started_once", + running or finished or abs(current_ms - int(default_ms)) > 1000, + )) reached = source_main.get("reached") if not isinstance(reached, dict): reached = {} @@ -7119,6 +7124,7 @@ class HockeyDataService: "current_ms": current_ms, "running": running, "paused": bool(source_main.get("paused", not running)), + "started_once": started_once, "finished": finished, "reached": reached, }, diff --git a/ui_builder/static/app.js b/ui_builder/static/app.js index d9faf8b..686522d 100644 --- a/ui_builder/static/app.js +++ b/ui_builder/static/app.js @@ -1,4 +1,4 @@ -// BUILD158_SETCOUNTDOWN_SUSPENDCOUNTDOWN +// BUILD159_COUNTDOWN_TRANSITION_FIXES // BUILD155: all hockey game/penalty timers use native vMix Countdown; no per-second SetText mirroring. // BUILD153: settings freeze all data-driven DOM rendering and keep dropdown popovers open. // BUILD152: all browser-side hockey data polling pauses while operator settings are open. @@ -4261,20 +4261,36 @@ function startCustomTooltips() { } function vmixGameCountdownControlCommands(input, selectedName, millisecondsProvider, action = "start") { - // BUILD158: restore the proven BUILD93/105 native-countdown transport. - // Runtime supplies the countdown duration/value once on each Start/Resume via - // SetCountdown, then vMix counts locally. A pause uses SuspendCountdown so the - // native countdown is stopped without StopCountdown's reset-to-start behaviour. - // There is never any per-second vMix timer write in this path. + // BUILD159: keep vMix as a native countdown, but separate the transitions: + // fresh start -> SetCountdown + StartCountdown + // resume -> StartCountdown only (never reseed a paused native clock) + // pause -> SuspendCountdown + // explicit set -> SetCountdown + StopCountdown so vMix immediately displays + // the newly requested value while remaining stopped + // set_running -> SetCountdown + StopCountdown + StartCountdown + // This avoids the 1-2 second jump that occurred when Resume re-read Runtime. const target = { Input: String(input || "").trim(), SelectedName: String(selectedName || "").trim() }; if (!target.Input || !target.SelectedName) return []; if (action === "pause" || action === "stop") { return [{ Function: "SuspendCountdown", ...target }]; } + if (action === "resume") { + return [{ Function: "StartCountdown", ...target }]; + } const milliseconds = typeof millisecondsProvider === "function" ? millisecondsProvider() : millisecondsProvider; const value = vmixCountdownValue(milliseconds); if (action === "set") { - return [{ Function: "SetCountdown", ...target, Value: value }]; + return [ + { Function: "SetCountdown", ...target, Value: value }, + { Function: "StopCountdown", ...target }, + ]; + } + if (action === "set_running") { + return [ + { Function: "SetCountdown", ...target, Value: value }, + { Function: "StopCountdown", ...target }, + { Function: "StartCountdown", ...target }, + ]; } return [ { Function: "SetCountdown", ...target, Value: value }, @@ -4910,7 +4926,7 @@ function startCustomTooltips() { } } - async function syncActiveVmixGameCountdown(component, timerState, eventName) { + async function syncActiveVmixGameCountdown(component, timerState, eventName, detail = {}) { if (!component?.action_id || eventName === "timer_tick") return false; const explicitSeedEvent = ["timer_reset", "timer_set_time", "timer_add_time", "timer_subtract_time", "timer_restart"].includes(eventName); const candidateSteps = []; @@ -4945,19 +4961,20 @@ function startCustomTooltips() { seenTargets.add(targetKey); const valueProvider = () => timerState.currentMs; - if (["timer_start", "timer_resume"].includes(eventName)) { - commands.push(...vmixGameCountdownControlCommands(input, selectedName, valueProvider, "start")); + if (eventName === "timer_start") { + const transition = detail?.wasStartedOnce ? "resume" : "start"; + commands.push(...vmixGameCountdownControlCommands(input, selectedName, valueProvider, transition)); + } else if (eventName === "timer_resume") { + commands.push(...vmixGameCountdownControlCommands(input, selectedName, valueProvider, "resume")); } else if (eventName === "timer_restart") { - commands.push(...vmixGameCountdownControlCommands(input, selectedName, valueProvider, "set")); - markVmixGameCountdownSeeded(input, selectedName); commands.push(...vmixGameCountdownControlCommands(input, selectedName, valueProvider, "start")); } else if (eventName === "timer_pause") { commands.push(...vmixGameCountdownControlCommands(input, selectedName, valueProvider, "pause")); } else if (["timer_stop", "timer_finished"].includes(eventName)) { commands.push(...vmixGameCountdownControlCommands(input, selectedName, valueProvider, "stop")); } else if (["timer_reset", "timer_set_time", "timer_add_time", "timer_subtract_time"].includes(eventName)) { - commands.push(...vmixGameCountdownControlCommands(input, selectedName, valueProvider, "set")); - markVmixGameCountdownSeeded(input, selectedName); + const transition = timerState.running ? "set_running" : "set"; + commands.push(...vmixGameCountdownControlCommands(input, selectedName, valueProvider, transition)); } } if (!commands.length) return false; @@ -5507,6 +5524,8 @@ function startCustomTooltips() { const pausing = action === "pause"; const commands = []; state.activeHockeyVmixTimerSteps.add(step.id); + const gameWasStartedOnce = Boolean(gameTimerState?.startedOnce); + const penaltyStartedBefore = new Map(currentHockeyPenaltyEntries().map(({ event }) => [String(event.id), Boolean(event.startedOnce || event.running)])); // BUILD95: update the web clocks FIRST. The vMix SetCountdown commands below // are then always seeded from the exact post-action Runtime value. @@ -5534,11 +5553,12 @@ function startCustomTooltips() { step.game_vmix_input, step.game_vmix_selected_name, () => gameTimerState.currentMs, "pause" )); } else { - // BUILD158: every Start/Resume sends SetCountdown from the current Runtime value, - // then starts the native countdown. vMix performs the second-by-second count - // locally; Runtime never mirrors timer_tick values to vMix. + // BUILD159: a fresh period/start seeds the native vMix countdown once. + // A true Resume sends only StartCountdown, so the paused vMix clock cannot + // jump by the browser/server latency accumulated while the operator presses Space. + const transition = gameWasStartedOnce ? "resume" : "start"; commands.push(...vmixGameCountdownControlCommands( - step.game_vmix_input, step.game_vmix_selected_name, () => gameTimerState.currentMs, "start" + step.game_vmix_input, step.game_vmix_selected_name, () => gameTimerState.currentMs, transition )); } } @@ -5586,8 +5606,9 @@ function startCustomTooltips() { )); } } else { + const transition = penaltyStartedBefore.get(String(event.id)) ? "resume" : "start"; commands.push(...vmixGameCountdownControlCommands( - target.input, target.selected_name, () => event.remainingMs, "start" + target.input, target.selected_name, () => event.remainingMs, transition )); } }); @@ -5986,6 +6007,7 @@ function applyExternalDataPatch(patch, { render = true } = {}) { currentMs: timerInitialMilliseconds(component), running: autoRunning, paused: !autoRunning, + startedOnce: autoRunning, finished: false, lastTimestamp: performance.now(), lastWholeSecond: null, @@ -6166,7 +6188,7 @@ function applyExternalDataPatch(patch, { render = true } = {}) { }); // BUILD155: timer_tick is UI/runtime-only. Never send a per-second vMix request. if (eventName !== "timer_tick" && !detail.suppressVmixSync) { - syncActiveVmixGameCountdown(component, timerState, eventName).catch((error) => console.error("vMix game countdown sync error", error)); + syncActiveVmixGameCountdown(component, timerState, eventName, detail).catch((error) => console.error("vMix game countdown sync error", error)); } if (eventName === "timer_finished") { fireConfiguredTimerFinishActions("game", { gameActionId: component.action_id, component, timerState }); @@ -6272,6 +6294,7 @@ function applyExternalDataPatch(patch, { render = true } = {}) { const timerState = ensureTimerState(component); const now = performance.now(); const valueMs = parseTimerMilliseconds(rawValue, 0); + const wasStartedOnce = Boolean(timerState.startedOnce); let eventName = `timer_${command}`; switch (command) { @@ -6283,11 +6306,13 @@ function applyExternalDataPatch(patch, { render = true } = {}) { } timerState.running = true; timerState.paused = false; + timerState.startedOnce = true; eventName = "timer_start"; break; case "resume": timerState.running = true; timerState.paused = false; + timerState.startedOnce = true; eventName = "timer_resume"; break; case "pause": @@ -6304,6 +6329,7 @@ function applyExternalDataPatch(patch, { render = true } = {}) { timerState.currentMs = timerInitialMilliseconds(component); timerState.running = false; timerState.paused = true; + timerState.startedOnce = false; timerState.finished = false; timerState.reached = {}; eventName = "timer_reset"; @@ -6312,6 +6338,7 @@ function applyExternalDataPatch(patch, { render = true } = {}) { timerState.currentMs = timerInitialMilliseconds(component); timerState.running = true; timerState.paused = false; + timerState.startedOnce = true; timerState.finished = false; timerState.reached = {}; eventName = "timer_restart"; @@ -6345,6 +6372,7 @@ function applyExternalDataPatch(patch, { render = true } = {}) { } timerState.running = true; timerState.paused = false; + timerState.startedOnce = true; eventName = "timer_start"; } break; @@ -6352,7 +6380,7 @@ function applyExternalDataPatch(patch, { render = true } = {}) { timerState.lastTimestamp = now; persistTimer(component, timerState, true); - emitTimerEvent(component, eventName, timerState, { command, amount: rawValue, suppressVmixSync: options.syncVmix === false }); + emitTimerEvent(component, eventName, timerState, { command, amount: rawValue, wasStartedOnce, suppressVmixSync: options.syncVmix === false }); return true; } @@ -9385,6 +9413,11 @@ function quickPanelSelectorRuntimeOptions(selector) { function quickPanelSelectorValue(selector) { const options = quickPanelSelectorRuntimeOptions(selector); + if (String(selector?.style || "") === "periods") { + const control = getByPath(state.data, "hockey.game_control") || {}; + const currentPeriod = String(control?.current_period || ""); + if (options.some((option) => option.value === currentPeriod)) return currentPeriod; + } const values = hockeyMatchRuntimeValues(); const stored = String(values[`panel.${selector.id}.value`] ?? ""); if (options.some((option) => option.value === stored)) return stored; @@ -9521,7 +9554,20 @@ function quickPanelSelectorMarkup(selector) { async function hockeyApplyQuickSelector(selector, value, label = "") { const option = quickPanelSelectorRuntimeOptions(selector).find((item) => item.value === value); const displayLabel = String(label || option?.label || value); - await hockeySetMatchValues({ + if (String(selector?.style || "") === "periods") { + const gameId = hockeyTimerSelectedGameId(); + if (!gameId) throw new Error("Сначала выберите матч"); + const language = hockeyGameControlLanguage(); + const response = await hockeyGameControlRequest(`/games/${encodeURIComponent(gameId)}/control/period`, { + method: "PUT", + body: JSON.stringify({ current_period: value, language }), + }); + hockeyStoreGameControl(gameId, response, { render: false, dispatch: true }); + renderHockeyQuickCommandDock(); + hockeyRefreshQuickPanelMapping().catch(() => {}); + return response; + } + return await hockeySetMatchValues({ [`panel.${selector.id}.value`]: value, [`panel.${selector.id}.label`]: displayLabel, }, { refreshMapping: true }); @@ -12774,6 +12820,7 @@ function renderHockeyPenaltyDashboard(node, component, runtime) { current_ms: Math.round(Number(mainState?.currentMs ?? (mainComponent ? timerInitialMilliseconds(mainComponent) : 20 * 60 * 1000))), running: Boolean(mainState?.running), paused: Boolean(mainState?.paused ?? true), + started_once: Boolean(mainState?.startedOnce), finished: Boolean(mainState?.finished), reached: clone(mainState?.reached || {}), }, @@ -12804,11 +12851,13 @@ function renderHockeyPenaltyDashboard(node, component, runtime) { timerState.finished = Boolean(saved.finished); timerState.running = Boolean(saved.running) && !timerState.finished; timerState.paused = Boolean(saved.paused ?? !timerState.running); + timerState.startedOnce = Boolean(saved.started_once ?? saved.startedOnce ?? (timerState.running || timerState.finished || Math.abs(timerState.currentMs - timerInitialMilliseconds(mainComponent)) > 1000)); timerState.reached = saved.reached && typeof saved.reached === "object" ? clone(saved.reached) : {}; } else { timerState.currentMs = timerInitialMilliseconds(mainComponent); timerState.running = false; timerState.paused = true; + timerState.startedOnce = false; timerState.finished = false; timerState.reached = {}; } @@ -14740,7 +14789,7 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
${timerFinishActionRows(step)}
${escapeHtml(shortcutInventoryLabel())}Для каждого countdown теперь обязательно выбирается конкретный Text / SelectedName. Это исключает отправку времени в первый текстовый элемент по умолчанию.
-

Режим Countdown vMix: каждый Start/Resume один раз передаёт текущее Runtime-время через ChangeCountdown, затем отправляет StartCountdown. После этого vMix считает локально — посекундной передачи времени нет. Pause/Stop отправляет только PauseCountdown. Явная установка/сброс времени также обновляет vMix через ChangeCountdown. Это не зависит от browser-only флага «таймер уже инициализирован» и устойчиво к перезапуску/перезагрузке vMix-титра. StopCountdown в обычном управлении не используется. Команды идут в Agent без ACK. Для верхнего счёта используется одна penalty-плашка: при реальном большинстве она показывает ближайшее изменение численного состава; при чистом равном обоюдном удалении сама по себе не появляется.

+

Режим Countdown vMix: новый период/первый Start задаёт время через SetCountdown и запускает StartCountdown. Пауза использует SuspendCountdown, а Resume — только StartCountdown, поэтому время не прыгает на 1–2 секунды. Смена периода и ручная правка сразу переустанавливают остановленный Countdown в vMix. Посекундной передачи времени нет.

`; } else if (step.type === "delay") { body.innerHTML = `
`; @@ -15567,6 +15616,10 @@ function renderHockeyPenaltyDashboard(node, component, runtime) { hockeyApplySavedTimers(gameId, payload.timers); state.hockeyTimerDirty = false; state.hockeyTimerRevision += 1; + // BUILD159: a real period transition resets the main Runtime clock to the + // rule duration (20:00 / regular OT / playoff OT) and immediately pins the + // stopped native vMix countdown to that same base value. + syncConfiguredScoreboardCountdownsToRuntime().catch((error) => console.error("vMix period countdown reset error", error)); } finally { state.hockeyTimerHydrating = false; }