feat: instance embed SSE live push and lighter tab revisit

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-07-07 11:01:10 +08:00
parent 444088baf3
commit 3db84d07e3
9 changed files with 288 additions and 25 deletions
+94
View File
@@ -0,0 +1,94 @@
/**
* embed 壳:SSE 收到后台 tick 后拉 JSON 快照更新 DOM,切换 tab 不再重复请求 HTML。
*/
(function (global) {
let liveEventSource = null;
let liveReconnectTimer = null;
let localLiveVersion = -1;
let sseConnected = false;
function isEmbedShell() {
return document.body && document.body.getAttribute("data-embed-shell") === "1";
}
function currentTab() {
if (global.InstanceEmbed && typeof global.InstanceEmbed.getTab === "function") {
return global.InstanceEmbed.getTab();
}
return document.body.getAttribute("data-page") || "trade";
}
function refreshTabData(tab, opts) {
const options = opts || {};
if (typeof global.refreshAccountSnapshot === "function") {
global.refreshAccountSnapshot();
}
if (typeof global.refreshPriceSnapshotConditional === "function") {
global.refreshPriceSnapshotConditional();
}
if (tab === "options" && global.OptionsPanelLive && typeof global.OptionsPanelLive.refreshSoft === "function") {
global.OptionsPanelLive.refreshSoft(options);
}
}
function onLiveEvent(data) {
const ver = Number(data && data.live_version) || 0;
if (!ver || ver === localLiveVersion) return;
localLiveVersion = ver;
refreshTabData(currentTab(), { silent: true });
}
function closeLiveStream() {
if (liveEventSource) {
liveEventSource.close();
liveEventSource = null;
}
if (liveReconnectTimer) {
clearTimeout(liveReconnectTimer);
liveReconnectTimer = null;
}
sseConnected = false;
}
function connectLiveStream() {
if (!isEmbedShell()) return;
closeLiveStream();
liveEventSource = new EventSource("/api/instance/live/stream");
liveEventSource.addEventListener("live", function (ev) {
try {
onLiveEvent(JSON.parse(ev.data || "{}"));
} catch (_) {}
});
liveEventSource.onopen = function () {
sseConnected = true;
};
liveEventSource.onerror = function () {
sseConnected = false;
closeLiveStream();
liveReconnectTimer = setTimeout(function () {
connectLiveStream();
refreshTabData(currentTab(), { silent: true });
}, 8000);
};
}
function startLive() {
if (!isEmbedShell()) return;
refreshTabData(currentTab());
connectLiveStream();
}
global.InstanceLive = {
start: startLive,
refreshTabData: refreshTabData,
isConnected: function () {
return sseConnected;
},
};
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", startLive);
} else {
startLive();
}
})(typeof window !== "undefined" ? window : globalThis);