mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(panel): upgrade modular dashboard UI, 6-segment context meter, and consumption analytics
This commit is contained in:
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* @fileoverview Vue-inspired lightweight component kernel supporting
|
||||
* props, custom v-model value transmission (emit('update:modelValue', val)),
|
||||
* reactive subscriptions, and lifecycle cleanup.
|
||||
*/
|
||||
|
||||
const globalEmitListeners = new Set();
|
||||
|
||||
export function onComponentEmit(listener) {
|
||||
globalEmitListeners.add(listener);
|
||||
return () => globalEmitListeners.delete(listener);
|
||||
}
|
||||
|
||||
export function defineComponent({ name, setup }) {
|
||||
return function createInstance(initialProps = {}) {
|
||||
let props = { ...initialProps };
|
||||
const cleanups = [];
|
||||
const eventHandlers = new Map();
|
||||
|
||||
function on(event, fn) {
|
||||
if (!eventHandlers.has(event)) {
|
||||
eventHandlers.set(event, new Set());
|
||||
}
|
||||
eventHandlers.get(event).add(fn);
|
||||
return () => eventHandlers.get(event)?.delete(fn);
|
||||
}
|
||||
|
||||
function emit(event, payload) {
|
||||
// Support Vue-style onUpdateModelValue / onChange prop callbacks
|
||||
if (event === 'update:modelValue') {
|
||||
if (typeof props.onUpdateModelValue === 'function') {
|
||||
props.onUpdateModelValue(payload);
|
||||
}
|
||||
if (typeof props.onChange === 'function') {
|
||||
props.onChange(payload);
|
||||
}
|
||||
}
|
||||
const handlers = eventHandlers.get(event);
|
||||
if (handlers) {
|
||||
for (const fn of handlers) {
|
||||
fn(payload);
|
||||
}
|
||||
}
|
||||
for (const observer of globalEmitListeners) {
|
||||
observer({
|
||||
component: name || 'AnonymousComponent',
|
||||
event,
|
||||
payload,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function onCleanup(fn) {
|
||||
if (typeof fn === 'function') {
|
||||
cleanups.push(fn);
|
||||
}
|
||||
}
|
||||
|
||||
const setupResult = setup({
|
||||
getProps: () => props,
|
||||
emit,
|
||||
onCleanup,
|
||||
});
|
||||
|
||||
function setProps(nextProps = {}) {
|
||||
props = { ...props, ...nextProps };
|
||||
if (typeof setupResult.onPropsChange === 'function') {
|
||||
setupResult.onPropsChange(props);
|
||||
}
|
||||
}
|
||||
|
||||
function setValue(nextValue) {
|
||||
setProps({ modelValue: nextValue });
|
||||
}
|
||||
|
||||
function getValue() {
|
||||
return typeof setupResult.getValue === 'function'
|
||||
? setupResult.getValue()
|
||||
: props.modelValue;
|
||||
}
|
||||
|
||||
function destroy() {
|
||||
for (const fn of cleanups.splice(0)) {
|
||||
try {
|
||||
fn();
|
||||
} catch (err) {
|
||||
console.error(`[${name}] cleanup error:`, err);
|
||||
}
|
||||
}
|
||||
if (setupResult.el?.parentNode) {
|
||||
setupResult.el.parentNode.removeChild(setupResult.el);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
name,
|
||||
el: setupResult.el,
|
||||
refs: setupResult.refs || {},
|
||||
on,
|
||||
emit,
|
||||
setProps,
|
||||
setValue,
|
||||
getValue,
|
||||
destroy,
|
||||
...setupResult.methods,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* @fileoverview Incremental DOM patching utilities and keyed list reconciler.
|
||||
* Prevents full innerHTML replacements and preserves active DOM element state.
|
||||
*/
|
||||
|
||||
export function h(tag, props = {}, children = []) {
|
||||
const el = document.createElement(tag);
|
||||
if (props) {
|
||||
for (const [key, val] of Object.entries(props)) {
|
||||
if (val === undefined || val === null || val === false) continue;
|
||||
if (key === 'className' || key === 'class') {
|
||||
el.className = String(val);
|
||||
} else if (key === 'dataset' && typeof val === 'object') {
|
||||
for (const [dk, dv] of Object.entries(val)) {
|
||||
if (dv !== undefined && dv !== null) {
|
||||
el.dataset[dk] = String(dv);
|
||||
}
|
||||
}
|
||||
} else if (key.startsWith('on') && typeof val === 'function') {
|
||||
const evt = key.slice(2).toLowerCase();
|
||||
el.addEventListener(evt, val);
|
||||
} else if (key === 'text') {
|
||||
el.textContent = String(val);
|
||||
} else if (val === true) {
|
||||
el.setAttribute(key, '');
|
||||
} else {
|
||||
el.setAttribute(key, String(val));
|
||||
}
|
||||
}
|
||||
}
|
||||
const childArray = Array.isArray(children) ? children : [children];
|
||||
for (const child of childArray) {
|
||||
if (child === null || child === undefined || child === false) continue;
|
||||
if (typeof child === 'string' || typeof child === 'number') {
|
||||
el.appendChild(document.createTextNode(String(child)));
|
||||
} else {
|
||||
el.appendChild(child);
|
||||
}
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
export function patchText(el, nextValue) {
|
||||
if (!el) return false;
|
||||
const nextStr = String(nextValue ?? '');
|
||||
if (el.textContent === nextStr) {
|
||||
return false;
|
||||
}
|
||||
el.textContent = nextStr;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function patchAttr(el, attrName, nextValue) {
|
||||
if (!el) return false;
|
||||
if (nextValue === null || nextValue === undefined || nextValue === false) {
|
||||
if (!el.hasAttribute(attrName)) {
|
||||
return false;
|
||||
}
|
||||
el.removeAttribute(attrName);
|
||||
return true;
|
||||
}
|
||||
const strVal = nextValue === true ? '' : String(nextValue);
|
||||
if (el.getAttribute(attrName) === strVal) {
|
||||
return false;
|
||||
}
|
||||
el.setAttribute(attrName, strVal);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function patchClasses(el, classMap) {
|
||||
if (!el || !classMap) return false;
|
||||
let mutated = false;
|
||||
for (const [cls, active] of Object.entries(classMap)) {
|
||||
if (!cls) continue;
|
||||
const has = el.classList.contains(cls);
|
||||
const shouldHave = Boolean(active);
|
||||
if (has !== shouldHave) {
|
||||
el.classList.toggle(cls, shouldHave);
|
||||
mutated = true;
|
||||
}
|
||||
}
|
||||
return mutated;
|
||||
}
|
||||
|
||||
export function patchStyleVar(el, varName, nextValue) {
|
||||
if (!el) return false;
|
||||
const strVal = String(nextValue ?? '');
|
||||
const prev = el.style.getPropertyValue(varName);
|
||||
if (prev === strVal) {
|
||||
return false;
|
||||
}
|
||||
el.style.setProperty(varName, strVal);
|
||||
return true;
|
||||
}
|
||||
|
||||
const keyedListState = new WeakMap();
|
||||
|
||||
/**
|
||||
* Keyed incremental list reconciler.
|
||||
* Reuses existing DOM nodes by key and patches only changed items in-place.
|
||||
*/
|
||||
export function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow }) {
|
||||
if (!container) return;
|
||||
let map = keyedListState.get(container);
|
||||
if (!map) {
|
||||
map = new Map();
|
||||
keyedListState.set(container, map);
|
||||
}
|
||||
|
||||
const nextKeys = new Set();
|
||||
const orderedNodes = [];
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
const key = String(keyFn(item, i));
|
||||
const sig = sigFn ? String(sigFn(item, i)) : JSON.stringify(item);
|
||||
nextKeys.add(key);
|
||||
|
||||
let record = map.get(key);
|
||||
if (!record) {
|
||||
const created = createRow(item, i);
|
||||
record = {
|
||||
el: created.el,
|
||||
refs: created.refs,
|
||||
sig,
|
||||
};
|
||||
updateRow(record.refs, item, i, record.el);
|
||||
map.set(key, record);
|
||||
} else if (record.sig !== sig) {
|
||||
record.sig = sig;
|
||||
updateRow(record.refs, item, i, record.el);
|
||||
}
|
||||
orderedNodes.push(record.el);
|
||||
}
|
||||
|
||||
// Remove stale keys
|
||||
for (const [oldKey, record] of map.entries()) {
|
||||
if (!nextKeys.has(oldKey)) {
|
||||
if (record.el.parentNode === container) {
|
||||
container.removeChild(record.el);
|
||||
}
|
||||
map.delete(oldKey);
|
||||
}
|
||||
}
|
||||
|
||||
// Reorder or insert nodes with minimal DOM moves
|
||||
for (let i = 0; i < orderedNodes.length; i++) {
|
||||
const targetNode = orderedNodes[i];
|
||||
const currentNode = container.children[i] || null;
|
||||
if (currentNode !== targetNode) {
|
||||
container.insertBefore(targetNode, currentNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* @fileoverview Pure formatting utilities for speed metrics, token counts,
|
||||
* USD estimates, countdown timers, and custom datetime displays.
|
||||
*/
|
||||
|
||||
export function formatMetric(value, unit = '') {
|
||||
return Number.isFinite(value) ? `${value.toFixed(1)}${unit}` : '—';
|
||||
}
|
||||
|
||||
export function formatTokens(num) {
|
||||
const n = Number(num || 0);
|
||||
if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`;
|
||||
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
||||
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
|
||||
return String(Math.round(n));
|
||||
}
|
||||
|
||||
export function formatTokensPrecise(num) {
|
||||
const n = Number(num || 0);
|
||||
if (n <= 0) return '0';
|
||||
if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`;
|
||||
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2)}M`;
|
||||
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
|
||||
return String(Math.round(n));
|
||||
}
|
||||
|
||||
export function formatCnyApprox(usdAmount, rate = 7.2) {
|
||||
const rmb = Number(usdAmount || 0) * rate;
|
||||
if (rmb <= 0) return '≈ ¥0';
|
||||
if (rmb >= 10) return `≈ ¥${Math.round(rmb)}`;
|
||||
return `≈ ¥${rmb.toFixed(1)}`;
|
||||
}
|
||||
|
||||
export function formatDateSpanBadge(startMs, endMs) {
|
||||
const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date();
|
||||
const e = endMs && Number.isFinite(endMs) ? new Date(endMs) : new Date();
|
||||
return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`;
|
||||
}
|
||||
|
||||
export function formatUsd(amount, { precise = false, estimated = false } = {}) {
|
||||
const val = Number(amount || 0);
|
||||
const prefix = estimated ? '≈$' : '$';
|
||||
if (precise) {
|
||||
return val >= 1 ? `${prefix}${val.toFixed(2)}` : `${prefix}${val.toFixed(3)}`;
|
||||
}
|
||||
return `${prefix}${val.toFixed(2)}`;
|
||||
}
|
||||
|
||||
export function speedReasonText(reason) {
|
||||
return ({
|
||||
compaction: '自动压缩不计测速',
|
||||
incomplete_or_invalid_timing: '未完成或计时缺失',
|
||||
invalid_output_tokens: '输出 Token 计数无效',
|
||||
inconsistent_timing: '原生首响应与总计时不一致',
|
||||
short_timing: '计时过短,暂不测速',
|
||||
short_sample: '短样本,不计均速',
|
||||
legacy_cache: '旧缓存,等待重新读取',
|
||||
})[reason] || '';
|
||||
}
|
||||
|
||||
export function sampleSummary(summary) {
|
||||
const valid = summary?.sampleCount || 0;
|
||||
const excluded = summary?.excludedCount || 0;
|
||||
return `${valid}/${valid + excluded} 步`;
|
||||
}
|
||||
|
||||
export function formatCountdown(isoTime, nowMs = Date.now()) {
|
||||
if (!isoTime) return '未知重置时间';
|
||||
const targetMs = Date.parse(isoTime);
|
||||
if (!targetMs || Number.isNaN(targetMs)) return '未知重置时间';
|
||||
const diffMs = targetMs - nowMs;
|
||||
if (diffMs <= 0) return '即将重置';
|
||||
|
||||
const totalMinutes = Math.floor(diffMs / 60000);
|
||||
const days = Math.floor(totalMinutes / (60 * 24));
|
||||
const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
|
||||
const minutes = totalMinutes % 60;
|
||||
|
||||
if (days > 0) return `${days}天 ${hours}小时后重置`;
|
||||
if (hours > 0) return `${hours}小时 ${minutes}分后重置`;
|
||||
return `${minutes}分钟后重置`;
|
||||
}
|
||||
|
||||
export function formatCompactDateTime(ms) {
|
||||
if (!ms || !Number.isFinite(ms)) return '选择时间';
|
||||
const d = new Date(ms);
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
export function escapeHtml(str) {
|
||||
return String(str || '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* @fileoverview Async HTTP client with AbortController cancellation for stale
|
||||
* polling requests and concurrent GET deduplication.
|
||||
*/
|
||||
|
||||
const inFlightGets = new Map();
|
||||
const activeControllers = new Map();
|
||||
|
||||
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}) {
|
||||
const upperMethod = method.toUpperCase();
|
||||
const dedupKey = upperMethod === 'GET' && !abortKey ? path : '';
|
||||
|
||||
if (dedupKey && inFlightGets.has(dedupKey)) {
|
||||
return inFlightGets.get(dedupKey);
|
||||
}
|
||||
|
||||
let signal;
|
||||
if (abortKey && typeof AbortController !== 'undefined') {
|
||||
const prev = activeControllers.get(abortKey);
|
||||
if (prev) {
|
||||
prev.abort();
|
||||
}
|
||||
const controller = new AbortController();
|
||||
activeControllers.set(abortKey, controller);
|
||||
signal = controller.signal;
|
||||
}
|
||||
|
||||
const runRequest = async () => {
|
||||
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
|
||||
const fetchFn = sidecar?.fetch
|
||||
? sidecar.fetch.bind(sidecar)
|
||||
: globalThis.fetch.bind(globalThis);
|
||||
|
||||
const res = await fetchFn(path, {
|
||||
method: upperMethod,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
if (signal?.aborted) {
|
||||
const abortErr = new Error('Request aborted');
|
||||
abortErr.name = 'AbortError';
|
||||
throw abortErr;
|
||||
}
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (signal?.aborted) {
|
||||
const abortErr = new Error('Request aborted');
|
||||
abortErr.name = 'AbortError';
|
||||
throw abortErr;
|
||||
}
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || `HTTP ${res.status}`);
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
const promise = runRequest().finally(() => {
|
||||
if (dedupKey) {
|
||||
inFlightGets.delete(dedupKey);
|
||||
}
|
||||
});
|
||||
|
||||
if (dedupKey) {
|
||||
inFlightGets.set(dedupKey, promise);
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* @fileoverview Fine-grained reactive store with async microtask batching
|
||||
* and structural slice comparison to prevent full-page re-renders.
|
||||
*/
|
||||
|
||||
const pendingJobs = new Set();
|
||||
let isFlushPending = false;
|
||||
|
||||
export function scheduleAsyncJob(job) {
|
||||
pendingJobs.add(job);
|
||||
if (!isFlushPending) {
|
||||
isFlushPending = true;
|
||||
queueMicrotask(flushAsyncJobs);
|
||||
}
|
||||
}
|
||||
|
||||
export function flushAsyncJobs() {
|
||||
isFlushPending = false;
|
||||
const jobs = Array.from(pendingJobs);
|
||||
pendingJobs.clear();
|
||||
for (const job of jobs) {
|
||||
job();
|
||||
}
|
||||
}
|
||||
|
||||
export function isShallowEqual(a, b) {
|
||||
if (Object.is(a, b)) return true;
|
||||
if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
|
||||
return false;
|
||||
}
|
||||
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
||||
if (Array.isArray(a)) {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (!Object.is(a[i], b[i])) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
const keysA = Object.keys(a);
|
||||
const keysB = Object.keys(b);
|
||||
if (keysA.length !== keysB.length) return false;
|
||||
for (const k of keysA) {
|
||||
if (!Object.prototype.hasOwnProperty.call(b, k) || !Object.is(a[k], b[k])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function createReactiveStore(initialState) {
|
||||
let state = { ...initialState };
|
||||
const subscribers = new Set();
|
||||
|
||||
function getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
function setState(patchOrUpdater, { sync = false } = {}) {
|
||||
const patch = typeof patchOrUpdater === 'function' ? patchOrUpdater(state) : patchOrUpdater;
|
||||
if (!patch || typeof patch !== 'object') return;
|
||||
|
||||
let changed = false;
|
||||
const nextState = { ...state };
|
||||
for (const [k, v] of Object.entries(patch)) {
|
||||
if (!Object.is(state[k], v)) {
|
||||
nextState[k] = v;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (!changed) {
|
||||
return;
|
||||
}
|
||||
state = nextState;
|
||||
|
||||
const notifyAll = () => {
|
||||
for (const sub of subscribers) {
|
||||
const nextSlice = sub.selector(state);
|
||||
const equal = sub.compare(sub.lastSlice, nextSlice);
|
||||
if (!equal) {
|
||||
const prevSlice = sub.lastSlice;
|
||||
sub.lastSlice = nextSlice;
|
||||
sub.listener(nextSlice, prevSlice);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (sync) {
|
||||
notifyAll();
|
||||
} else {
|
||||
scheduleAsyncJob(notifyAll);
|
||||
}
|
||||
}
|
||||
|
||||
function subscribe(selector, listener, { immediate = true, compare = isShallowEqual } = {}) {
|
||||
const initialSlice = selector(state);
|
||||
const sub = {
|
||||
selector,
|
||||
listener,
|
||||
compare,
|
||||
lastSlice: initialSlice,
|
||||
};
|
||||
subscribers.add(sub);
|
||||
if (immediate) {
|
||||
listener(initialSlice, undefined);
|
||||
}
|
||||
return () => {
|
||||
subscribers.delete(sub);
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
getState,
|
||||
setState,
|
||||
subscribe,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user