165 build - ChatGPT-6 поправка интерфейса

This commit is contained in:
2026-09-29 11:11:17 +03:00
parent 5d416b729b
commit 615cf5d109
7 changed files with 825 additions and 35 deletions

106
app.py
View File

@@ -1,6 +1,8 @@
from __future__ import annotations from __future__ import annotations
import json
import os import os
import tempfile
from pathlib import Path from pathlib import Path
from datetime import date from datetime import date
from typing import Any from typing import Any
@@ -33,7 +35,7 @@ from khl_site.khl_data_center import APP as khl_site_app, configure_storage, syn
from hockey_data.khl_career import KhlCareerService from hockey_data.khl_career import KhlCareerService
BASE_DIR = Path(__file__).resolve().parent BASE_DIR = Path(__file__).resolve().parent
BUILD_VERSION = "2026.09.27.3" BUILD_VERSION = "2026.09.29.2"
# compatibility: BUILD_VERSION = "2026.09.24.2" # compatibility: BUILD_VERSION = "2026.09.24.2"
# compatibility: BUILD_VERSION = "2026.09.23.8" # compatibility: BUILD_VERSION = "2026.09.23.8"
# compatibility: BUILD_VERSION = "2026.09.23.7" # compatibility: BUILD_VERSION = "2026.09.23.7"
@@ -90,6 +92,89 @@ hockey_agent_hub = VmixAgentHub(hockey_database, settings=hockey_settings)
hockey_idle_matches = IdleMatchReaper(hockey_database, hockey_agent_hub) hockey_idle_matches = IdleMatchReaper(hockey_database, hockey_agent_hub)
PLAYER_PANEL_BUTTONS_PATH = BASE_DIR / "settings" / "hockey_player_panel_buttons.json"
def _normalise_player_panel_title_buttons(payload: Any) -> dict[str, Any]:
"""Normalise operator-configured Preview buttons for player-selection panels.
This deliberately lives in a standalone JSON file rather than app.js / the
main UI Builder document. A studio can therefore change title assignments
without editing application code or rebuilding the whole layout.
"""
source = payload if isinstance(payload, dict) else {}
rows = source.get("buttons") if isinstance(source.get("buttons"), list) else []
result: list[dict[str, Any]] = []
used_ids: set[str] = set()
for index, raw in enumerate(rows[:128]):
if not isinstance(raw, dict):
continue
panel_id = str(raw.get("panel_id") or "").strip()[:64]
label = str(raw.get("label") or "").strip()[:80]
input_ref = str(raw.get("input") or raw.get("input_ref") or "").strip()[:300]
if not panel_id or not label:
continue
button_id = str(raw.get("id") or f"panel_title_{index + 1}").strip()
button_id = "".join(ch if ch.isascii() and (ch.isalnum() or ch in "_-") else "_" for ch in button_id)[:64].strip("_")
if not button_id:
button_id = f"panel_title_{index + 1}"
base_id = button_id
suffix = 2
while button_id in used_ids:
ending = f"_{suffix}"
button_id = f"{base_id[:64 - len(ending)]}{ending}"
suffix += 1
used_ids.add(button_id)
try:
sort_order = int(raw.get("sort_order", index * 10))
except (TypeError, ValueError):
sort_order = index * 10
result.append({
"id": button_id,
"panel_id": panel_id,
"label": label,
"description": str(raw.get("description") or "").strip()[:300],
"icon": str(raw.get("icon") or "▶").strip()[:32] or "▶",
"icon_only": raw.get("icon_only") is True,
"input": input_ref,
"enabled": raw.get("enabled") is not False,
"sort_order": max(0, min(100000, sort_order)),
})
result.sort(key=lambda item: (str(item["panel_id"]), int(item["sort_order"]), str(item["label"]).casefold()))
return {"version": 1, "buttons": result}
def _load_player_panel_title_buttons() -> dict[str, Any]:
PLAYER_PANEL_BUTTONS_PATH.parent.mkdir(parents=True, exist_ok=True)
if not PLAYER_PANEL_BUTTONS_PATH.exists():
payload = {"version": 1, "buttons": []}
try:
with PLAYER_PANEL_BUTTONS_PATH.open("x", encoding="utf-8") as target:
target.write(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
except FileExistsError:
return _load_player_panel_title_buttons()
return payload
try:
raw = json.loads(PLAYER_PANEL_BUTTONS_PATH.read_text(encoding="utf-8"))
except (OSError, ValueError, TypeError) as error:
raise HTTPException(status_code=500, detail="Не удалось прочитать настройки кнопок титров. Проверьте settings/hockey_player_panel_buttons.json.") from error
return _normalise_player_panel_title_buttons(raw)
def _save_player_panel_title_buttons(payload: Any) -> dict[str, Any]:
normalised = _normalise_player_panel_title_buttons(payload)
PLAYER_PANEL_BUTTONS_PATH.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=PLAYER_PANEL_BUTTONS_PATH.parent,
prefix=".panel-buttons-", suffix=".tmp", delete=False) as target:
tmp_path = Path(target.name)
target.write(json.dumps(normalised, ensure_ascii=False, indent=2) + "\n")
try:
tmp_path.replace(PLAYER_PANEL_BUTTONS_PATH)
finally:
tmp_path.unlink(missing_ok=True)
return normalised
@app.on_event("startup") @app.on_event("startup")
async def hockey_mapping_auto_refresh_startup() -> None: async def hockey_mapping_auto_refresh_startup() -> None:
await run_db(sync_storage) await run_db(sync_storage)
@@ -315,6 +400,25 @@ async def save_hockey_prematch_buttons(payload: dict[str, Any]) -> dict[str, Any
} }
@app.get(
"/api/hockey/ui/player-panel-buttons",
dependencies=[Depends(hockey_auth.require_user)],
tags=["Hockey UI"],
)
async def get_hockey_player_panel_buttons() -> dict[str, Any]:
return _load_player_panel_title_buttons()
@app.post(
"/api/hockey/ui/player-panel-buttons",
dependencies=[Depends(hockey_auth.require_admin)],
tags=["Hockey UI"],
)
async def save_hockey_player_panel_buttons(payload: dict[str, Any]) -> dict[str, Any]:
saved = _save_player_panel_title_buttons(payload)
return {"ok": True, **saved}
@app.post( @app.post(
"/api/hockey/ui/triggers", "/api/hockey/ui/triggers",
dependencies=[Depends(hockey_auth.require_admin)], dependencies=[Depends(hockey_auth.require_admin)],

View File

@@ -1373,6 +1373,10 @@ class UserPreference(Base):
selected_tournament_external_id: Mapped[str] = mapped_column( selected_tournament_external_id: Mapped[str] = mapped_column(
String(64), nullable=False, default="" String(64), nullable=False, default=""
) )
# Per-account runtime layout preferences (currently the resizable lower
# command dock). JSON keeps this additive and leaves room for future
# operator-only layout options without changing the shared UI config.
runtime_ui_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
updated_at: Mapped[datetime] = mapped_column( updated_at: Mapped[datetime] = mapped_column(
DateTime, nullable=False, default=datetime.utcnow DateTime, nullable=False, default=datetime.utcnow
) )

View File

@@ -90,6 +90,10 @@ class TriggerPreferencePayload(BaseModel):
enabled: bool = True enabled: bool = True
class RuntimeUiPreferencePayload(BaseModel):
quick_panel_height: int = Field(default=82, ge=72, le=360)
class SessionPayload(BaseModel): class SessionPayload(BaseModel):
tournament_external_id: str = Field(min_length=1, max_length=64) tournament_external_id: str = Field(min_length=1, max_length=64)
game_external_id: str = Field(default="", max_length=64) game_external_id: str = Field(default="", max_length=64)
@@ -1494,6 +1498,24 @@ def create_hockey_router(
enabled=payload.enabled, enabled=payload.enabled,
) )
@router.get("/preferences/runtime-ui")
@db_endpoint
def runtime_ui_preference(
user: HockeyUser = Depends(auth_dependency),
) -> dict[str, Any]:
return service.runtime_ui_preference(wfl_user_id=user.id)
@router.put("/preferences/runtime-ui")
@db_endpoint
def save_runtime_ui_preference(
payload: RuntimeUiPreferencePayload,
user: HockeyUser = Depends(auth_dependency),
) -> dict[str, Any]:
return service.save_runtime_ui_preference(
wfl_user_id=user.id,
quick_panel_height=payload.quick_panel_height,
)
@router.put("/preferences/events") @router.put("/preferences/events")
@db_endpoint @db_endpoint
def save_events_preference( def save_events_preference(

View File

@@ -8679,6 +8679,45 @@ class HockeyDataService:
"toasts_enabled": not bool(row.triggers_disabled), "toasts_enabled": not bool(row.triggers_disabled),
} }
@staticmethod
def _normalise_runtime_ui_preference(raw: Any) -> dict[str, Any]:
payload = raw if isinstance(raw, dict) else {}
try:
height = int(payload.get("quick_panel_height", 82))
except (TypeError, ValueError):
height = 82
return {"quick_panel_height": max(72, min(360, height))}
def runtime_ui_preference(self, *, wfl_user_id: str) -> dict[str, Any]:
with self.database.session() as session:
row = session.get(UserPreference, wfl_user_id)
try:
stored = json.loads(str(row.runtime_ui_json or "{}")) if row is not None else {}
except (TypeError, ValueError):
stored = {}
return {
"wfl_user_id": wfl_user_id,
**self._normalise_runtime_ui_preference(stored),
}
def save_runtime_ui_preference(
self,
*,
wfl_user_id: str,
quick_panel_height: int,
) -> dict[str, Any]:
value = self._normalise_runtime_ui_preference(
{"quick_panel_height": quick_panel_height}
)
with self.database.session() as session:
row = session.get(UserPreference, wfl_user_id)
if row is None:
row = UserPreference(wfl_user_id=wfl_user_id)
session.add(row)
row.runtime_ui_json = json.dumps(value, ensure_ascii=False, separators=(",", ":"))
row.updated_at = datetime.utcnow()
return {"wfl_user_id": wfl_user_id, **value}
def save_toasts_preference(self, *, wfl_user_id: str, enabled: bool) -> dict[str, Any]: def save_toasts_preference(self, *, wfl_user_id: str, enabled: bool) -> dict[str, Any]:
# Reuse the build55 additive column for compatibility, but from build59 it # Reuse the build55 additive column for compatibility, but from build59 it
# represents only routine toast visibility. Trigger execution stays on. # represents only routine toast visibility. Trigger execution stays on.

View File

@@ -192,11 +192,11 @@
function render(force = false) { function render(force = false) {
if (!state.root || !window.UIBuilderRuntime) return; if (!state.root || !window.UIBuilderRuntime) return;
// The header refreshes frequently because the timer changes. Replacing the
// <select> while its native popup is open closes the popup in Chromium.
// Freeze this header only for the duration of period selection.
const periodSelect = state.root.querySelector("[data-hockey-current-period]"); const periodSelect = state.root.querySelector("[data-hockey-current-period]");
if (state.periodEditing || periodSelect === document.activeElement) return; const periodShell = periodSelect?.closest(".hockey-status-period");
const periodBusy = Boolean(state.periodEditing || (periodShell && (
periodShell.contains(document.activeElement) || periodShell.querySelector(".control-popover-open")
)));
const value = snapshot(); const value = snapshot();
const game = value.game; const game = value.game;
const language = value.language === "en" ? "en" : "ru"; const language = value.language === "en" ? "en" : "ru";
@@ -253,6 +253,7 @@
league, league,
finishLabel, finishLabel,
currentPeriod, currentPeriod,
periodOptions,
strengthLabel, strengthLabel,
strengthAdvantage, strengthAdvantage,
strengthHomeLabel, strengthHomeLabel,
@@ -289,7 +290,7 @@
</article>` : ""; </article>` : "";
state.root.classList.toggle("has-game", Boolean(game)); state.root.classList.toggle("has-game", Boolean(game));
state.root.innerHTML = ` const markup = `
<div class="hockey-status-match"> <div class="hockey-status-match">
<div class="hockey-status-team is-home"> <div class="hockey-status-team is-home">
<span>${language === "en" ? "HOME" : "ХОЗЯЕВА"}</span> <span>${language === "en" ? "HOME" : "ХОЗЯЕВА"}</span>
@@ -323,7 +324,29 @@
${penalties} ${penalties}
</div> </div>
`; `;
const periodSignature = JSON.stringify([game?.external_id || "", language, currentPeriod, periodOptions,
Boolean(game && window.HockeyMatchAccess?.canControl?.(String(game.external_id || game.id || "")))]);
const fragment = document.createElement("template");
fragment.innerHTML = markup;
for (const fresh of Array.from(fragment.content.children)) {
const current = state.root.querySelector(`.${fresh.classList[0]}`);
if (fresh.classList.contains("hockey-status-period")) {
const sameGame = state.root.dataset.periodGameId === String(game?.external_id || "");
if (current && sameGame && (periodBusy || state.root.dataset.periodSignature === periodSignature)) {
if (state.root.dataset.periodSignature !== periodSignature) state.signature = "";
continue;
}
state.periodEditing = false;
state.root.dataset.periodSignature = periodSignature;
state.root.dataset.periodGameId = String(game?.external_id || "");
} else if (current?.outerHTML === fresh.outerHTML) continue;
if (current) current.replaceWith(fresh);
else state.root.appendChild(fresh);
}
const currentPeriodSelect = state.root.querySelector("[data-hockey-current-period]"); const currentPeriodSelect = state.root.querySelector("[data-hockey-current-period]");
if (!currentPeriodSelect || currentPeriodSelect.dataset.periodBound === "1") return;
currentPeriodSelect.dataset.periodBound = "1";
window.dispatchEvent(new CustomEvent("ui-builder:controls-rendered", { detail: { root: state.root } }));
currentPeriodSelect?.addEventListener("pointerdown", () => { state.periodEditing = true; }); currentPeriodSelect?.addEventListener("pointerdown", () => { state.periodEditing = true; });
currentPeriodSelect?.addEventListener("focus", () => { state.periodEditing = true; }); currentPeriodSelect?.addEventListener("focus", () => { state.periodEditing = true; });
currentPeriodSelect?.addEventListener("change", (event) => { currentPeriodSelect?.addEventListener("change", (event) => {
@@ -351,6 +374,7 @@
document.querySelector(".runtime-actions .hockey-selected-chip")?.click(); document.querySelector(".runtime-actions .hockey-selected-chip")?.click();
}); });
root.addEventListener("keydown", (event) => { root.addEventListener("keydown", (event) => {
if (event.target !== root && !event.target.closest(".hockey-status-match")) return;
if (event.key !== "Enter" && event.key !== " ") return; if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault(); event.preventDefault();
document.querySelector(".runtime-actions .hockey-selected-chip")?.click(); document.querySelector(".runtime-actions .hockey-selected-chip")?.click();

View File

@@ -1,5 +1,7 @@
// BUILD159_COUNTDOWN_TRANSITION_FIXES // BUILD159_COUNTDOWN_TRANSITION_FIXES
// BUILD155: all hockey game/penalty timers use native vMix Countdown; no per-second SetText mirroring. // BUILD155: all hockey game/penalty timers use native vMix Countdown; no per-second SetText mirroring.
// BUILD165: protect detached select popovers and roster searches; icon buttons; ordered account layout saves.
// BUILD164: live Game controls stay stable during polling; player blocks get configurable Preview buttons; lower dock height is per account.
// BUILD161: live data refresh cannot rebuild an open infraction picker on the main Game tab. // BUILD161: live data refresh cannot rebuild an open infraction picker on the main Game tab.
// BUILD160: strict settings freeze; background vMix inventory refresh never rebuilds an open settings form. // BUILD160: strict settings freeze; background vMix inventory refresh never rebuilds an open settings form.
// BUILD153: settings freeze all data-driven DOM rendering and keep dropdown popovers open. // BUILD153: settings freeze all data-driven DOM rendering and keep dropdown popovers open.
@@ -131,6 +133,21 @@
vmixOverlayTallyAuthoritative: false, vmixOverlayTallyAuthoritative: false,
quickPanelOverlayPollTimer: null, quickPanelOverlayPollTimer: null,
quickPanelOverlayPollPending: false, quickPanelOverlayPollPending: false,
quickPanelResizeActive: false,
quickPanelRenderPending: false,
quickPanelMarkup: "",
runtimeUiPreferenceRevision: 0,
runtimeUiPreferenceSaveQueue: Promise.resolve(),
playerPanelTitleBusy: new Set(),
runtimeRenderedGameId: null,
runtimeRenderedTab: "",
runtimeUiPreferences: { quick_panel_height: 82 },
runtimeUiPreferencesLoaded: false,
runtimeUiPreferenceSaveTimer: null,
hockeyRuntimeInteractiveRenderPending: false,
hockeyRuntimeInteractiveRenderTimer: null,
playerPanelTitleButtons: [],
playerPanelTitleButtonsLoaded: false,
triggerEditorOpenIds: new Set(), triggerEditorOpenIds: new Set(),
shortcutSequenceOpenId: "", shortcutSequenceOpenId: "",
shortcutInventory: { device_id: "", device_name: "", online: false, vmix_connected: false, inventory: { inputs: [] }, devices: [] }, shortcutInventory: { device_id: "", device_name: "", online: false, vmix_connected: false, inventory: { inputs: [] }, devices: [] },
@@ -2080,7 +2097,7 @@
// old handler immediately closed the dropdown, which made settings // old handler immediately closed the dropdown, which made settings
// selects unusable. While settings are open, keep the popover alive // selects unusable. While settings are open, keep the popover alive
// and only recalculate its position. // and only recalculate its position.
if (hockeySettingsDataRefreshPaused() && activeControlPopover.anchor?.isConnected) { if (activeControlPopover.anchor?.isConnected) {
positionControlPopover(activeControlPopover.anchor, activeControlPopover.popup); positionControlPopover(activeControlPopover.anchor, activeControlPopover.popup);
return; return;
} }
@@ -2756,7 +2773,7 @@ function startCustomTooltips() {
if (el.rawData) el.rawData.textContent = JSON.stringify(state.data, null, 2); if (el.rawData) el.rawData.textContent = JSON.stringify(state.data, null, 2);
renderDataPaths(); renderDataPaths();
renderCanvas(); renderCanvas();
renderRuntime(); renderRuntime({ background: true });
if (showToast) toast("Данные обновлены"); if (showToast) toast("Данные обновлены");
} catch (error) { } catch (error) {
state.data = {}; state.data = {};
@@ -5959,7 +5976,7 @@ function applyExternalDataPatch(patch, { render = true } = {}) {
renderDataPaths(); renderDataPaths();
if (render) { if (render) {
renderCanvas(); renderCanvas();
renderRuntime(); renderRuntime({ background: true });
} }
} }
window.dispatchEvent( window.dispatchEvent(
@@ -8267,6 +8284,11 @@ function openTimerQuickEditor(focusActionId = "") {
// BUILD161: do not rebuild the penalty dashboard under an open infraction menu. // BUILD161: do not rebuild the penalty dashboard under an open infraction menu.
// Live match polling and penalty-state refreshes can still update state/tickers, // Live match polling and penalty-state refreshes can still update state/tickers,
// but the operator's dropdown/search stays physically intact until it is closed. // but the operator's dropdown/search stays physically intact until it is closed.
if (activeControlPopover?.anchor?.isConnected && nodes.some((node) => node.contains(activeControlPopover.anchor))) {
scheduleHockeyRuntimeRenderAfterInteraction();
updateHockeyBoardTickerNodes(component);
return;
}
if (menuOpen) { if (menuOpen) {
state.hockeyInfractionMenuRenderPending = true; state.hockeyInfractionMenuRenderPending = true;
updateHockeyBoardTickerNodes(component); updateHockeyBoardTickerNodes(component);
@@ -8469,7 +8491,12 @@ function readAnyHockeyDragData(event) {
} }
const list = div("hpd-roster-list"); const list = div("hpd-roster-list");
players.forEach((player) => list.appendChild(hockeyPlayerRow(component, player, runtime))); const query = String(ensureHockeyBoardState(component).search[side] || "").trim().toLowerCase();
players.forEach((player) => {
const row = hockeyPlayerRow(component, player, runtime);
row.classList.toggle("hidden", Boolean(query) && !row.textContent.toLowerCase().includes(query));
list.appendChild(row);
});
panel.appendChild(list); panel.appendChild(list);
return panel; return panel;
} }
@@ -9216,7 +9243,16 @@ async function hockeyPersistPrematchButtons(buttons, groups = state.config.prema
state.config.quick_panel_selectors = normalizeQuickPanelSelectors(payload.quick_panel_selectors || normalizedSelectors); state.config.quick_panel_selectors = normalizeQuickPanelSelectors(payload.quick_panel_selectors || normalizedSelectors);
state.config.player_selection_panels = normalizePlayerSelectionPanels(payload.player_selection_panels || normalizedPlayerPanels); state.config.player_selection_panels = normalizePlayerSelectionPanels(payload.player_selection_panels || normalizedPlayerPanels);
} }
// Editing dock/button settings must not reset the live match clocks,
// the penalty draft or the operator's search and player selection.
const runtimeState = {
timers: state.timers,
hockeyPenaltyBoards: state.hockeyPenaltyBoards,
componentStates: state.componentStates,
runtimeVisibility: state.runtimeVisibility,
};
ensureConfig(); ensureConfig();
Object.assign(state, runtimeState);
toast("Нижняя панель кнопок сохранена"); toast("Нижняя панель кнопок сохранена");
renderRuntime(); renderRuntime();
return true; return true;
@@ -9256,15 +9292,20 @@ function hockeyQuickPanelButtonOptions(buttons, selectedId = "") {
return triggerSelectOptions([["", "— отдельный элемент —"], ...buttons.map((button) => [button.id, button.label])], selectedId); return triggerSelectOptions([["", "— отдельный элемент —"], ...buttons.map((button) => [button.id, button.label])], selectedId);
} }
function openHockeyPrematchButtonsEditor() { async function openHockeyPrematchButtonsEditor({ section = "buttons", panelId = "" } = {}) {
if (!(await hockeyLoadPlayerPanelTitleButtons({ render: false }))) {
toast("Не удалось загрузить настройки кнопок титров. Попробуйте открыть настройки ещё раз.", true);
return;
}
let draftGroups = normalizePrematchGroups(state.config.prematch_groups); let draftGroups = normalizePrematchGroups(state.config.prematch_groups);
let draft = normalizePrematchButtons(state.config.prematch_buttons); let draft = normalizePrematchButtons(state.config.prematch_buttons);
let draftSelectors = normalizeQuickPanelSelectors(state.config.quick_panel_selectors); let draftSelectors = normalizeQuickPanelSelectors(state.config.quick_panel_selectors);
let draftPlayerPanels = normalizePlayerSelectionPanels(state.config.player_selection_panels); let draftPlayerPanels = normalizePlayerSelectionPanels(state.config.player_selection_panels);
let draftPanelTitleButtons = normalisePlayerPanelTitleButtons(state.playerPanelTitleButtons);
let dragButtonId = ""; let dragButtonId = "";
let dragSelectorId = ""; let dragSelectorId = "";
let activeEditorGroupId = String(state.quickPanelActiveTab || ""); let activeEditorGroupId = String(state.quickPanelActiveTab || "");
let activeEditorSection = "buttons"; let activeEditorSection = ["buttons", "players", "panel_titles"].includes(section) ? section : "buttons";
if (activeEditorGroupId === "__ungrouped") activeEditorGroupId = ""; if (activeEditorGroupId === "__ungrouped") activeEditorGroupId = "";
if (activeEditorGroupId && !draftGroups.some((group) => group.id === activeEditorGroupId)) activeEditorGroupId = draftGroups[0]?.id || ""; if (activeEditorGroupId && !draftGroups.some((group) => group.id === activeEditorGroupId)) activeEditorGroupId = draftGroups[0]?.id || "";
const collapsedEditorGroups = new Set(["", ...draftGroups.map((group) => String(group.id || ""))]); const collapsedEditorGroups = new Set(["", ...draftGroups.map((group) => String(group.id || ""))]);
@@ -9342,6 +9383,26 @@ function openHockeyPrematchButtonsEditor() {
<button type="button" class="icon-btn danger" data-player-panel-delete="${escapeHtml(panel.id)}" title="Удалить блок">×</button> <button type="button" class="icon-btn danger" data-player-panel-delete="${escapeHtml(panel.id)}" title="Удалить блок">×</button>
</article>`; </article>`;
const playerPanelTitleButtonPanelOptions = (selectedId = "") => triggerSelectOptions(
[["", "— выберите блок —"], ...draftPlayerPanels.map((panel) => [panel.id, panel.label])],
selectedId
);
const renderPanelTitleButtonRow = (button, index) => `
<article class="panel-title-button-editor-row" data-panel-title-button-row="${escapeHtml(button.id)}">
<span class="shortcut-target-index">${index + 1}</span>
<label class="shortcut-inline-check"><input type="checkbox" data-panel-title-button-field="enabled" data-panel-title-button-id="${escapeHtml(button.id)}" ${button.enabled ? "checked" : ""}> Активна</label>
<label>Название<input type="text" maxlength="80" data-panel-title-button-field="label" data-panel-title-button-id="${escapeHtml(button.id)}" value="${escapeHtml(button.label)}"></label>
<label>ID<input type="text" maxlength="64" data-panel-title-button-field="id" data-panel-title-button-id="${escapeHtml(button.id)}" value="${escapeHtml(button.id)}"></label>
<label>Блок игроков<select data-panel-title-button-field="panel_id" data-panel-title-button-id="${escapeHtml(button.id)}">${playerPanelTitleButtonPanelOptions(button.panel_id)}</select></label>
<label class="panel-title-button-input">vMix Input → Preview<select data-panel-title-button-field="input" data-panel-title-button-id="${escapeHtml(button.id)}">${vmixInputOptions(button.input)}</select></label>
<label>Иконка<input type="text" maxlength="32" data-panel-title-button-field="icon" data-panel-title-button-id="${escapeHtml(button.id)}" value="${escapeHtml(button.icon)}" placeholder="▶ ★ 📊 👤"></label>
<label class="shortcut-inline-check"><input type="checkbox" data-panel-title-button-field="icon_only" data-panel-title-button-id="${escapeHtml(button.id)}" ${button.icon_only ? "checked" : ""}> Только иконка</label>
<label class="panel-title-button-description">Подсказка<input type="text" maxlength="300" data-panel-title-button-field="description" data-panel-title-button-id="${escapeHtml(button.id)}" value="${escapeHtml(button.description)}" placeholder="Например: крупная статистика игрока"></label>
<div class="player-selection-editor-order"><button type="button" class="mini-btn" data-panel-title-button-up="${escapeHtml(button.id)}" ${index <= 0 ? "disabled" : ""}>↑</button><button type="button" class="mini-btn" data-panel-title-button-down="${escapeHtml(button.id)}" ${index >= draftPanelTitleButtons.length - 1 ? "disabled" : ""}>↓</button></div>
<button type="button" class="icon-btn danger" data-panel-title-button-delete="${escapeHtml(button.id)}" title="Удалить кнопку">×</button>
</article>`;
const renderGroup = (group, groupIndex) => { const renderGroup = (group, groupIndex) => {
const groupId = group?.id || ""; const groupId = group?.id || "";
const buttons = groupButtons(groupId); const buttons = groupButtons(groupId);
@@ -9373,11 +9434,13 @@ function openHockeyPrematchButtonsEditor() {
const validButtons = new Set(draft.map((button) => button.id)); const validButtons = new Set(draft.map((button) => button.id));
draftSelectors = normalizeQuickPanelSelectors(draftSelectors).map((selector) => ({ ...selector, group_id: validGroups.has(selector.group_id) ? selector.group_id : "", button_id: validButtons.has(selector.button_id) ? selector.button_id : "" })); draftSelectors = normalizeQuickPanelSelectors(draftSelectors).map((selector) => ({ ...selector, group_id: validGroups.has(selector.group_id) ? selector.group_id : "", button_id: validButtons.has(selector.button_id) ? selector.button_id : "" }));
draftPlayerPanels = normalizePlayerSelectionPanels(draftPlayerPanels); draftPlayerPanels = normalizePlayerSelectionPanels(draftPlayerPanels);
draftPanelTitleButtons = normalisePlayerPanelTitleButtons(draftPanelTitleButtons);
showSettingsModal("Нижняя панель · кнопки", ` showSettingsModal("Нижняя панель · кнопки", `
<div class="prematch-editor"> <div class="prematch-editor">
<nav class="prematch-editor-tabs" aria-label="Раздел настроек нижней панели"> <nav class="prematch-editor-tabs" aria-label="Раздел настроек нижней панели">
<button type="button" class="prematch-editor-tab ${activeEditorSection === "buttons" ? "active" : ""}" data-prematch-editor-tab="buttons">Кнопки</button> <button type="button" class="prematch-editor-tab ${activeEditorSection === "buttons" ? "active" : ""}" data-prematch-editor-tab="buttons">Кнопки</button>
<button type="button" class="prematch-editor-tab ${activeEditorSection === "players" ? "active" : ""}" data-prematch-editor-tab="players">Блоки игроков <span>${draftPlayerPanels.length}</span></button> <button type="button" class="prematch-editor-tab ${activeEditorSection === "players" ? "active" : ""}" data-prematch-editor-tab="players">Блоки игроков <span>${draftPlayerPanels.length}</span></button>
<button type="button" class="prematch-editor-tab ${activeEditorSection === "panel_titles" ? "active" : ""}" data-prematch-editor-tab="panel_titles">Титры блоков <span>${draftPanelTitleButtons.length}</span></button>
</nav> </nav>
${activeEditorSection === "buttons" ? ` ${activeEditorSection === "buttons" ? `
<section class="prematch-editor-section" data-prematch-editor-section="buttons"> <section class="prematch-editor-section" data-prematch-editor-section="buttons">
@@ -9394,11 +9457,16 @@ function openHockeyPrematchButtonsEditor() {
${draftGroups.map((group, index) => renderGroup(group, index)).join("")} ${draftGroups.map((group, index) => renderGroup(group, index)).join("")}
</div> </div>
</section> </section>
` : ` ` : activeEditorSection === "players" ? `
<section class="player-selection-editor prematch-editor-section" data-prematch-editor-section="players"> <section class="player-selection-editor prematch-editor-section" data-prematch-editor-section="players">
<header><div><span>DRAG & DROP ИГРОКОВ</span><strong>Блоки выбора игроков</strong><small>Создание сравнений, «3 звезды» и одиночных выборов. ID автоматически формирует Mapping: player_select.&lt;ID&gt;.player1_id и т. д.</small></div><button type="button" class="btn" data-player-panel-add>+ Блок игроков</button></header> <header><div><span>DRAG & DROP ИГРОКОВ</span><strong>Блоки выбора игроков</strong><small>Создание сравнений, «3 звезды» и одиночных выборов. ID автоматически формирует Mapping: player_select.&lt;ID&gt;.player1_id и т. д.</small></div><button type="button" class="btn" data-player-panel-add>+ Блок игроков</button></header>
<div class="player-selection-editor-list">${draftPlayerPanels.length ? draftPlayerPanels.map(renderPlayerPanelRow).join("") : `<div class="prematch-group-empty">Блоков игроков пока нет</div>`}</div> <div class="player-selection-editor-list">${draftPlayerPanels.length ? draftPlayerPanels.map(renderPlayerPanelRow).join("") : `<div class="prematch-group-empty">Блоков игроков пока нет</div>`}</div>
</section> </section>
` : `
<section class="panel-title-button-editor prematch-editor-section" data-prematch-editor-section="panel_titles">
<header><div><span>PLAYER BLOCK → VMIX PREVIEW</span><strong>Кнопки титров под блоками игроков</strong><small>Один блок может иметь несколько кнопок. Перед Preview обновляется Mapping выбранного блока, затем выбранный vMix Input отправляется в Preview.</small></div><div class="prematch-editor-head-actions"><button type="button" class="btn" data-panel-title-refresh-inputs>↻ Inputs</button><button type="button" class="btn btn-accent" data-panel-title-button-add>+ Кнопка титра</button></div></header>
<div class="panel-title-button-editor-list">${draftPanelTitleButtons.length ? draftPanelTitleButtons.map(renderPanelTitleButtonRow).join("") : `<div class="prematch-group-empty">Кнопок титров пока нет. Создайте блок игроков, затем назначьте ему один или несколько vMix Input.</div>`}</div>
</section>
`} `}
<div class="prematch-editor-actions"> <div class="prematch-editor-actions">
<button type="button" class="btn" data-prematch-cancel>Отмена</button> <button type="button" class="btn" data-prematch-cancel>Отмена</button>
@@ -9409,7 +9477,7 @@ function openHockeyPrematchButtonsEditor() {
document.querySelectorAll("[data-prematch-editor-tab]").forEach((button) => button.addEventListener("click", () => { document.querySelectorAll("[data-prematch-editor-tab]").forEach((button) => button.addEventListener("click", () => {
const section = String(button.dataset.prematchEditorTab || "buttons"); const section = String(button.dataset.prematchEditorTab || "buttons");
if (!["buttons", "players"].includes(section) || section === activeEditorSection) return; if (!["buttons", "players", "panel_titles"].includes(section) || section === activeEditorSection) return;
activeEditorSection = section; activeEditorSection = section;
renderEditor(); renderEditor();
})); }));
@@ -9434,6 +9502,27 @@ function openHockeyPrematchButtonsEditor() {
draftPlayerPanels.push({ id: `players_${draftPlayerPanels.length + 1}`, label: `Игроки ${draftPlayerPanels.length + 1}`, description: "", slots: 2, rule: "any", sync_selected_player: false, collapsed_default: true, sort_order: draftPlayerPanels.length * 10, enabled: true }); draftPlayerPanels.push({ id: `players_${draftPlayerPanels.length + 1}`, label: `Игроки ${draftPlayerPanels.length + 1}`, description: "", slots: 2, rule: "any", sync_selected_player: false, collapsed_default: true, sort_order: draftPlayerPanels.length * 10, enabled: true });
renderEditor(); renderEditor();
}); });
document.querySelector("[data-panel-title-button-add]")?.addEventListener("click", () => {
if (!draftPlayerPanels.length) return toast("Сначала создайте хотя бы один блок игроков", true);
if (draftPanelTitleButtons.length >= 128) return toast("Можно создать до 128 кнопок титров", true);
const panel = draftPlayerPanels.find((item) => item.id === panelId) || draftPlayerPanels[0];
draftPanelTitleButtons.push({
id: `panel_title_${draftPanelTitleButtons.length + 1}`,
panel_id: panel.id,
label: `Титр ${draftPanelTitleButtons.length + 1}`,
description: "",
icon: "▶",
icon_only: false,
input: "",
enabled: true,
sort_order: draftPanelTitleButtons.length * 10,
});
renderEditor();
});
document.querySelector("[data-panel-title-refresh-inputs]")?.addEventListener("click", async () => {
await loadShortcutInventory({ silent: true });
renderEditor();
});
document.querySelector("[data-prematch-add]")?.addEventListener("click", () => { document.querySelector("[data-prematch-add]")?.addEventListener("click", () => {
if (draft.length >= 64) return toast("Можно создать до 64 кнопок", true); if (draft.length >= 64) return toast("Можно создать до 64 кнопок", true);
@@ -9523,7 +9612,10 @@ function openHockeyPrematchButtonsEditor() {
draftPlayerPanels = normalized; draftPlayerPanels = normalized;
const updated = draftPlayerPanels.find((item) => item.id === String(panel.id || "").trim().replace(/[^A-Za-z0-9_]+/g, "_").replace(/^_+|_+$/g, "")) const updated = draftPlayerPanels.find((item) => item.id === String(panel.id || "").trim().replace(/[^A-Za-z0-9_]+/g, "_").replace(/^_+|_+$/g, ""))
|| draftPlayerPanels.find((item) => item.sort_order === panel.sort_order && item.label === panel.label); || draftPlayerPanels.find((item) => item.sort_order === panel.sort_order && item.label === panel.label);
if (updated && previousId !== updated.id) toast(`ID блока: ${updated.id}`); if (updated && previousId !== updated.id) {
draftPanelTitleButtons.forEach((button) => { if (button.panel_id === previousId) button.panel_id = updated.id; });
toast(`ID блока: ${updated.id}`);
}
renderEditor(); renderEditor();
} }
}); });
@@ -9544,6 +9636,41 @@ function openHockeyPrematchButtonsEditor() {
const panel = draftPlayerPanels.find((item) => item.id === button.dataset.playerPanelDelete); const panel = draftPlayerPanels.find((item) => item.id === button.dataset.playerPanelDelete);
if (!panel || !window.confirm(`Удалить блок «${panel.label}»? Сохранённые значения матча останутся в базе, но блок исчезнет из интерфейса.`)) return; if (!panel || !window.confirm(`Удалить блок «${panel.label}»? Сохранённые значения матча останутся в базе, но блок исчезнет из интерфейса.`)) return;
draftPlayerPanels = draftPlayerPanels.filter((item) => item.id !== panel.id); draftPlayerPanels = draftPlayerPanels.filter((item) => item.id !== panel.id);
draftPanelTitleButtons = draftPanelTitleButtons.filter((item) => item.panel_id !== panel.id);
renderEditor();
}));
document.querySelectorAll("[data-panel-title-button-field]").forEach((control) => {
const field = control.dataset.panelTitleButtonField;
const eventName = field === "id" || control.type === "checkbox" || control.tagName === "SELECT" ? "change" : "input";
control.addEventListener(eventName, () => {
const button = draftPanelTitleButtons.find((item) => item.id === control.dataset.panelTitleButtonId);
if (!button) return;
const previousId = button.id;
button[field] = control.type === "checkbox" ? control.checked : control.value;
if (field === "id") {
draftPanelTitleButtons = normalisePlayerPanelTitleButtons(draftPanelTitleButtons);
const renamed = draftPanelTitleButtons.find((item) => item.id === String(button.id || "").replace(/[^A-Za-z0-9_-]+/g, "_").replace(/^_+|_+$/g, ""))
|| draftPanelTitleButtons.find((item) => item.panel_id === button.panel_id && item.label === button.label);
if (renamed && renamed.id !== previousId) toast(`ID кнопки: ${renamed.id}`);
renderEditor();
}
});
});
document.querySelectorAll("[data-panel-title-button-up]").forEach((button) => button.addEventListener("click", () => {
const index = draftPanelTitleButtons.findIndex((item) => item.id === button.dataset.panelTitleButtonUp);
if (index > 0) [draftPanelTitleButtons[index - 1], draftPanelTitleButtons[index]] = [draftPanelTitleButtons[index], draftPanelTitleButtons[index - 1]];
draftPanelTitleButtons.forEach((item, i) => { item.sort_order = i * 10; });
renderEditor();
}));
document.querySelectorAll("[data-panel-title-button-down]").forEach((button) => button.addEventListener("click", () => {
const index = draftPanelTitleButtons.findIndex((item) => item.id === button.dataset.panelTitleButtonDown);
if (index >= 0 && index < draftPanelTitleButtons.length - 1) [draftPanelTitleButtons[index + 1], draftPanelTitleButtons[index]] = [draftPanelTitleButtons[index], draftPanelTitleButtons[index + 1]];
draftPanelTitleButtons.forEach((item, i) => { item.sort_order = i * 10; });
renderEditor();
}));
document.querySelectorAll("[data-panel-title-button-delete]").forEach((button) => button.addEventListener("click", () => {
draftPanelTitleButtons = draftPanelTitleButtons.filter((item) => item.id !== button.dataset.panelTitleButtonDelete);
renderEditor(); renderEditor();
})); }));
@@ -9658,10 +9785,24 @@ function openHockeyPrematchButtonsEditor() {
panel[field] = control.type === "checkbox" ? control.checked : (control.type === "number" ? clamp(Number(control.value) || 1, 1, 6) : control.value); panel[field] = control.type === "checkbox" ? control.checked : (control.type === "number" ? clamp(Number(control.value) || 1, 1, 6) : control.value);
}); });
}); });
document.querySelectorAll("[data-panel-title-button-row]").forEach((row) => {
const button = draftPanelTitleButtons.find((item) => item.id === row.dataset.panelTitleButtonRow);
if (!button) return;
row.querySelectorAll("[data-panel-title-button-field]").forEach((control) => {
const field = control.dataset.panelTitleButtonField;
button[field] = control.type === "checkbox" ? control.checked : control.value;
});
});
draftGroups.forEach((item, index) => { item.sort_order = index * 10; }); draftGroups.forEach((item, index) => { item.sort_order = index * 10; });
draftPlayerPanels.forEach((item, index) => { item.sort_order = index * 10; }); draftPlayerPanels.forEach((item, index) => { item.sort_order = index * 10; });
draftPanelTitleButtons.forEach((item, index) => { item.sort_order = index * 10; });
for (const groupId of ["", ...draftGroups.map((group) => group.id)]) renumberGroup(groupId); for (const groupId of ["", ...draftGroups.map((group) => group.id)]) renumberGroup(groupId);
if (await hockeyPersistPrematchButtons(draft, draftGroups, draftSelectors, draftPlayerPanels)) closeModal(); if (!(await hockeyPersistPrematchButtons(draft, draftGroups, draftSelectors, draftPlayerPanels))) return;
if (!(await hockeySavePlayerPanelTitleButtons(draftPanelTitleButtons))) return;
toast("Кнопки титров блоков сохранены");
closeModal();
renderRuntime();
renderHockeyQuickCommandDock({ force: true });
}); });
}; };
renderEditor(); renderEditor();
@@ -9746,7 +9887,8 @@ async function hockeyRefreshQuickPanelMapping() {
try { try {
const response = await fetch(`/api/hockey/agents/devices/${encodeURIComponent(deviceId)}/apply-mapping?only_changed=true`, { method: "POST", cache: "no-store", credentials: "same-origin" }); const response = await fetch(`/api/hockey/agents/devices/${encodeURIComponent(deviceId)}/apply-mapping?only_changed=true`, { method: "POST", cache: "no-store", credentials: "same-origin" });
if (!response.ok) return false; if (!response.ok) return false;
return true; const payload = await response.json();
return payload?.ok !== false && !(payload?.errors?.length);
} catch (_) { return false; } } catch (_) { return false; }
} }
@@ -9822,7 +9964,7 @@ async function hockeyScoreCommand(command, { refreshMapping = true, announce = t
}); });
hockeyStoreGameControl(gameId, payload, { render: false, dispatch: true }); hockeyStoreGameControl(gameId, payload, { render: false, dispatch: true });
hockeyApplyScoreToRuntime(payload?.score, { render: false }); hockeyApplyScoreToRuntime(payload?.score, { render: false });
renderHockeyQuickCommandDock(); renderHockeyQuickCommandDock({ force: true });
if (refreshMapping) await hockeyRefreshScoreMapping(); if (refreshMapping) await hockeyRefreshScoreMapping();
if (announce) { if (announce) {
const score = payload?.score || {}; const score = payload?.score || {};
@@ -9879,7 +10021,7 @@ async function hockeyApplyQuickSelector(selector, value, label = "") {
body: JSON.stringify({ current_period: value, language }), body: JSON.stringify({ current_period: value, language }),
}); });
hockeyStoreGameControl(gameId, response, { render: false, dispatch: true }); hockeyStoreGameControl(gameId, response, { render: false, dispatch: true });
renderHockeyQuickCommandDock(); renderHockeyQuickCommandDock({ force: true });
hockeyRefreshQuickPanelMapping().catch(() => {}); hockeyRefreshQuickPanelMapping().catch(() => {});
return response; return response;
} }
@@ -9905,7 +10047,7 @@ async function hockeyCommitQuickPanelButtonContext(button, attachedSelectors, {
await hockeySetMatchValues(patch, { refreshMapping }); await hockeySetMatchValues(patch, { refreshMapping });
} }
function renderHockeyQuickCommandDock() { function renderHockeyQuickCommandDock({ force = false } = {}) {
if (!el.runtimeButtonDock) return; if (!el.runtimeButtonDock) return;
const isHockeyProject = (state.config.components || []).some((component) => String(component?.type || "").startsWith("hockey_")); const isHockeyProject = (state.config.components || []).some((component) => String(component?.type || "").startsWith("hockey_"));
if (!isHockeyProject) { if (!isHockeyProject) {
@@ -9913,6 +10055,18 @@ function renderHockeyQuickCommandDock() {
el.runtimeButtonDock.innerHTML = ""; el.runtimeButtonDock.innerHTML = "";
return; return;
} }
const dockFocused = document.activeElement?.closest?.(".runtime-button-dock")
|| activeControlPopover?.anchor?.closest?.(".runtime-button-dock");
let dockHovered = false;
try { dockHovered = Boolean(el.runtimeButtonDock.matches(":hover")); } catch (_) {}
if (!force && (state.quickPanelResizeActive || dockFocused || dockHovered)) {
state.quickPanelRenderPending = true;
scheduleHockeyRuntimeRenderAfterInteraction();
applyRuntimeUiPreferences();
refreshQuickPanelOnAirClasses();
return;
}
state.quickPanelRenderPending = false;
el.runtimeButtonDock.classList.remove("hidden"); el.runtimeButtonDock.classList.remove("hidden");
const { tabs, buttons, selectors } = hockeyQuickPanelTabs(); const { tabs, buttons, selectors } = hockeyQuickPanelTabs();
const availableIds = new Set(tabs.map((tab) => tab.id)); const availableIds = new Set(tabs.map((tab) => tab.id));
@@ -9934,16 +10088,25 @@ function renderHockeyQuickCommandDock() {
}).join(""); }).join("");
const standaloneSelectors = selectors.filter((selector) => !selector.button_id && (activeId === "__ungrouped" ? !selector.group_id : selector.group_id === activeId)); const standaloneSelectors = selectors.filter((selector) => !selector.button_id && (activeId === "__ungrouped" ? !selector.group_id : selector.group_id === activeId));
const standaloneMarkup = standaloneSelectors.map((selector) => `<div class="quick-command-item is-selector-only">${quickPanelSelectorMarkup(selector)}</div>`).join(""); const standaloneMarkup = standaloneSelectors.map((selector) => `<div class="quick-command-item is-selector-only">${quickPanelSelectorMarkup(selector)}</div>`).join("");
el.runtimeButtonDock.innerHTML = ` const markup = `
<div class="quick-command-resize-handle" data-quick-dock-resize title="Потяните вверх или вниз · размер сохраняется для вашего аккаунта"><span></span></div>
<div class="quick-command-dock-tabs"> <div class="quick-command-dock-tabs">
<div class="quick-command-tab-scroll">${tabMarkup || `<span class="quick-command-no-tabs">Создайте вкладку для операторских кнопок</span>`}</div> <div class="quick-command-tab-scroll">${tabMarkup || `<span class="quick-command-no-tabs">Создайте вкладку для операторских кнопок</span>`}</div>
<button type="button" class="quick-command-settings" data-quick-command-settings data-tooltip="Настроить вкладки и кнопки">⚙</button> <button type="button" class="quick-command-settings" data-quick-command-settings data-tooltip="Настроить вкладки и кнопки">⚙</button>
</div> </div>
<div class="quick-command-dock-buttons">${hockeyScoreDockMarkup()}${buttonMarkup || standaloneMarkup ? `${buttonMarkup}${standaloneMarkup}` : `<span class="quick-command-empty">Во вкладке пока нет кнопок</span>`}</div> <div class="quick-command-dock-buttons">${hockeyScoreDockMarkup()}${buttonMarkup || standaloneMarkup ? `${buttonMarkup}${standaloneMarkup}` : `<span class="quick-command-empty">Во вкладке пока нет кнопок</span>`}</div>
`; `;
if (state.quickPanelMarkup === markup && el.runtimeButtonDock.childElementCount) {
applyRuntimeUiPreferences();
refreshQuickPanelOnAirClasses();
return;
}
state.quickPanelMarkup = markup;
el.runtimeButtonDock.innerHTML = markup;
scheduleStyledControls();
el.runtimeButtonDock.querySelectorAll("[data-quick-command-tab]").forEach((tab) => tab.addEventListener("click", () => { el.runtimeButtonDock.querySelectorAll("[data-quick-command-tab]").forEach((tab) => tab.addEventListener("click", () => {
state.quickPanelActiveTab = String(tab.dataset.quickCommandTab || ""); state.quickPanelActiveTab = String(tab.dataset.quickCommandTab || "");
renderHockeyQuickCommandDock(); renderHockeyQuickCommandDock({ force: true });
scheduleRuntimeScale(); scheduleRuntimeScale();
})); }));
el.runtimeButtonDock.querySelector("[data-quick-command-settings]")?.addEventListener("click", (event) => { el.runtimeButtonDock.querySelector("[data-quick-command-settings]")?.addEventListener("click", (event) => {
@@ -10007,6 +10170,8 @@ function renderHockeyQuickCommandDock() {
refreshQuickPanelOnAirClasses(); refreshQuickPanelOnAirClasses();
} }
})); }));
applyRuntimeUiPreferences();
bindQuickPanelResizeHandle();
} }
function hockeyPrematchPanelNode(component, runtime) { function hockeyPrematchPanelNode(component, runtime) {
@@ -10205,6 +10370,116 @@ function hockeyPlayerSelectionPanels() {
return normalizePlayerSelectionPanels(state.config.player_selection_panels).filter((panel) => panel.enabled !== false); return normalizePlayerSelectionPanels(state.config.player_selection_panels).filter((panel) => panel.enabled !== false);
} }
function normalisePlayerPanelTitleButtons(source) {
const raw = Array.isArray(source) ? source : [];
const used = new Set();
return raw.slice(0, 128).map((button, index) => {
const panelId = String(button?.panel_id || "").trim().slice(0, 64);
const label = String(button?.label || `Preview ${index + 1}`).trim().slice(0, 80);
let id = String(button?.id || `panel_title_${index + 1}`).trim().replace(/[^A-Za-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 64);
if (!id) id = `panel_title_${index + 1}`;
const base = id;
let suffix = 2;
while (used.has(id)) {
const ending = `_${suffix++}`;
id = `${base.slice(0, 64 - ending.length)}${ending}`;
}
used.add(id);
return {
id,
panel_id: panelId,
label,
description: String(button?.description || "").trim().slice(0, 300),
icon: String(button?.icon || "▶").trim().slice(0, 32) || "▶",
icon_only: button?.icon_only === true,
input: String(button?.input || button?.input_ref || "").trim().slice(0, 300),
enabled: button?.enabled !== false,
sort_order: Math.max(0, Number(button?.sort_order ?? index * 10) || 0),
};
}).filter((button) => button.panel_id && button.label)
.sort((a, b) => a.panel_id.localeCompare(b.panel_id, "ru") || Number(a.sort_order) - Number(b.sort_order) || a.label.localeCompare(b.label, "ru"));
}
function hockeyPlayerPanelTitleButtons(panelId) {
return normalisePlayerPanelTitleButtons(state.playerPanelTitleButtons)
.filter((button) => button.enabled !== false && button.panel_id === String(panelId || ""))
.sort((a, b) => Number(a.sort_order) - Number(b.sort_order) || a.label.localeCompare(b.label, "ru"));
}
async function hockeyLoadPlayerPanelTitleButtons({ render = false } = {}) {
try {
const payload = await hockeyGameControlRequest("/ui/player-panel-buttons");
state.playerPanelTitleButtons = normalisePlayerPanelTitleButtons(payload?.buttons || []);
state.playerPanelTitleButtonsLoaded = true;
if (render && state.activeTab === "main") renderRuntime();
return state.playerPanelTitleButtons;
} catch (error) {
console.warn("Could not load player panel title buttons", error);
state.playerPanelTitleButtonsLoaded = false;
return null;
}
}
async function hockeySavePlayerPanelTitleButtons(buttons) {
const normalised = normalisePlayerPanelTitleButtons(buttons);
try {
const payload = await hockeyGameControlRequest("/ui/player-panel-buttons", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ version: 1, buttons: normalised }),
});
state.playerPanelTitleButtons = normalisePlayerPanelTitleButtons(payload?.buttons || normalised);
state.playerPanelTitleButtonsLoaded = true;
return true;
} catch (error) {
toast(`Кнопки титров блоков: ${error.message}`, true);
return false;
}
}
async function hockeyPreviewPlayerPanelTitle(panel, button) {
if (!panel || !button || !hockeyCanControl() || state.playerPanelTitleBusy.has(panel.id)) return false;
if (!button.input) {
toast(`Для «${button.label}» не назначен vMix Input`, true);
return false;
}
const slots = Array.from({ length: panel.slots }, (_, index) => hockeyPlayerSelectionSlot(panel, index + 1));
if (!slots.some((slot) => slot.id || slot.dbId)) {
toast(`${panel.label}: сначала выберите игрока`, true);
return false;
}
state.playerPanelTitleBusy.add(panel.id);
const syncBusy = () => {
document.querySelectorAll("[data-player-panel-title-button]").forEach((node) => {
if (node.dataset.playerPanelId === panel.id) node.disabled = state.playerPanelTitleBusy.has(panel.id) || !slots.some((slot) => slot.id || slot.dbId);
});
};
syncBusy();
const gameId = hockeyTimerSelectedGameId();
try {
// Publish which panel button is being used before PreviewInput. SQL/Mapping
// can therefore distinguish several graphics that use the same selected
// player block while the player identifiers themselves stay unchanged.
await hockeySetMatchValues({
[`player_select.${panel.id}._preview_button_id`]: button.id,
[`player_select.${panel.id}._preview_button_label`]: button.label,
[`player_select.${panel.id}._preview_input`]: button.input,
}, { refreshMapping: false });
if (!(await hockeyRefreshQuickPanelMapping())) throw new Error("Не удалось обновить данные титра в vMix");
if (gameId !== hockeyTimerSelectedGameId() || !hockeyCanControl()) throw new Error("Выбранный матч изменился");
const result = await sendRuntimeVmixSequence([{ Function: "PreviewInput", Input: button.input }]);
if (!result || result.ok === false) throw new Error("Титр не отправлен в Preview");
toast(`${panel.label} · ${button.label} → Preview`);
return true;
} catch (error) {
toast(`${button.label}: ${String(error?.message || error)}`, true);
return false;
} finally {
state.playerPanelTitleBusy.delete(panel.id);
syncBusy();
}
}
function hockeyPlayerSelectionValueKey(panelId, slot, field) { function hockeyPlayerSelectionValueKey(panelId, slot, field) {
return `player_select.${panelId}.player${slot}_${field}`; return `player_select.${panelId}.player${slot}_${field}`;
} }
@@ -10433,6 +10708,7 @@ function renderHockeyPlayerSelectionWindows() {
const collapsed = hasStored ? Boolean(state.formValues[stateKey]) : Boolean(panel.collapsed_default); const collapsed = hasStored ? Boolean(state.formValues[stateKey]) : Boolean(panel.collapsed_default);
const slots = Array.from({ length: panel.slots }, (_, index) => hockeyPlayerSelectionSlot(panel, index + 1)); const slots = Array.from({ length: panel.slots }, (_, index) => hockeyPlayerSelectionSlot(panel, index + 1));
const filled = slots.filter((slot) => slot.id || slot.dbId).length; const filled = slots.filter((slot) => slot.id || slot.dbId).length;
const titleButtons = hockeyPlayerPanelTitleButtons(panel.id);
const node = document.createElement("section"); const node = document.createElement("section");
node.className = `hockey-player-select-panel ${collapsed ? "is-collapsed" : ""}`; node.className = `hockey-player-select-panel ${collapsed ? "is-collapsed" : ""}`;
node.dataset.playerPanelId = panel.id; node.dataset.playerPanelId = panel.id;
@@ -10457,9 +10733,13 @@ function renderHockeyPlayerSelectionWindows() {
</div>`; </div>`;
}).join("")} }).join("")}
</div> </div>
${filled ? `<div class="hockey-player-select-footer"><button type="button" class="hockey-player-select-prepared" data-player-panel-prepared="${escapeHtml(panel.id)}">+ В заготовки</button><button type="button" class="hockey-player-select-clear" data-player-panel-clear-all="${escapeHtml(panel.id)}">Очистить блок</button></div>` : ""} </div>
<div class="hockey-player-select-footer">
${titleButtons.length ? `<div class="hockey-player-select-title-buttons">${titleButtons.map((button) => `<button type="button" class="hockey-player-select-title-preview ${button.icon_only ? "is-icon-only" : ""}" aria-label="${escapeHtml(button.label)}" data-player-panel-title-button="${escapeHtml(button.id)}" data-player-panel-id="${escapeHtml(panel.id)}" data-tooltip="${escapeHtml(button.description || `${button.label} → Preview`)}" ${filled && !state.playerPanelTitleBusy.has(panel.id) ? "" : "disabled"}><span aria-hidden="true">${escapeHtml(button.icon)}</span>${button.icon_only ? "" : ` ${escapeHtml(button.label)}`}</button>`).join("")}</div>` : ""}
<div class="hockey-player-select-footer-tools">${filled ? `<button type="button" class="hockey-player-select-prepared" data-player-panel-prepared="${escapeHtml(panel.id)}">+ В заготовки</button><button type="button" class="hockey-player-select-clear" data-player-panel-clear-all="${escapeHtml(panel.id)}">Очистить блок</button>` : ""}<button type="button" class="hockey-player-select-configure" data-player-panel-configure="${escapeHtml(panel.id)}" data-tooltip="Настроить кнопки титров для этого блока" aria-label="Настроить кнопки титров">⚙</button></div>
</div>`; </div>`;
stack.appendChild(node); stack.appendChild(node);
node.querySelector("[data-player-panel-configure]")?.addEventListener("click", () => openHockeyPrematchButtonsEditor({ section: "panel_titles", panelId: panel.id }));
node.querySelector("[data-player-panel-collapse]")?.addEventListener("click", () => { node.querySelector("[data-player-panel-collapse]")?.addEventListener("click", () => {
state.formValues[stateKey] = !collapsed; state.formValues[stateKey] = !collapsed;
renderRuntime(); renderRuntime();
@@ -10517,6 +10797,19 @@ function renderHockeyPlayerSelectionWindows() {
})); }));
node.querySelector("[data-player-panel-prepared]")?.addEventListener("click", () => hockeyOpenPreparedFromPlayerPanel(panel)); node.querySelector("[data-player-panel-prepared]")?.addEventListener("click", () => hockeyOpenPreparedFromPlayerPanel(panel));
node.querySelector("[data-player-panel-clear-all]")?.addEventListener("click", async () => hockeyClearPlayerSelectionPanel(panel)); node.querySelector("[data-player-panel-clear-all]")?.addEventListener("click", async () => hockeyClearPlayerSelectionPanel(panel));
node.querySelectorAll("[data-player-panel-title-button]").forEach((buttonNode) => buttonNode.addEventListener("click", async (event) => {
event.preventDefault();
if (buttonNode.dataset.busy === "1") return;
const button = titleButtons.find((item) => item.id === buttonNode.dataset.playerPanelTitleButton);
if (!button) return;
buttonNode.dataset.busy = "1";
buttonNode.classList.add("is-sending");
try { await hockeyPreviewPlayerPanelTitle(panel, button); }
finally {
delete buttonNode.dataset.busy;
buttonNode.classList.remove("is-sending");
}
}));
} }
setTimeout(() => hockeyEnsurePlayerSelectionRuntimeValues().catch(() => {}), 0); setTimeout(() => hockeyEnsurePlayerSelectionRuntimeValues().catch(() => {}), 0);
return true; return true;
@@ -11423,7 +11716,8 @@ function renderStandaloneHockeyPlayByPlayWindow() {
function renderHockeyPenaltyDashboard(node, component, runtime) { function renderHockeyPenaltyDashboard(node, component, runtime) {
const board = ensureHockeyBoardState(component); const board = ensureHockeyBoardState(component);
node.innerHTML = ""; const existingLayout = runtime ? node.querySelector(".hpd-layout") : null;
if (!existingLayout) node.innerHTML = "";
node.className = "hockey-penalty-dashboard"; node.className = "hockey-penalty-dashboard";
node.style.setProperty("--hpd-home", component.props?.homeColor || "#4d9cff"); node.style.setProperty("--hpd-home", component.props?.homeColor || "#4d9cff");
node.style.setProperty("--hpd-away", component.props?.awayColor || "#ff5f79"); node.style.setProperty("--hpd-away", component.props?.awayColor || "#ff5f79");
@@ -11441,6 +11735,12 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
hockeyHistoryPanel(component) hockeyHistoryPanel(component)
); );
if (existingLayout) {
existingLayout.querySelector(".hpd-center")?.replaceWith(center);
updateHockeyBoardTickerNodes(component);
scheduleStyledControls();
return;
}
content.append( content.append(
hockeyRosterPanel(component, "home", runtime), hockeyRosterPanel(component, "home", runtime),
center, center,
@@ -13073,6 +13373,118 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
} }
} }
function normaliseRuntimeUiPreferences(payload = {}) {
const raw = Number(payload?.quick_panel_height ?? 82);
return {
quick_panel_height: clamp(Number.isFinite(raw) ? Math.round(raw) : 82, 72, 360),
};
}
function applyRuntimeUiPreferences() {
if (!el.runtimeButtonDock) return;
const prefs = normaliseRuntimeUiPreferences(state.runtimeUiPreferences);
state.runtimeUiPreferences = prefs;
const height = prefs.quick_panel_height;
el.runtimeButtonDock.style.setProperty("--runtime-button-dock-height", `${height}px`);
el.runtimeButtonDock.classList.toggle("is-expanded", height > 110);
}
async function loadRuntimeUiPreferences() {
const revision = state.runtimeUiPreferenceRevision;
try {
const payload = await hockeyGameControlRequest("/preferences/runtime-ui");
if (revision === state.runtimeUiPreferenceRevision && !state.quickPanelResizeActive) {
state.runtimeUiPreferences = normaliseRuntimeUiPreferences(payload);
}
state.runtimeUiPreferencesLoaded = true;
} catch (error) {
console.warn("Could not load runtime UI preference", error);
state.runtimeUiPreferences = normaliseRuntimeUiPreferences(state.runtimeUiPreferences);
}
applyRuntimeUiPreferences();
return state.runtimeUiPreferences;
}
async function saveRuntimeUiPreferences({ immediate = false } = {}) {
if (state.runtimeUiPreferenceSaveTimer) clearTimeout(state.runtimeUiPreferenceSaveTimer);
state.runtimeUiPreferenceSaveTimer = null;
const save = () => {
const revision = state.runtimeUiPreferenceRevision;
const preferences = normaliseRuntimeUiPreferences(state.runtimeUiPreferences);
const run = async () => {
try {
const payload = await hockeyGameControlRequest("/preferences/runtime-ui", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(preferences),
});
// Older responses must not undo a newer drag. Writes are serialized
// so the final database value also belongs to the last resize.
if (revision === state.runtimeUiPreferenceRevision && !state.quickPanelResizeActive) {
state.runtimeUiPreferences = normaliseRuntimeUiPreferences(payload);
applyRuntimeUiPreferences();
}
state.runtimeUiPreferencesLoaded = true;
return true;
} catch (error) {
toast(`Размер нижней панели: ${error.message}`, true);
return false;
}
};
const pending = state.runtimeUiPreferenceSaveQueue.catch(() => {}).then(run);
state.runtimeUiPreferenceSaveQueue = pending;
return pending;
};
if (immediate) return await save();
state.runtimeUiPreferenceSaveTimer = window.setTimeout(() => {
state.runtimeUiPreferenceSaveTimer = null;
save().catch(() => {});
}, 250);
return true;
}
function bindQuickPanelResizeHandle() {
const handle = el.runtimeButtonDock?.querySelector?.("[data-quick-dock-resize]");
if (!handle || handle.dataset.bound === "1") return;
handle.dataset.bound = "1";
handle.addEventListener("pointerdown", (event) => {
if (event.button !== undefined && event.button !== 0) return;
event.preventDefault();
const startY = event.clientY;
const startHeight = el.runtimeButtonDock?.getBoundingClientRect?.().height
|| Number(state.runtimeUiPreferences?.quick_panel_height || 82);
state.quickPanelResizeActive = true;
handle.setPointerCapture?.(event.pointerId);
const move = (moveEvent) => {
const next = clamp(Math.round(startHeight + (startY - moveEvent.clientY)), 72, 360);
state.runtimeUiPreferenceRevision += 1;
state.runtimeUiPreferences = { ...state.runtimeUiPreferences, quick_panel_height: next };
applyRuntimeUiPreferences();
scheduleRuntimeScale();
};
let finished = false;
const finish = (upEvent) => {
if (finished) return;
finished = true;
handle.removeEventListener("lostpointercapture", finish);
handle.removeEventListener("pointermove", move);
handle.removeEventListener("pointerup", finish);
handle.removeEventListener("pointercancel", finish);
try { handle.releasePointerCapture?.(upEvent.pointerId); } catch (_) {}
state.quickPanelResizeActive = false;
saveRuntimeUiPreferences({ immediate: true }).catch(() => {});
if (state.quickPanelRenderPending) {
state.quickPanelRenderPending = false;
renderHockeyQuickCommandDock({ force: true });
}
};
handle.addEventListener("pointermove", move);
handle.addEventListener("pointerup", finish);
handle.addEventListener("pointercancel", finish);
handle.addEventListener("lostpointercapture", finish);
});
}
function hockeyApplyTimerRules(payload) { function hockeyApplyTimerRules(payload) {
const component = hockeyMainTimerComponent(); const component = hockeyMainTimerComponent();
const minutes = Number(payload?.timer_rules?.minutes); const minutes = Number(payload?.timer_rules?.minutes);
@@ -13274,7 +13686,7 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
const language = hockeyGameControlLanguage(); const language = hockeyGameControlLanguage();
const payload = await hockeyGameControlRequest(`/games/${encodeURIComponent(gameId)}/control?language=${language}`); const payload = await hockeyGameControlRequest(`/games/${encodeURIComponent(gameId)}/control?language=${language}`);
hockeyStoreGameControl(gameId, payload, { render: false, dispatch: true }); hockeyStoreGameControl(gameId, payload, { render: false, dispatch: true });
if (rerender) renderRuntime(); if (rerender) renderRuntime({ background: true });
return payload; return payload;
} catch (error) { } catch (error) {
console.error("Hockey game control load failed", error); console.error("Hockey game control load failed", error);
@@ -13564,6 +13976,8 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
lastAdvantageSide: ["home", "away"].includes(savedSide) ? savedSide : "", lastAdvantageSide: ["home", "away"].includes(savedSide) ? savedSide : "",
}; };
} }
const previousBoard = state.hockeyTimerGameId === String(gameId || "")
? state.hockeyPenaltyBoards[boardComponent.action_id] : null;
const board = createHockeyBoardState(boardComponent); const board = createHockeyBoardState(boardComponent);
board.penalties = (Array.isArray(source.penalties) ? source.penalties : []) board.penalties = (Array.isArray(source.penalties) ? source.penalties : [])
.slice(0, 64) .slice(0, 64)
@@ -13574,6 +13988,12 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
board.selectedPreset = null; board.selectedPreset = null;
board.selectedEventId = null; board.selectedEventId = null;
board.historyOpen = false; board.historyOpen = false;
if (previousBoard) {
for (const key of ["search", "selectedPlayer", "selectedInfraction", "selectedPreset", "historyOpen", "infractionDropdownOpen"]) {
if (previousBoard[key] !== undefined) board[key] = previousBoard[key];
}
if (board.penalties.some((penalty) => penalty.id === previousBoard.selectedEventId)) board.selectedEventId = previousBoard.selectedEventId;
}
board.lastPersistAt = 0; board.lastPersistAt = 0;
state.hockeyPenaltyBoards[boardComponent.action_id] = board; state.hockeyPenaltyBoards[boardComponent.action_id] = board;
refreshHockeyBoardNodes(boardComponent); refreshHockeyBoardNodes(boardComponent);
@@ -14671,8 +15091,49 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
}); });
} }
function renderRuntime() { function hockeyRuntimeOperatorInteractionActive() {
if (state.quickPanelResizeActive || state.hockeyDragPlayer || state.hockeyDragInfraction || state.hockeyDragPreset) return true;
if (activeControlPopover?.anchor?.isConnected && activeControlPopover.anchor.closest?.("#runtimeView")) return true;
const active = document.activeElement;
if (active && active !== document.body) {
if (active.closest?.(".runtime-button-dock")) return true;
if (active.closest?.(".hpd-roster, .hockey-penalty-dashboard, .hockey-player-select-panel")) return true;
if (active.closest?.(".runtime-stage") && active.matches?.("input, textarea, select, [contenteditable='true']")) return true;
}
try {
if (el.runtimeButtonDock?.matches?.(":hover")) return true;
if (el.runtimeView?.querySelector?.(".hpd-roster:hover, .hockey-player-select-panel:hover")) return true;
} catch (_) {}
return false;
}
function scheduleHockeyRuntimeRenderAfterInteraction() {
state.hockeyRuntimeInteractiveRenderPending = true;
if (state.hockeyRuntimeInteractiveRenderTimer) return;
const check = () => {
state.hockeyRuntimeInteractiveRenderTimer = null;
if (!state.hockeyRuntimeInteractiveRenderPending) return;
if (hockeyRuntimeOperatorInteractionActive()) {
state.hockeyRuntimeInteractiveRenderTimer = window.setTimeout(check, 300);
return;
}
state.hockeyRuntimeInteractiveRenderPending = false;
renderRuntime({ background: true });
if (state.quickPanelRenderPending) renderHockeyQuickCommandDock();
};
state.hockeyRuntimeInteractiveRenderTimer = window.setTimeout(check, 300);
}
function renderRuntime({ background = false } = {}) {
if (!el.runtimeStage || (!state.preview && boot.mode !== "runtime")) return; if (!el.runtimeStage || (!state.preview && boot.mode !== "runtime")) return;
const gameId = String(getByPath(state.data, "hockey.selected_game.external_id") || "");
const sameView = state.runtimeRenderedGameId === gameId && state.runtimeRenderedTab === state.activeTab;
const runtimePopoverOpen = activeControlPopover?.anchor?.isConnected
&& (el.runtimeStage.contains(activeControlPopover.anchor) || activeControlPopover.anchor.closest?.(".hockey-player-select-panel"));
if (sameView && state.activeTab === "main" && (runtimePopoverOpen || (background && hockeyRuntimeOperatorInteractionActive()))) {
scheduleHockeyRuntimeRenderAfterInteraction();
return;
}
// BUILD153: never rebuild the runtime DOM underneath a settings modal. // BUILD153: never rebuild the runtime DOM underneath a settings modal.
// Incoming data is retained and rendered once after the modal closes. // Incoming data is retained and rendered once after the modal closes.
if (hockeySettingsDataRefreshPaused()) { if (hockeySettingsDataRefreshPaused()) {
@@ -14711,6 +15172,14 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
}); });
const visibleTabs = runtimeVisibleTabs(); const visibleTabs = runtimeVisibleTabs();
if (!visibleTabs.some((tab) => tab.id === state.activeTab)) state.activeTab = visibleTabs[0]?.id || "main"; if (!visibleTabs.some((tab) => tab.id === state.activeTab)) state.activeTab = visibleTabs[0]?.id || "main";
const rosterScroll = {};
el.runtimeStage.querySelectorAll(".hpd-roster").forEach((roster) => {
rosterScroll[roster.classList.contains("team-away") ? "away" : "home"] = roster.querySelector(".hpd-roster-list")?.scrollTop || 0;
});
const sideScroll = document.getElementById("hockeyRuntimeSideStack")?.scrollTop || 0;
state.runtimeRenderedGameId = gameId;
state.runtimeRenderedTab = state.activeTab;
state.hockeyRuntimeInteractiveRenderPending = false;
renderRuntimeTabs(); renderRuntimeTabs();
el.runtimeTitle.textContent = state.config.project_name; el.runtimeTitle.textContent = state.config.project_name;
el.runtimeStage.innerHTML = ""; el.runtimeStage.innerHTML = "";
@@ -14735,6 +15204,14 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
renderHockeyRuntimeSideWindows(); renderHockeyRuntimeSideWindows();
renderHockeyQuickCommandDock(); renderHockeyQuickCommandDock();
} }
if (sameView) {
Object.entries(rosterScroll).forEach(([side, top]) => {
const list = el.runtimeStage.querySelector(`.hpd-roster.team-${side} .hpd-roster-list`);
if (list) list.scrollTop = top;
});
const sideStack = document.getElementById("hockeyRuntimeSideStack");
if (sideStack) sideStack.scrollTop = sideScroll;
}
Object.entries(shootoutRosterScroll).forEach(([side, top]) => { Object.entries(shootoutRosterScroll).forEach(([side, top]) => {
const list = el.runtimeStage.querySelector(`.hso-roster.side-${side} .hso-player-list`); const list = el.runtimeStage.querySelector(`.hso-roster.side-${side} .hso-player-list`);
if (list) list.scrollTop = top; if (list) list.scrollTop = top;
@@ -16519,7 +16996,7 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
} finally { state.hockeyTimerHydrating = false; } } finally { state.hockeyTimerHydrating = false; }
if (previousRevision !== payload.revision) { if (previousRevision !== payload.revision) {
if (state.activeTab === "custom_pluses") hockeyLoadCustomPlusesWorkspace({ force: true }).catch(() => {}); if (state.activeTab === "custom_pluses") hockeyLoadCustomPlusesWorkspace({ force: true }).catch(() => {});
renderRuntime(); renderRuntime({ background: true });
} }
}); });
window.addEventListener("hockey:game-selected", (event) => { window.addEventListener("hockey:game-selected", (event) => {
@@ -16660,6 +17137,8 @@ function renderHockeyPenaltyDashboard(node, component, runtime) {
await loadSources(); await loadSources();
await loadConfig(); await loadConfig();
bindEvents(); bindEvents();
await hockeyLoadPlayerPanelTitleButtons({ render: false });
await loadRuntimeUiPreferences();
if ("ResizeObserver" in window && el.runtimeViewport) { if ("ResizeObserver" in window && el.runtimeViewport) {
state.runtimeResizeObserver = new ResizeObserver(scheduleRuntimeScale); state.runtimeResizeObserver = new ResizeObserver(scheduleRuntimeScale);
state.runtimeResizeObserver.observe(el.runtimeViewport); state.runtimeResizeObserver.observe(el.runtimeViewport);

View File

@@ -6692,9 +6692,11 @@ body.hockey-navigation-open .runtime-viewport > .runtime-sizer { margin-inline:
/* BUILD53 — persistent bottom command dock. */ /* BUILD53 — persistent bottom command dock. */
.runtime-button-dock { .runtime-button-dock {
flex: 0 0 auto; flex: 0 0 auto;
min-height: 82px; height: var(--runtime-button-dock-height, 82px);
min-height: 72px;
max-height: 360px;
display: grid; display: grid;
grid-template-rows: 31px minmax(45px, auto); grid-template-rows: 7px 31px minmax(34px, 1fr);
overflow: hidden; overflow: hidden;
border-top: 1px solid #243a52; border-top: 1px solid #243a52;
background: rgba(7, 14, 23, .985); background: rgba(7, 14, 23, .985);
@@ -6702,6 +6704,26 @@ body.hockey-navigation-open .runtime-viewport > .runtime-sizer { margin-inline:
z-index: 45; z-index: 45;
} }
.runtime-button-dock.hidden { display: none !important; } .runtime-button-dock.hidden { display: none !important; }
.quick-command-resize-handle {
display:flex;
align-items:center;
justify-content:center;
cursor:ns-resize;
touch-action:none;
user-select:none;
background:rgba(11,22,35,.98);
}
.quick-command-resize-handle span {
width:52px;
height:3px;
border-radius:999px;
background:#314a64;
transition:background .12s ease,width .12s ease;
}
.quick-command-resize-handle:hover span {
width:72px;
background:#55d9bc;
}
.quick-command-dock-tabs { .quick-command-dock-tabs {
min-width: 0; min-width: 0;
display: grid; display: grid;
@@ -6753,6 +6775,15 @@ body.hockey-navigation-open .runtime-viewport > .runtime-sizer { margin-inline:
padding: 6px 10px 8px; padding: 6px 10px 8px;
scrollbar-width: thin; scrollbar-width: thin;
} }
.runtime-button-dock.is-expanded .quick-command-dock-buttons {
flex-wrap: wrap;
align-content: flex-start;
overflow-x: hidden;
overflow-y: auto;
}
.runtime-button-dock.is-expanded .quick-command-item {
flex: 0 0 auto;
}
.quick-command-dock-buttons::-webkit-scrollbar { height: 5px; } .quick-command-dock-buttons::-webkit-scrollbar { height: 5px; }
.quick-command-dock-buttons::-webkit-scrollbar-thumb { background:#314a64; border-radius:999px; } .quick-command-dock-buttons::-webkit-scrollbar-thumb { background:#314a64; border-radius:999px; }
.quick-command-button { .quick-command-button {
@@ -6793,7 +6824,7 @@ body.hockey-navigation-open .runtime-viewport > .runtime-sizer { margin-inline:
} }
.quick-command-no-tabs,.quick-command-empty { color:#657d96; font-size:9px; font-weight:800; white-space:nowrap; } .quick-command-no-tabs,.quick-command-empty { color:#657d96; font-size:9px; font-weight:800; white-space:nowrap; }
@media (max-width:760px) { @media (max-width:760px) {
.runtime-button-dock { min-height:76px; grid-template-rows:29px minmax(41px,auto); } .runtime-button-dock { min-height:72px; grid-template-rows:7px 29px minmax(36px,1fr); }
.quick-command-button { min-width:92px; height:31px; padding-inline:10px; } .quick-command-button { min-width:92px; height:31px; padding-inline:10px; }
} }
@@ -7166,7 +7197,7 @@ body.hockey-navigation-open .runtime-viewport.has-hockey-pbp { gap: 14px !import
These sizes reduce empty chrome so the additional height is available to it. */ These sizes reduce empty chrome so the additional height is available to it. */
@media (min-width: 1500px) and (min-height: 850px) { @media (min-width: 1500px) and (min-height: 850px) {
.runtime-topbar { min-height: 58px; } .runtime-topbar { min-height: 58px; }
.runtime-button-dock { min-height: 76px; grid-template-rows: 29px minmax(41px,auto); } .runtime-button-dock { min-height: 72px; grid-template-rows: 7px 29px minmax(36px,1fr); }
.quick-command-dock-buttons { padding-block: 4px 6px; } .quick-command-dock-buttons { padding-block: 4px 6px; }
} }
@media (min-width: 1900px) and (min-height: 1000px) { @media (min-width: 1900px) and (min-height: 1000px) {
@@ -7426,6 +7457,48 @@ body.hockey-navigation-open .runtime-viewport.has-hockey-pbp { gap: 14px !import
padding-right:4px; padding-right:4px;
overscroll-behavior:contain; overscroll-behavior:contain;
} }
.panel-title-button-editor.prematch-editor-section {
min-height:0;
display:grid;
grid-template-rows:auto minmax(0,1fr);
gap:8px;
}
.panel-title-button-editor > header {
display:flex;
align-items:center;
justify-content:space-between;
gap:12px;
}
.panel-title-button-editor > header > div:first-child { min-width:0; display:grid; gap:2px; }
.panel-title-button-editor > header span { color:#48dfbd; font-size:7px; font-weight:950; letter-spacing:.08em; }
.panel-title-button-editor > header strong { font-size:12px; }
.panel-title-button-editor > header small { color:#728ba1; font-size:8px; }
.panel-title-button-editor-list {
min-height:0;
display:grid;
align-content:start;
gap:5px;
overflow:auto;
padding-right:4px;
}
.panel-title-button-editor-row {
display:grid;
grid-template-columns:24px 72px minmax(140px,1fr) minmax(110px,.8fr) minmax(140px,1fr) minmax(120px,.8fr) 56px 30px;
gap:5px;
align-items:center;
min-height:49px;
padding:4px 5px;
border:1px solid #293f55;
border-radius:8px;
background:#0c1826;
}
.panel-title-button-editor-row label { min-width:0; display:grid; gap:2px; color:#758da3; font-size:6.5px; font-weight:850; }
.panel-title-button-editor-row input,
.panel-title-button-editor-row select { min-width:0; height:26px; font-size:9px; }
.panel-title-button-editor-row .shortcut-inline-check { display:flex; align-items:center; gap:4px; white-space:nowrap; }
.panel-title-button-editor-row .shortcut-inline-check input { width:16px; height:16px; }
.panel-title-button-editor-row .mini-btn,
.panel-title-button-editor-row > .icon-btn { width:26px; min-width:26px; height:26px; padding:0; }
.hockey-player-select-slot { grid-template-columns:27px minmax(0,1fr) auto auto; } .hockey-player-select-slot { grid-template-columns:27px minmax(0,1fr) auto auto; }
.hockey-player-select-slot[draggable="true"] { cursor:grab; } .hockey-player-select-slot[draggable="true"] { cursor:grab; }
@@ -7476,12 +7549,39 @@ body.hockey-navigation-open .runtime-viewport.has-hockey-pbp { gap: 14px !import
/* BUILD84 — prepared vMix title workspace + player block handoff. */ /* BUILD84 — prepared vMix title workspace + player block handoff. */
.hockey-player-select-footer { .hockey-player-select-footer {
display:flex; display:grid;
justify-content:space-between;
align-items:center;
gap:6px; gap:6px;
margin-top:7px; margin-top:7px;
} }
.hockey-player-select-title-buttons {
display:flex;
flex-wrap:wrap;
gap:5px;
}
.hockey-player-select-title-preview {
min-height:26px;
padding:4px 8px;
color:#cfe5f5;
border:1px solid #36566f;
border-radius:7px;
background:linear-gradient(180deg,#12283b,#0b1d2c);
font-size:7px;
font-weight:950;
cursor:pointer;
}
.hockey-player-select-title-preview:hover:not(:disabled) {
color:#061713;
border-color:#54e5c4;
background:#48dfbd;
}
.hockey-player-select-title-preview:disabled { opacity:.42; cursor:not-allowed; }
.hockey-player-select-title-preview.is-sending { opacity:.7; cursor:wait; }
.hockey-player-select-footer-tools {
display:flex;
align-items:center;
justify-content:space-between;
gap:6px;
}
.hockey-player-select-prepared { .hockey-player-select-prepared {
padding:5px 8px; padding:5px 8px;
color:#071a1d; color:#071a1d;
@@ -8324,3 +8424,21 @@ body.hockey-navigation-open .runtime-viewport.has-hockey-pbp { gap: 14px !import
.ha-value strong { font-size:15px; } .ha-value strong { font-size:15px; }
.hockey-analytics .ha-notes-status { flex-wrap:wrap; } .hockey-analytics .ha-notes-status { flex-wrap:wrap; }
} }
/* BUILD165: title buttons are available even on a collapsed player panel. */
.panel-title-button-editor-row .player-selection-editor-order { grid-column: 7; grid-row: 1; }
.panel-title-button-editor-row > .icon-btn { grid-column: 8; grid-row: 1; }
.hockey-player-select-footer { padding: 0 7px 7px; }
.hockey-player-select-title-preview.is-icon-only { min-width: 32px; font-size: 17px; line-height: 1; }
.hockey-player-select-configure { margin-left:auto; border:1px solid #36566f; border-radius:6px; background:#12283b; color:#b4d2e8; cursor:pointer; padding:3px 7px; }
.runtime-button-dock .quick-command-dock-buttons { padding-block:4px 5px; }
/* Keep the icon-only option within the row on both wide and laptop screens. */
.panel-title-button-editor-row > label:nth-of-type(1) { grid-column:2; grid-row:1; }
.panel-title-button-editor-row > label:nth-of-type(2) { grid-column:3 / 5; grid-row:1; }
.panel-title-button-editor-row > label:nth-of-type(3) { grid-column:5; grid-row:1; }
.panel-title-button-editor-row > label:nth-of-type(4) { grid-column:6; grid-row:1; }
.panel-title-button-editor-row > .panel-title-button-input { grid-column:3 / 5; grid-row:2; }
.panel-title-button-editor-row > label:nth-of-type(6) { grid-column:5; grid-row:2; }
.panel-title-button-editor-row > label:nth-of-type(7) { grid-column:6 / 9; grid-row:2; }
.panel-title-button-editor-row > .panel-title-button-description { grid-column:3 / 9; grid-row:3; }