feat: refine earth hud panel behaviors and news board

This commit is contained in:
linkong
2026-04-17 17:41:15 +08:00
parent 8f3ab88743
commit 1cf1f32ddd
20 changed files with 1803 additions and 250 deletions

View File

@@ -18,6 +18,11 @@ import {
import { getShowCables } from "./cables.js";
import { toggleBGP, getShowBGP, getBGPCount } from "./bgp.js";
import { ensureTVPanelReady } from "./tv.js";
import {
ensureNewsPanelReady,
setNewsPanelVisible,
updateNewsToggleUI,
} from "./news.js";
export let autoRotate = true;
export let zoomLevel = 1.0;
@@ -31,6 +36,7 @@ const HUD_PANEL_IDS = [
"legend",
"earth-stats",
"tv-panel",
"news-panel",
"layer-toggles",
];
const DRAGGABLE_PANEL_SELECTOR = ".hud-panel-draggable";
@@ -97,6 +103,14 @@ function setHudPanelVisibility(panelId, visible) {
});
}
}
if (panelId === "news-panel") {
updateNewsToggleUI(visible);
if (visible) {
ensureNewsPanelReady().catch((error) => {
console.error("初始化态势新闻面板失败:", error);
});
}
}
}
function syncSettingsToggle(panelId, visible) {
@@ -230,7 +244,7 @@ function setupDraggableHudPanels() {
};
bindListener(handle, "pointerdown", (event) => {
if (event.target.closest(".hud-panel-close, .layer-panel-btn, .info-card-close, .tv-panel-select, .tv-panel-action, .tv-panel-player, .tv-panel-edge, .legend-bar-btn")) return;
if (event.target.closest(".hud-panel-close, .hud-panel__action, .layer-panel-btn, .info-card-close, .tv-panel-select, .tv-panel-player, .tv-panel-edge, .legend-bar-btn, .news-story-card")) return;
isDragging = true;
startPointerX = event.clientX;
startPointerY = event.clientY;
@@ -623,7 +637,7 @@ function setupLayerPanel() {
collapseBtn.title = isCollapsed ? "展开" : "折叠";
collapseBtn.setAttribute("aria-label", isCollapsed ? "展开图层列表" : "折叠图层列表");
const icon = collapseBtn.querySelector(".material-symbols-rounded");
if (icon) icon.textContent = isCollapsed ? "expand_less" : "expand_more";
if (icon) icon.textContent = isCollapsed ? "expand_more" : "expand_less";
});
if (searchInput) {
@@ -801,6 +815,14 @@ function setupTerrainControls() {
console.error("初始化电视直播面板失败:", error);
});
}
const newsVisible = !document.getElementById("news-panel")?.classList.contains("hud-panel-hidden");
updateNewsToggleUI(newsVisible);
setNewsPanelVisible(newsVisible);
if (newsVisible) {
ensureNewsPanelReady().catch((error) => {
console.error("初始化态势新闻面板失败:", error);
});
}
updateLayoutUI(container);
}

View File

@@ -0,0 +1,233 @@
const DEFAULT_COLLAPSED_CLASS = "hud-panel--collapsed";
const DEFAULT_HIDDEN_CLASS = "hud-panel-hidden";
const EXPAND_DIRECTION_BUFFER_PX = 20;
function clampExpandDirection(direction) {
return direction === "up" ? "up" : "down";
}
function resolveElement(target, root = document) {
if (!target) return null;
if (target instanceof HTMLElement) return target;
if (typeof target === "string") {
return root.querySelector(target);
}
return null;
}
function pickExpandDirection({
headerRect,
expandedHeight,
preferredDirection,
currentDirection,
}) {
const spaceAbove = Math.max(0, headerRect.top);
const spaceBelow = Math.max(0, window.innerHeight - headerRect.bottom);
const preferred = clampExpandDirection(preferredDirection);
const fitsAbove = expandedHeight <= spaceAbove;
const fitsBelow = expandedHeight <= spaceBelow;
const bufferedFitsBelow = expandedHeight + EXPAND_DIRECTION_BUFFER_PX <= spaceBelow;
const activeDirection = clampExpandDirection(currentDirection ?? preferred);
// Hysteresis:
// - if we're already in "up", keep it until bottom space drops below h
// - if we're already in "down", keep it until bottom space grows beyond h + 20
if (activeDirection === "up" && spaceBelow > expandedHeight && fitsAbove) {
return "up";
}
if (activeDirection === "down" && spaceBelow < expandedHeight + EXPAND_DIRECTION_BUFFER_PX && fitsBelow) {
return "down";
}
// Main contract:
// d = spaceBelow, h = expandedHeight
// - d > h + 20 => up
// - d <= h + 20 => down
// Only fall back when the preferred side cannot actually fit.
if (bufferedFitsBelow && fitsAbove) return "up";
if (!bufferedFitsBelow && fitsBelow) return "down";
if (fitsAbove && fitsBelow) return preferred;
if (fitsAbove) return "up";
if (fitsBelow) return "down";
return spaceAbove > spaceBelow ? "up" : "down";
}
function getCollapseButtonState({ collapsed, direction, expandLabel, collapseLabel }) {
// The arrow always describes the next action and must stay aligned with the
// real expansion direction chosen by the controller. Panels should not add
// their own extra CSS rotation on top of this mapping.
if (collapsed) {
return {
title: expandLabel,
icon: direction === "up" ? "expand_less" : "expand_more",
};
}
return {
title: collapseLabel,
icon: direction === "up" ? "expand_more" : "expand_less",
};
}
export function createHUDPanel({
panel,
header,
body,
collapseBtn,
bodyCollapsedClass = "",
preferredDirection = "down",
collapsedClass = DEFAULT_COLLAPSED_CLASS,
hiddenClass = DEFAULT_HIDDEN_CLASS,
expandLabel = "展开",
collapseLabel = "折叠",
}) {
const panelEl = resolveElement(panel);
const headerEl = resolveElement(header, panelEl ?? document);
const bodyEl = resolveElement(body, panelEl ?? document);
const collapseBtnEl = resolveElement(collapseBtn, panelEl ?? document);
if (!(panelEl instanceof HTMLElement) || !(headerEl instanceof HTMLElement) || !(bodyEl instanceof HTMLElement)) {
return {
panel: panelEl,
header: headerEl,
body: bodyEl,
collapseBtn: collapseBtnEl,
setCollapsed() {},
setVisible() {},
syncLayout() {},
destroy() {},
isCollapsed() {
return false;
},
isVisible() {
return false;
},
getExpandDirection() {
return clampExpandDirection(preferredDirection);
},
};
}
let currentDirection = clampExpandDirection(preferredDirection);
const shouldAnchorBottomDuringToggle = () =>
panelEl.dataset.dragged === "true" && typeof panelEl.style.top === "string" && panelEl.style.top !== "";
const compensateTopForBottomAnchor = (beforeBottom) => {
if (!shouldAnchorBottomDuringToggle()) return;
const afterBottom = panelEl.getBoundingClientRect().bottom;
const delta = afterBottom - beforeBottom;
if (delta === 0) return;
panelEl.style.top = `${parseFloat(panelEl.style.top) - delta}px`;
};
const syncDirection = () => {
const expandedHeight = Math.max(bodyEl.scrollHeight, bodyEl.getBoundingClientRect().height);
const nextDirection = pickExpandDirection({
headerRect: headerEl.getBoundingClientRect(),
expandedHeight,
preferredDirection,
currentDirection,
});
currentDirection = nextDirection;
panelEl.classList.toggle("hud-panel--expand-up", nextDirection === "up");
panelEl.classList.toggle("hud-panel--expand-down", nextDirection !== "up");
panelEl.dataset.expandDirection = nextDirection;
};
const syncButton = () => {
if (!(collapseBtnEl instanceof HTMLElement)) return;
const iconEl = collapseBtnEl.querySelector(".material-symbols-rounded");
const { title, icon } = getCollapseButtonState({
collapsed: panelEl.classList.contains(collapsedClass),
direction: currentDirection,
expandLabel,
collapseLabel,
});
collapseBtnEl.title = title;
collapseBtnEl.setAttribute("aria-label", title);
collapseBtnEl.dataset.expandDirection = currentDirection;
if (iconEl) {
iconEl.textContent = icon;
}
};
const syncLayout = () => {
syncDirection();
syncButton();
};
const setCollapsed = (collapsed) => {
syncDirection();
const nextCollapsed = Boolean(collapsed);
const shouldCompensate = currentDirection === "up" && shouldAnchorBottomDuringToggle();
const bottomBefore = shouldCompensate ? panelEl.getBoundingClientRect().bottom : 0;
if (shouldCompensate) {
bodyEl.style.transition = "none";
}
panelEl.classList.toggle(collapsedClass, nextCollapsed);
if (bodyCollapsedClass) {
bodyEl.classList.toggle(bodyCollapsedClass, nextCollapsed);
}
if (shouldCompensate) {
void panelEl.offsetHeight;
compensateTopForBottomAnchor(bottomBefore);
requestAnimationFrame(() => {
bodyEl.style.transition = "";
});
}
syncButton();
};
const setVisible = (visible) => {
panelEl.classList.toggle(hiddenClass, !visible);
if (visible) {
syncLayout();
}
};
const handleViewportChange = () => {
if (!panelEl.classList.contains(collapsedClass) && !panelEl.classList.contains(hiddenClass)) {
syncLayout();
}
};
window.addEventListener("resize", handleViewportChange);
document.addEventListener("pointerup", handleViewportChange);
syncLayout();
return {
panel: panelEl,
header: headerEl,
body: bodyEl,
collapseBtn: collapseBtnEl,
setCollapsed,
setVisible,
syncLayout,
destroy() {
window.removeEventListener("resize", handleViewportChange);
document.removeEventListener("pointerup", handleViewportChange);
},
isCollapsed() {
return panelEl.classList.contains(collapsedClass);
},
isVisible() {
return !panelEl.classList.contains(hiddenClass);
},
getExpandDirection() {
return currentDirection;
},
};
}
export function setupCollapsibleHudPanel(options) {
return createHUDPanel(options);
}

View File

@@ -1,3 +1,5 @@
import { createHUDPanel } from "./hud-panels.js";
const LEGEND_MODES = {
cables: { title: "海缆" },
satellites: { title: "卫星" },
@@ -5,6 +7,7 @@ const LEGEND_MODES = {
};
let currentLegendMode = "cables";
let legendPanel = null;
let legendItemsByMode = {
cables: [],
satellites: [],
@@ -12,34 +15,33 @@ let legendItemsByMode = {
};
export function initLegend() {
// Tab click → switch mode
const tabsEl = document.getElementById("legend-tabs");
if (tabsEl) {
tabsEl.addEventListener("click", (e) => {
const btn = e.target.closest(".legend-tab");
if (!btn) return;
const mode = btn.dataset.legendMode;
if (mode) setLegendMode(mode);
});
}
// Collapse toggle
const collapseBtn = document.getElementById("legend-collapse");
const legend = document.getElementById("legend");
if (collapseBtn && legend) {
legendPanel = createHUDPanel({
panel: legend,
header: ".legend-bar",
body: "#legend-body",
collapseBtn,
preferredDirection: "down",
expandLabel: "展开图例",
collapseLabel: "折叠图例",
});
collapseBtn.addEventListener("click", (e) => {
e.stopPropagation();
legend.classList.toggle("legend--collapsed");
legendPanel?.setCollapsed(!(legendPanel?.isCollapsed() ?? false));
});
}
syncCurrentLabel(currentLegendMode);
renderLegend(currentLegendMode);
}
export function setLegendMode(mode) {
const nextMode = LEGEND_MODES[mode] ? mode : "cables";
currentLegendMode = nextMode;
syncTabs(nextMode);
syncCurrentLabel(nextMode);
renderLegend(nextMode);
}
@@ -59,11 +61,10 @@ export function setLegendItems(mode, items) {
}
}
function syncTabs(mode) {
const tabs = document.querySelectorAll("#legend-tabs .legend-tab");
tabs.forEach((tab) => {
tab.classList.toggle("legend-tab--active", tab.dataset.legendMode === mode);
});
function syncCurrentLabel(mode) {
const labelEl = document.getElementById("legend-current-label");
if (!labelEl) return;
labelEl.textContent = LEGEND_MODES[mode]?.title || LEGEND_MODES.cables.title;
}
function renderLegend(mode) {

View File

@@ -127,6 +127,7 @@ import {
} from "./legend.js";
import { mountBrand } from "./brand.js";
import { initTVPanel } from "./tv.js";
import { initNewsPanel, updateNewsViewFocus } from "./news.js";
export let scene;
export let camera;
@@ -173,6 +174,7 @@ const scratchCableCenter = new THREE.Vector3();
const scratchCableDirection = new THREE.Vector3();
const scratchBGPDirection = new THREE.Vector3();
const scratchBGPWorldPosition = new THREE.Vector3();
const scratchViewCenterWorld = new THREE.Vector3();
const cleanupFns = [];
const DRAG_SMOOTHING_FACTOR = 0.18;
@@ -194,6 +196,8 @@ const HUD_INTERACTIVE_SELECTORS = [
"#earth-stats *",
"#tv-panel",
"#tv-panel *",
"#news-panel",
"#news-panel *",
];
function bindListener(target, eventName, handler, options) {
@@ -871,6 +875,20 @@ function updateStatsSummary() {
});
}
function getCurrentViewCenterCoords() {
const earth = getEarth();
if (!earth || !camera) return null;
scratchViewCenterWorld
.copy(camera.position)
.sub(earth.position)
.normalize()
.multiplyScalar(CONFIG.earthRadius);
earth.worldToLocal(scratchViewCenterWorld);
return vector3ToLatLon(scratchViewCenterWorld);
}
window.addEventListener("error", (event) => {
console.error("全局错误:", event.error);
});
@@ -889,6 +907,7 @@ export function init() {
const brandRoot = document.getElementById("brand-root");
mountBrand(brandRoot, HUD_CONFIG.brandLanguage);
initTVPanel();
initNewsPanel();
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(
@@ -1693,6 +1712,7 @@ function animate() {
updateSatellitePositions(deltaTime);
updateBreathingPhase(deltaTime);
updateRelatedSatelliteHighlights();
updateNewsViewFocus(getCurrentViewCenterCoords());
const satPositions = getSatellitePositions();
if (

View File

@@ -0,0 +1,350 @@
import { showStatusMessage } from "./ui.js";
import { createHUDPanel } from "./hud-panels.js";
const EARTH_NEWS_API = "/api/v1/news/earth-feed";
const FOCUS_UPDATE_INTERVAL_MS = 4000;
const DATA_REFRESH_INTERVAL_MS = 180000;
const MIN_REGION_SWITCH_INTERVAL_MS = 2500;
const REQUEST_TIMEOUT_MS = 15000;
let initialized = false;
let refreshPromise = null;
let payload = null;
let lastFocus = null;
let lastFetchAt = 0;
let lastRegionSwitchAt = 0;
let newsPanel = null;
function getElements() {
return {
panel: document.getElementById("news-panel"),
toggleBtn: document.getElementById("toggle-news"),
refreshBtn: document.getElementById("news-refresh"),
openBtn: document.getElementById("news-open-external"),
collapseBtn: document.getElementById("news-collapse"),
status: document.getElementById("news-board-status"),
focusLabel: document.getElementById("news-focus-label"),
focusCoords: document.getElementById("news-focus-coords"),
sourceCount: document.getElementById("news-source-count"),
regionChip: document.getElementById("news-region-chip"),
board: document.getElementById("news-board-list"),
empty: document.getElementById("news-board-empty"),
feedAnchor: document.getElementById("news-feed-anchor"),
};
}
function formatCoord(value, positiveLabel, negativeLabel) {
const abs = Math.abs(value).toFixed(1);
return `${abs}°${value >= 0 ? positiveLabel : negativeLabel}`;
}
function formatRelativeTime(raw) {
if (!raw) return "刚刚同步";
const date = new Date(raw);
if (Number.isNaN(date.getTime())) return "刚刚同步";
const diff = Date.now() - date.getTime();
const minutes = Math.max(1, Math.round(diff / 60000));
if (minutes < 60) return `${minutes} 分钟前`;
const hours = Math.round(minutes / 60);
if (hours < 24) return `${hours} 小时前`;
const days = Math.round(hours / 24);
return `${days} 天前`;
}
export function updateNewsToggleUI(visible) {
const { toggleBtn } = getElements();
if (!toggleBtn) return;
toggleBtn.classList.toggle("active", visible);
const tooltip = toggleBtn.querySelector(".earth-toolbar-tooltip");
if (tooltip) {
tooltip.textContent = visible ? "关闭态势新闻" : "打开态势新闻";
}
}
function syncSettingsToggle(visible) {
const input = document.querySelector('[data-settings-panel="news-panel"]');
if (input instanceof HTMLInputElement) {
input.checked = visible;
}
}
export function setNewsPanelVisible(visible) {
const { panel } = getElements();
if (!panel) return;
newsPanel?.setVisible(visible);
updateNewsToggleUI(visible);
syncSettingsToggle(visible);
}
function renderEmptyState(message) {
const { board, empty, status, openBtn } = getElements();
if (board) board.innerHTML = "";
if (empty) {
empty.hidden = false;
empty.textContent = message;
}
if (status) {
status.textContent = "等待聚合新闻源";
}
if (openBtn) openBtn.disabled = true;
}
function renderPayload(nextPayload) {
payload = nextPayload;
const {
board,
empty,
status,
focusLabel,
focusCoords,
sourceCount,
regionChip,
openBtn,
feedAnchor,
} = getElements();
if (!board || !status || !focusLabel || !focusCoords || !sourceCount || !regionChip) {
return;
}
const items = Array.isArray(nextPayload?.items) ? nextPayload.items : [];
const sources = Array.isArray(nextPayload?.sources) ? nextPayload.sources : [];
const focus = nextPayload?.focus || {};
focusLabel.textContent = focus.label || "全球焦点";
regionChip.textContent = focus.region || "global";
regionChip.style.setProperty("--news-accent", focus.accent || "#d6e6ff");
if (typeof focus.lat === "number" && typeof focus.lon === "number") {
focusCoords.textContent = `${formatCoord(focus.lat, "N", "S")} · ${formatCoord(focus.lon, "E", "W")}`;
} else {
focusCoords.textContent = "跟随当前视角自动聚焦";
}
sourceCount.textContent = `${sources.length} 路聚合源`;
if (nextPayload?.stale) {
status.textContent = `当前显示最近一次可用新闻缓存,共 ${items.length}`;
} else {
status.textContent = nextPayload?.errors?.length
? `已聚合 ${items.length} 条,部分源不可用`
: `已聚合 ${items.length} 条态势新闻`;
}
if (feedAnchor) {
const matchedSource = sources.find((source) => source.region === focus.region) || sources[0];
feedAnchor.href = matchedSource?.homepage_url || "https://news.google.com/";
}
if (openBtn) {
openBtn.disabled = !feedAnchor?.href;
}
if (items.length === 0) {
board.innerHTML = "";
if (empty) {
empty.hidden = false;
empty.textContent = "当前未拉到可用新闻,请稍后刷新或切换视角区域。";
}
return;
}
if (empty) empty.hidden = true;
board.innerHTML = items
.map((item) => {
const cardClass = item.is_focus_match
? "news-story-card news-story-card--focus"
: "news-story-card";
const summary = item.summary
? `<div class="news-story-summary">${item.summary}</div>`
: "";
return `
<a class="${cardClass}" href="${item.url}" target="_blank" rel="noreferrer noopener">
<div class="news-story-meta">
<span class="news-story-source">${item.source}</span>
<span class="news-story-time">${formatRelativeTime(item.published_at)}</span>
</div>
<div class="news-story-title">${item.title}</div>
${summary}
<div class="news-story-tags">
<span class="news-story-tag">${item.region}</span>
<span class="news-story-tag">${item.feed_name}</span>
</div>
</a>
`;
})
.join("");
}
async function fetchNews(lat, lon) {
const url = new URL(EARTH_NEWS_API, window.location.origin);
if (typeof lat === "number") url.searchParams.set("lat", lat.toFixed(4));
if (typeof lon === "number") url.searchParams.set("lon", lon.toFixed(4));
const controller = new AbortController();
const timeoutId = window.setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
const response = await fetch(url.toString(), {
cache: "no-store",
signal: controller.signal,
}).finally(() => {
window.clearTimeout(timeoutId);
});
if (!response.ok) {
throw new Error(`新闻源请求失败: ${response.status}`);
}
return response.json();
}
async function refreshNews(lat, lon, { silent = false } = {}) {
if (refreshPromise) return refreshPromise;
const { status } = getElements();
if (status) {
status.textContent = "正在同步全球态势新闻...";
}
refreshPromise = fetchNews(lat, lon)
.then((nextPayload) => {
renderPayload(nextPayload);
lastFetchAt = Date.now();
if (Array.isArray(nextPayload?.items) && nextPayload.items.length === 0) {
const { status } = getElements();
if (status) {
status.textContent = "当前区域暂无可用新闻,已完成一次聚合尝试";
}
}
return nextPayload;
})
.catch((error) => {
console.error("加载 Earth RSS 新闻失败:", error);
const message = error?.name === "AbortError"
? "新闻聚合请求超时,请稍后重试"
: `新闻聚合暂时不可用: ${error?.message || "未知错误"}`;
if (!payload) {
renderEmptyState(message);
} else if (!silent) {
showStatusMessage("态势新闻同步失败", "error");
}
throw error;
})
.finally(() => {
refreshPromise = null;
});
return refreshPromise;
}
function shouldRefreshForFocus(lat, lon, region) {
const now = Date.now();
if (!lastFocus) return true;
if (region !== lastFocus.region && now - lastRegionSwitchAt > MIN_REGION_SWITCH_INTERVAL_MS) {
lastRegionSwitchAt = now;
return true;
}
if (now - lastFetchAt > DATA_REFRESH_INTERVAL_MS) return true;
if (now - (lastFocus.updatedAt || 0) < FOCUS_UPDATE_INTERVAL_MS) return false;
const latDrift = Math.abs((lat || 0) - (lastFocus.lat || 0));
const lonDrift = Math.abs((lon || 0) - (lastFocus.lon || 0));
return latDrift >= 18 || lonDrift >= 25;
}
function inferRegion(lat, lon) {
if (typeof lat !== "number" || typeof lon !== "number") return "global";
if (lon >= -170 && lon <= -30) return "americas";
if (lon > -30 && lon <= 45) return lat >= 30 ? "europe" : "middle-east-africa";
if (lon > 45 && lon <= 150) return lat < 10 ? "middle-east-africa" : "asia-pacific";
return "asia-pacific";
}
function openCurrentSourceHomepage() {
const { feedAnchor } = getElements();
if (feedAnchor?.href) {
window.open(feedAnchor.href, "_blank", "noopener,noreferrer");
}
}
function setCollapsed(collapsed) {
newsPanel?.setCollapsed(collapsed);
}
export function updateNewsViewFocus(coords) {
if (!initialized) return;
if (!coords || typeof coords.lat !== "number" || typeof coords.lon !== "number") return;
const region = inferRegion(coords.lat, coords.lon);
const nextFocus = {
lat: coords.lat,
lon: coords.lon,
region,
updatedAt: Date.now(),
};
const shouldRefresh = shouldRefreshForFocus(coords.lat, coords.lon, region);
lastFocus = nextFocus;
if (shouldRefresh) {
refreshNews(coords.lat, coords.lon, { silent: true }).catch(() => {});
}
}
export async function ensureNewsPanelReady() {
if (!initialized) {
initNewsPanel();
}
if (!payload) {
await refreshNews(lastFocus?.lat, lastFocus?.lon);
}
return payload;
}
export function initNewsPanel() {
if (initialized) return;
initialized = true;
const { panel, toggleBtn, refreshBtn, openBtn, collapseBtn } = getElements();
if (panel && collapseBtn) {
newsPanel = createHUDPanel({
panel,
header: ".hud-panel__header",
body: "#news-panel-body",
collapseBtn,
preferredDirection: "down",
expandLabel: "展开新闻面板",
collapseLabel: "折叠新闻面板",
});
}
updateNewsToggleUI(true);
syncSettingsToggle(true);
renderEmptyState("正在准备全球态势新闻聚合源...");
toggleBtn?.addEventListener("click", async () => {
const nextVisible = !(newsPanel?.isVisible() ?? false);
setNewsPanelVisible(nextVisible);
if (nextVisible) {
try {
await ensureNewsPanelReady();
} catch {
// surface already handled
}
}
});
refreshBtn?.addEventListener("click", async () => {
try {
await refreshNews(lastFocus?.lat, lastFocus?.lon);
showStatusMessage("态势新闻已刷新", "info");
} catch {
showStatusMessage("态势新闻刷新失败", "error");
}
});
openBtn?.addEventListener("click", openCurrentSourceHomepage);
collapseBtn?.addEventListener("click", (event) => {
event.stopPropagation();
setCollapsed(!newsPanel?.isCollapsed());
});
refreshNews(undefined, undefined, { silent: true }).catch(() => {});
}

View File

@@ -1,5 +1,6 @@
import Hls from "hls.js";
import { showStatusMessage } from "./ui.js";
import { createHUDPanel } from "./hud-panels.js";
const TV_STREAMS_API = "/api/v1/tv/streams";
const TV_PROXY_API = "/api/v1/tv/proxy";
@@ -21,6 +22,7 @@ let refreshPromise = null;
let hlsPlayer = null;
let hlsRecoveryAttempts = 0;
let metaAutoCollapseTimer = null;
let tvPanel = null;
const failedSourceIds = new Set();
let probeTimer = null;
@@ -58,36 +60,7 @@ function getElements() {
}
function setMetaCollapsed(collapsed) {
const { metaWrap, metaToggle, panel } = getElements();
if (!metaWrap) return;
const isDragged = panel?.dataset.dragged === "true" && panel.style.top;
if (isDragged) {
// Top-anchored panel: toggle instantly and compensate top so the player
// (panel bottom) stays visually fixed.
const bottomBefore = panel.getBoundingClientRect().bottom;
metaWrap.style.transition = "none";
metaWrap.classList.toggle("is-collapsed", collapsed);
metaToggle?.classList.toggle("is-collapsed", collapsed);
// Force synchronous reflow to get updated panel height
void panel.offsetHeight;
const delta = panel.getBoundingClientRect().bottom - bottomBefore;
if (delta !== 0) {
panel.style.top = `${parseFloat(panel.style.top) - delta}px`;
}
// Restore CSS transition after this paint
requestAnimationFrame(() => {
metaWrap.style.transition = "";
});
} else {
metaWrap.classList.toggle("is-collapsed", collapsed);
metaToggle?.classList.toggle("is-collapsed", collapsed);
}
tvPanel?.setCollapsed(collapsed);
}
function autoExpandMeta() {
@@ -209,7 +182,7 @@ function syncSettingsToggle(visible) {
function setPanelVisible(visible) {
const { panel } = getElements();
if (!panel) return;
panel.classList.toggle("hud-panel-hidden", !visible);
tvPanel?.setVisible(visible);
updateToggleButton(visible);
syncSettingsToggle(visible);
}
@@ -679,15 +652,28 @@ export function initTVPanel() {
if (initialized) return;
initialized = true;
const { select, refreshBtn, iframe, video, toggleBtn, panel } = getElements();
const { select, refreshBtn, iframe, video, toggleBtn, panel, metaToggle } = getElements();
updateToggleButton(!panel?.classList.contains("hud-panel-hidden"));
syncSettingsToggle(!panel?.classList.contains("hud-panel-hidden"));
if (panel && metaToggle) {
tvPanel = createHUDPanel({
panel,
header: ".hud-panel__header",
body: "#tv-meta-wrap",
collapseBtn: metaToggle,
bodyCollapsedClass: "is-collapsed",
preferredDirection: "up",
expandLabel: "展开新闻直播信息",
collapseLabel: "折叠新闻直播信息",
});
}
updateToggleButton(tvPanel?.isVisible() ?? !panel?.classList.contains("hud-panel-hidden"));
syncSettingsToggle(tvPanel?.isVisible() ?? !panel?.classList.contains("hud-panel-hidden"));
toggleBtn?.addEventListener("click", async (event) => {
event.preventDefault();
event.stopPropagation();
const nextVisible = panel?.classList.contains("hud-panel-hidden") ?? true;
const nextVisible = !(tvPanel?.isVisible() ?? false);
setPanelVisible(nextVisible);
if (nextVisible) {
await ensureTVPanelReady();
@@ -704,10 +690,9 @@ export function initTVPanel() {
renderSource(findSourceById(currentSourceId));
});
const { metaToggle } = getElements();
metaToggle?.addEventListener("click", () => {
clearTimeout(metaAutoCollapseTimer);
const isNowCollapsed = !metaToggle.classList.contains("is-collapsed");
const isNowCollapsed = !(tvPanel?.isCollapsed() ?? false);
setMetaCollapsed(isNowCollapsed);
});