/** * 浏览器半边:在 `shell.overlay`(框架级浮层,list 插槽,默认点击穿透)里 * 渲染一个常驻的余额状态条。 * * 数据来源是宿主已有的 `account` Remote 命名空间,也就是「设置 → 账户 → * 余额」用的同一个方法:`getBalance(client)`。插件本身不碰凭据、不发平台 * 请求,因此不会引入第二套账号逻辑;未登录(使用 API Key)时该方法返回 * `null`,这里显示为未登录状态。 * * 注册进 `shell.overlay` 的条目默认点击穿透,控件自己打开 pointer-events。 */ window.__ModuleLoader__.load({ id: 'dsh-balance-pill', factory(require) { const React = require('react'); const h = React.createElement; /** 本插件在 Client locale 服务里的命名空间。 */ const NS = 'dsh-balance-pill'; /** 自动刷新间隔(毫秒);仅在文档可见时计时。 */ const REFRESH_INTERVAL_MS = 60000; /** 宿主读取余额时随请求上报的客户端版本;取不到真实版本时的兜底值。 */ const FALLBACK_CLIENT_VERSION = '0.2.0-rc.2'; const COPY = { en: { label: 'Balance', bonus: 'Bonus', loading: 'Reading balance…', unavailable: 'Balance unavailable', signedOut: 'Not signed in', amountPlaceholder: '--', updated: 'Updated {time}', auto: 'Auto refresh every {seconds}s', refresh: 'Click to refresh now', retry: 'Click to retry', }, zh: { label: '余额', bonus: '赠送', loading: '正在读取余额…', unavailable: '余额读取失败', signedOut: '未登录 DeepSeek 账户', amountPlaceholder: '--', updated: '更新于 {time}', auto: '每 {seconds} 秒自动刷新', refresh: '点击立即刷新', retry: '点击重试', }, }; /** * 币种符号;未知币种退化成代码前缀,绝不猜符号。 * @param {string} currency - 平台返回的币种代码。 * @returns {string} 金额前缀。 */ function symbolOf(currency) { if (currency === 'CNY') return '¥'; if (currency === 'USD') return '$'; return `${currency} `; } /** * 千位分组。 * @param {string} text - 已经是定点小数的文本。 * @returns {string} 带分组符的文本。 */ function group(text) { const [integer, fraction] = text.split('.'); return `${Number(integer).toLocaleString()}.${fraction}`; } /** * 向零截断到分,再定点输出;避免浮点乘法把 0.29 抬成 0.30。 * @param {number} value - 正数金额。 * @returns {string} 两位小数文本。 */ function truncateToCents(value) { const cents = Math.floor(Number((value * 100).toFixed(6))) / 100; return cents.toFixed(2); } /** * 与宿主账户卡片一致的显示规则:两位小数、千位分组、正的次分金额显示 * 为 `<¥0.01`、负金额取绝对值并按 0.01 兜底。宿主用 big.js 保留原始 * 十进制精度,这里按余额量级用 Number 复现同一套显示结果;无法解析的 * 值绝不伪装成 0。 * @param {string} amount - 平台返回的十进制金额文本。 * @param {string} symbol - 币种符号。 * @returns {string} 展示用金额。 */ function formatBalance(amount, symbol) { const value = Number(amount); if (typeof amount !== 'string' || amount === '' || !Number.isFinite(value)) return `${symbol}--`; if (value === 0) return `${symbol}0.00`; if (value < 0) return `-${symbol}${value > -0.01 ? '0.01' : group(Math.abs(value).toFixed(2))}`; if (value < 0.01) return `<${symbol}0.01`; return `${symbol}${group(truncateToCents(value))}`; } /** * 本客户端构建的版本号。宿主只要求它是非空字符串,用于 x-client-version * 上报;取不到就退回打包时的桌面版本。 * @returns {string} 版本字符串。 */ function clientVersion() { const bridge = globalThis.dshDesktop; const candidates = [ typeof bridge === 'object' && bridge !== null ? bridge.version : undefined, typeof bridge === 'object' && bridge !== null ? bridge.appVersion : undefined, globalThis.__DSH_BOOT__?.version, globalThis.__DSH_VERSION__, ]; for (const candidate of candidates) if (typeof candidate === 'string' && candidate !== '') return candidate; return FALLBACK_CLIENT_VERSION; } /** * 组装一次账户调用携带的客户端身份,与宿主账户页取值的时机一致:调用 * 那一刻的语言和时区,而不是挂载时的。 * @param {object} ctx - 客户端插件上下文。 * @returns {{ version: string, locale: string, timezoneOffsetSeconds: number }} 请求身份。 */ function clientMetadata(ctx) { let locale = 'en'; try { locale = ctx.locale.getSnapshot().active; } catch (error) { // 语言读取失败不该阻断余额读取;退回英文,宿主的 locale 头同样会归一到 en_US。 } return { version: clientVersion(), locale, timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60, }; } /** * 组装状态条组件;组件闭包持有 ctx,因此可以直接调用 account Remote。 * @param {object} ctx - 客户端插件上下文。 * @param {Function} t - 本插件命名空间的翻译函数。 * @returns {Function} 状态条组件。 */ function createBalancePill(ctx, t) { return function BalancePill() { const [state, setState] = React.useState({ phase: 'loading', wallets: [], bonusWallets: [], at: 0, message: '' }); const [hover, setHover] = React.useState(false); const [focused, setFocused] = React.useState(false); const inFlight = React.useRef(false); const alive = React.useRef(true); const read = React.useCallback(async () => { if (inFlight.current) return; inFlight.current = true; try { const result = await ctx.remote.account.getBalance(clientMetadata(ctx)); if (!alive.current) return; if (!result || result.ok !== true) throw new Error(String(result?.error?.message ?? 'account balance request refused')); const value = result.value; if (value === null || value === undefined) { setState({ phase: 'signed-out', wallets: [], bonusWallets: [], at: Date.now(), message: '' }); return; } if (value.status === 'ready') { setState({ phase: 'ready', wallets: Array.isArray(value.value) ? value.value : [], bonusWallets: Array.isArray(value.bonusWallets) ? value.bonusWallets : [], at: Date.now(), message: '', }); return; } setState({ phase: 'failed', wallets: [], bonusWallets: [], at: Date.now(), message: '' }); } catch (error) { if (!alive.current) return; setState({ phase: 'error', wallets: [], bonusWallets: [], at: Date.now(), message: String(error?.message ?? error) }); } finally { inFlight.current = false; } }, []); React.useEffect(() => { alive.current = true; read(); const timer = window.setInterval(() => { if (document.visibilityState !== 'hidden') read(); }, REFRESH_INTERVAL_MS); const onVisibility = () => { if (document.visibilityState !== 'hidden') read(); }; document.addEventListener('visibilitychange', onVisibility); window.addEventListener('focus', onVisibility); return () => { alive.current = false; window.clearInterval(timer); document.removeEventListener('visibilitychange', onVisibility); window.removeEventListener('focus', onVisibility); }; }, [read]); const phase = state.phase; const dotColor = phase === 'ready' ? 'var(--dsw-alias-state-success-primary)' : phase === 'error' ? 'var(--dsw-alias-state-error-primary)' : phase === 'failed' ? 'var(--dsw-alias-state-warn-primary)' : 'var(--dsw-alias-label-tertiary)'; const amounts = state.wallets.map((wallet) => formatBalance(wallet?.balance, symbolOf(wallet?.currency))); const amountText = phase === 'ready' ? (amounts.length > 0 ? amounts.join(' · ') : `${t('label')} ${t('amountPlaceholder')}`) : phase === 'loading' ? t('amountPlaceholder') : phase === 'signed-out' ? t('amountPlaceholder') : t('amountPlaceholder'); const titleLines = [t('label')]; if (phase === 'ready') { for (const wallet of state.wallets) titleLines.push(`${symbolOf(wallet?.currency)}${wallet?.balance ?? '--'}`); for (const wallet of state.bonusWallets) titleLines.push(`${t('bonus')} ${symbolOf(wallet?.currency)}${wallet?.balance ?? '--'}`); if (state.at > 0) titleLines.push(t('updated', { time: new Date(state.at).toLocaleTimeString() })); titleLines.push(t('auto', { seconds: Math.round(REFRESH_INTERVAL_MS / 1000) })); titleLines.push(t('refresh')); } else if (phase === 'loading') { titleLines.push(t('loading')); } else if (phase === 'signed-out') { titleLines.push(t('signedOut')); titleLines.push(t('refresh')); } else { titleLines.push(phase === 'error' && state.message !== '' ? state.message : t('unavailable')); titleLines.push(t('retry')); } const background = hover ? 'var(--dsw-alias-interactive-bg-hover)' : 'var(--dsw-alias-bg-layer-2)'; return h('button', { type: 'button', title: titleLines.join('\n'), 'aria-label': `${t('label')} ${amountText}`, onClick: () => { void read(); }, onMouseEnter: () => setHover(true), onMouseLeave: () => setHover(false), onFocus: () => setFocused(true), onBlur: () => setFocused(false), style: { position: 'absolute', right: 16, bottom: 16, zIndex: 5, pointerEvents: 'auto', display: 'inline-flex', alignItems: 'center', gap: 6, height: 30, padding: '0 10px', boxSizing: 'border-box', border: '0.5px solid var(--dsw-alias-border-l3)', borderRadius: 999, background, backdropFilter: 'blur(12px)', color: 'var(--dsw-alias-label-secondary)', font: 'inherit', fontSize: 12, lineHeight: '1', whiteSpace: 'nowrap', cursor: 'pointer', boxShadow: '0 2px 10px var(--dsw-alias-bg-mask-1)', outline: focused ? 'var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary))' : 'none', outlineOffset: 2, WebkitAppRegion: 'no-drag', transition: 'background 120ms ease', }, }, [ h('span', { key: 'dot', 'aria-hidden': true, style: { width: 6, height: 6, borderRadius: '50%', flex: 'none', background: dotColor, opacity: phase === 'loading' ? 0.5 : 1, }, }), h('span', { key: 'label', style: { color: 'var(--dsw-alias-label-tertiary)' } }, t('label')), h('span', { key: 'amount', style: { color: phase === 'ready' ? 'var(--dsw-alias-label-primary)' : 'var(--dsw-alias-label-tertiary)', fontVariantNumeric: 'tabular-nums', fontWeight: phase === 'ready' ? 500 : 400, }, }, amountText), ]); }; } return { /** 需要的 Client 服务:插槽、语言,以及 account Remote 命名空间。 */ inject: ['slots', 'locale', 'remote', 'remote.account'], /** * 注册字典并把状态条挂进框架浮层。 * @param {object} ctx - 客户端插件上下文。 */ apply(ctx) { ctx.effect(() => ctx.locale.register(NS, { en: COPY.en, zh: COPY.zh }), 'balance-pill: dictionaries'); const t = ctx.locale.bind(NS); const BalancePill = createBalancePill(ctx, t); ctx.slots.inject('shell.overlay', () => ctx.slots.register({ name: 'shell.overlay', id: 'balance-pill', order: 500, }, BalancePill)); }, }; }, });