dsh-plugin-balance-usage 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/LICENSE +21 -0
- package/README.md +52 -2
- package/client.js +1419 -0
- package/cordis.patch.yml +3 -0
- package/docs/DETAIL.md +75 -0
- package/icon.svg +9 -0
- package/index.js +557 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +74 -4
package/client.js
ADDED
|
@@ -0,0 +1,1419 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client half of the balance & usage bundle.
|
|
3
|
+
*
|
|
4
|
+
* Registers one sidebar footer action and one floating panel. Balance and the
|
|
5
|
+
* official usage link come from existing account Remotes; token usage comes
|
|
6
|
+
* from this bundle's own Host route (see index.js).
|
|
7
|
+
*/
|
|
8
|
+
window.__ModuleLoader__.load({
|
|
9
|
+
id: 'dsh-plugin-balance-usage',
|
|
10
|
+
factory(require) {
|
|
11
|
+
const React = require('react')
|
|
12
|
+
const h = React.createElement
|
|
13
|
+
const { useEffect, useRef, useState } = React
|
|
14
|
+
const nativeSyncExternalStore = React.useSyncExternalStore
|
|
15
|
+
|
|
16
|
+
function useSyncExternalStore(subscribe, getSnapshot) {
|
|
17
|
+
if (nativeSyncExternalStore) return nativeSyncExternalStore(subscribe, getSnapshot)
|
|
18
|
+
/* Fallback for a React build without the hook: same contract, coarser. */
|
|
19
|
+
const [value, setValue] = useState(getSnapshot)
|
|
20
|
+
useEffect(() => {
|
|
21
|
+
const unsubscribe = subscribe(() => setValue(getSnapshot()))
|
|
22
|
+
setValue(getSnapshot())
|
|
23
|
+
return unsubscribe
|
|
24
|
+
}, [])
|
|
25
|
+
return value
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const ROUTE = '/plugins/balance-usage/summary'
|
|
29
|
+
const PREFS_ROUTE = '/plugins/balance-usage/prefs'
|
|
30
|
+
const FALLBACK_USAGE_URL = 'https://platform.deepseek.com/usage'
|
|
31
|
+
const KEY_PRIMARY = 'dsh.balance-usage.primary'
|
|
32
|
+
const KEY_COLLAPSED = 'dsh.balance-usage.collapsed'
|
|
33
|
+
const PANEL_ID = 'dbu-panel'
|
|
34
|
+
const PANEL_TITLE_ID = 'dbu-panel-title'
|
|
35
|
+
const PLATFORM_BACK_ID = 'dbu-platform-back'
|
|
36
|
+
/* The footer numbers are glanceable, so they refresh on their own: often while the
|
|
37
|
+
panel is open, less often while it is closed, and immediately when the window
|
|
38
|
+
comes back to the foreground. */
|
|
39
|
+
const REFRESH_OPEN_MS = 15_000
|
|
40
|
+
const REFRESH_IDLE_MS = 30_000
|
|
41
|
+
const TICK_MS = 5_000
|
|
42
|
+
const STALE_MS = 8_000
|
|
43
|
+
|
|
44
|
+
/* ---------------------------------------------------------------- *
|
|
45
|
+
* Copy
|
|
46
|
+
* ---------------------------------------------------------------- */
|
|
47
|
+
|
|
48
|
+
const COPY = {
|
|
49
|
+
zh: {
|
|
50
|
+
entry: '余额与用量',
|
|
51
|
+
title: '余额与用量',
|
|
52
|
+
refresh: '刷新',
|
|
53
|
+
close: '关闭',
|
|
54
|
+
balance: '账户余额',
|
|
55
|
+
bonus: '赠送余额',
|
|
56
|
+
signedOut: '尚未登录 DeepSeek 账号,登录后可读取余额。',
|
|
57
|
+
signedOutShort: '未登录',
|
|
58
|
+
accountUnavailable: '账户服务不可用',
|
|
59
|
+
usage: 'Token 用量',
|
|
60
|
+
today: '今日',
|
|
61
|
+
total: '累计',
|
|
62
|
+
input: '输入',
|
|
63
|
+
output: '输出',
|
|
64
|
+
cache: '缓存读取',
|
|
65
|
+
requests: '请求',
|
|
66
|
+
primary: '主线',
|
|
67
|
+
auto: '自动',
|
|
68
|
+
setPrimary: '设为主线',
|
|
69
|
+
clearPrimary: '取消主线',
|
|
70
|
+
groups: '模型 / 运营商',
|
|
71
|
+
empty: '还没有用量记录,发送一条消息后再看看。',
|
|
72
|
+
openUsage: '打开官方 Token 用量详情',
|
|
73
|
+
loading: '读取中…',
|
|
74
|
+
failed: '数据读取失败',
|
|
75
|
+
noUsageRoute: '用量统计服务未就绪',
|
|
76
|
+
updated: '更新于',
|
|
77
|
+
last14: '近 14 天',
|
|
78
|
+
sessions: '个会话',
|
|
79
|
+
entryTitle: '余额与用量',
|
|
80
|
+
requestsSuffix: '次请求',
|
|
81
|
+
retry: '重试',
|
|
82
|
+
starHint: '星标 = 侧栏显示的主线',
|
|
83
|
+
stale: '(未更新)',
|
|
84
|
+
composition: '累计构成',
|
|
85
|
+
newWindow: '新窗口',
|
|
86
|
+
back: '返回',
|
|
87
|
+
usagePage: 'Token 用量',
|
|
88
|
+
platformLoading: '正在打开官方页面…',
|
|
89
|
+
platformFailed: '应用内页面打开失败',
|
|
90
|
+
browser: '在浏览器打开',
|
|
91
|
+
},
|
|
92
|
+
en: {
|
|
93
|
+
entry: 'Balance & usage',
|
|
94
|
+
title: 'Balance & usage',
|
|
95
|
+
refresh: 'Refresh',
|
|
96
|
+
close: 'Close',
|
|
97
|
+
balance: 'Account balance',
|
|
98
|
+
bonus: 'Bonus balance',
|
|
99
|
+
signedOut: 'Not signed in to a DeepSeek account. Sign in to read the balance.',
|
|
100
|
+
signedOutShort: 'Signed out',
|
|
101
|
+
accountUnavailable: 'Account service unavailable',
|
|
102
|
+
usage: 'Token usage',
|
|
103
|
+
today: 'Today',
|
|
104
|
+
total: 'Total',
|
|
105
|
+
input: 'Input',
|
|
106
|
+
output: 'Output',
|
|
107
|
+
cache: 'Cache read',
|
|
108
|
+
requests: 'requests',
|
|
109
|
+
primary: 'Main',
|
|
110
|
+
auto: 'Auto',
|
|
111
|
+
setPrimary: 'Set as main',
|
|
112
|
+
clearPrimary: 'Clear main',
|
|
113
|
+
groups: 'Models / providers',
|
|
114
|
+
empty: 'No usage recorded yet. Send a message first.',
|
|
115
|
+
openUsage: 'Open the official token usage page',
|
|
116
|
+
loading: 'Loading…',
|
|
117
|
+
failed: 'Could not load data',
|
|
118
|
+
noUsageRoute: 'Usage service not available',
|
|
119
|
+
updated: 'Updated',
|
|
120
|
+
last14: 'Last 14 days',
|
|
121
|
+
sessions: 'sessions',
|
|
122
|
+
entryTitle: 'Balance & usage',
|
|
123
|
+
requestsSuffix: 'requests',
|
|
124
|
+
retry: 'Retry',
|
|
125
|
+
starHint: 'Star picks the line the sidebar shows',
|
|
126
|
+
stale: ' (not updated)',
|
|
127
|
+
composition: 'Total breakdown',
|
|
128
|
+
newWindow: 'new window',
|
|
129
|
+
back: 'Back',
|
|
130
|
+
usagePage: 'Token usage',
|
|
131
|
+
platformLoading: 'Opening the official page…',
|
|
132
|
+
platformFailed: 'Could not open the page in the app',
|
|
133
|
+
browser: 'Open in browser',
|
|
134
|
+
},
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const PROVIDERS = {
|
|
138
|
+
'deepseek-account': { zh: 'DeepSeek 账号', en: 'DeepSeek account' },
|
|
139
|
+
deepseek: { zh: 'DeepSeek', en: 'DeepSeek' },
|
|
140
|
+
openrouter: { zh: 'OpenRouter', en: 'OpenRouter' },
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/* getLocale() returns the locale snapshot ({ active, locales, revision }), not a tag. */
|
|
144
|
+
function activeLocale() {
|
|
145
|
+
const snapshot = clientCtx?.locale?.getLocale?.()
|
|
146
|
+
return typeof snapshot?.active === 'string' ? snapshot.active : ''
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function isChinese() {
|
|
150
|
+
return activeLocale().toLowerCase().startsWith('zh')
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function copy() {
|
|
154
|
+
return isChinese() ? COPY.zh : COPY.en
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function providerLabel(id) {
|
|
158
|
+
const entry = PROVIDERS[id]
|
|
159
|
+
if (!entry) return id
|
|
160
|
+
return isChinese() ? entry.zh : entry.en
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/* ---------------------------------------------------------------- *
|
|
164
|
+
* Formatting
|
|
165
|
+
* ---------------------------------------------------------------- */
|
|
166
|
+
|
|
167
|
+
function fmtTokens(value) {
|
|
168
|
+
const number = Number(value) || 0
|
|
169
|
+
if (number <= 0) return '0'
|
|
170
|
+
if (number >= 1e9) return `${(number / 1e9).toFixed(2)}B`
|
|
171
|
+
if (number >= 1e6) return `${(number / 1e6).toFixed(2)}M`
|
|
172
|
+
if (number >= 1e3) return `${(number / 1e3).toFixed(1)}K`
|
|
173
|
+
return String(Math.round(number))
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function walletNumber(wallet) {
|
|
177
|
+
const parsed = Number(wallet?.balance)
|
|
178
|
+
return Number.isFinite(parsed) ? parsed : null
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function fmtWallet(wallet) {
|
|
182
|
+
if (!wallet) return '—'
|
|
183
|
+
const number = walletNumber(wallet)
|
|
184
|
+
const currency = wallet.currency === 'USD' ? 'USD' : 'CNY'
|
|
185
|
+
if (number === null) return `${currency === 'USD' ? '$' : '¥'}${wallet.balance}`
|
|
186
|
+
try {
|
|
187
|
+
return new Intl.NumberFormat(isChinese() ? 'zh-CN' : 'en-US', {
|
|
188
|
+
style: 'currency',
|
|
189
|
+
currency,
|
|
190
|
+
minimumFractionDigits: 2,
|
|
191
|
+
maximumFractionDigits: 2,
|
|
192
|
+
}).format(number)
|
|
193
|
+
} catch {
|
|
194
|
+
return `${currency === 'USD' ? '$' : '¥'}${number.toFixed(2)}`
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function mainWallet(wallets) {
|
|
199
|
+
if (!Array.isArray(wallets) || wallets.length === 0) return null
|
|
200
|
+
/* CNY is the primary wallet when both currencies are present; otherwise the
|
|
201
|
+
largest usable balance stands in. */
|
|
202
|
+
const cny = wallets.find((wallet) => wallet.currency === 'CNY' && walletNumber(wallet) !== null)
|
|
203
|
+
if (cny) return cny
|
|
204
|
+
const usable = wallets.filter((wallet) => walletNumber(wallet) !== null)
|
|
205
|
+
if (usable.length === 0) return wallets[0]
|
|
206
|
+
return usable.sort((a, b) => walletNumber(b) - walletNumber(a))[0]
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function bonusTotal(wallets) {
|
|
210
|
+
if (!Array.isArray(wallets) || wallets.length === 0) return null
|
|
211
|
+
const usable = wallets.filter((wallet) => walletNumber(wallet) !== null)
|
|
212
|
+
if (usable.length === 0) return null
|
|
213
|
+
const currency = usable[0].currency === 'USD' ? 'USD' : 'CNY'
|
|
214
|
+
const total = usable
|
|
215
|
+
.filter((wallet) => (wallet.currency === 'USD' ? 'USD' : 'CNY') === currency)
|
|
216
|
+
.reduce((sum, wallet) => sum + walletNumber(wallet), 0)
|
|
217
|
+
return { currency, total }
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function fmtClock(ms) {
|
|
221
|
+
if (!ms) return ''
|
|
222
|
+
const date = new Date(ms)
|
|
223
|
+
return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function fmtRelative(ms) {
|
|
227
|
+
if (!ms) return ''
|
|
228
|
+
const diff = Date.now() - ms
|
|
229
|
+
const locale = isChinese() ? 'zh-CN' : 'en-US'
|
|
230
|
+
try {
|
|
231
|
+
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })
|
|
232
|
+
const minutes = Math.round(diff / 60_000)
|
|
233
|
+
if (minutes < 1) return rtf.format(0, 'minute')
|
|
234
|
+
if (minutes < 60) return rtf.format(-minutes, 'minute')
|
|
235
|
+
const hours = Math.round(minutes / 60)
|
|
236
|
+
if (hours < 24) return rtf.format(-hours, 'hour')
|
|
237
|
+
const days = Math.round(hours / 24)
|
|
238
|
+
if (days < 15) return rtf.format(-days, 'day')
|
|
239
|
+
return new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric' }).format(new Date(ms))
|
|
240
|
+
} catch {
|
|
241
|
+
const hours = Math.round(diff / 3_600_000)
|
|
242
|
+
return hours < 1 ? '<1h' : `${hours}h`
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/* ---------------------------------------------------------------- *
|
|
247
|
+
* Small persisted settings
|
|
248
|
+
* ---------------------------------------------------------------- */
|
|
249
|
+
|
|
250
|
+
function readPrimary() {
|
|
251
|
+
try {
|
|
252
|
+
const raw = globalThis.localStorage?.getItem(KEY_PRIMARY)
|
|
253
|
+
if (!raw) return null
|
|
254
|
+
const value = JSON.parse(raw)
|
|
255
|
+
if (value && typeof value.provider === 'string' && typeof value.model === 'string') return value
|
|
256
|
+
} catch {
|
|
257
|
+
/* ignore a corrupt preference */
|
|
258
|
+
}
|
|
259
|
+
return null
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function writePrimary(value) {
|
|
263
|
+
try {
|
|
264
|
+
if (value) globalThis.localStorage?.setItem(KEY_PRIMARY, JSON.stringify(value))
|
|
265
|
+
else globalThis.localStorage?.removeItem(KEY_PRIMARY)
|
|
266
|
+
} catch {
|
|
267
|
+
/* storage may be unavailable */
|
|
268
|
+
}
|
|
269
|
+
pushPrefs({ primary: value })
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function readCollapsed() {
|
|
273
|
+
try {
|
|
274
|
+
const raw = globalThis.localStorage?.getItem(KEY_COLLAPSED)
|
|
275
|
+
const value = raw ? JSON.parse(raw) : null
|
|
276
|
+
if (Array.isArray(value)) return value.filter((item) => typeof item === 'string')
|
|
277
|
+
} catch {
|
|
278
|
+
/* ignore */
|
|
279
|
+
}
|
|
280
|
+
return []
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function writeCollapsed(value) {
|
|
284
|
+
try {
|
|
285
|
+
globalThis.localStorage?.setItem(KEY_COLLAPSED, JSON.stringify(value))
|
|
286
|
+
} catch {
|
|
287
|
+
/* ignore */
|
|
288
|
+
}
|
|
289
|
+
pushPrefs({ collapsed: value })
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/* The Host keeps the same two settings in `~/.dsh/plugin-settings/balance-usage.json`
|
|
293
|
+
so the profile-sync plugin can carry them to another machine. localStorage stays
|
|
294
|
+
as the offline fallback. */
|
|
295
|
+
async function pushPrefs(patch) {
|
|
296
|
+
try {
|
|
297
|
+
const values = {
|
|
298
|
+
primary: patch.primary !== undefined ? patch.primary : state.primary,
|
|
299
|
+
collapsed: patch.collapsed !== undefined ? patch.collapsed : state.collapsed,
|
|
300
|
+
}
|
|
301
|
+
await fetch(PREFS_ROUTE, {
|
|
302
|
+
method: 'POST',
|
|
303
|
+
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
|
304
|
+
body: JSON.stringify({ values }),
|
|
305
|
+
cache: 'no-store',
|
|
306
|
+
})
|
|
307
|
+
} catch {
|
|
308
|
+
/* the Host route may be absent in an older install */
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
async function readPrefs() {
|
|
313
|
+
try {
|
|
314
|
+
const options = { headers: { accept: 'application/json' }, cache: 'no-store' }
|
|
315
|
+
if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
|
|
316
|
+
options.signal = AbortSignal.timeout(4000)
|
|
317
|
+
}
|
|
318
|
+
const response = await fetch(PREFS_ROUTE, options)
|
|
319
|
+
if (!response.ok) return null
|
|
320
|
+
const body = await response.json()
|
|
321
|
+
return body && body.ok === true && body.values ? body.values : null
|
|
322
|
+
} catch {
|
|
323
|
+
return null
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/* ---------------------------------------------------------------- *
|
|
328
|
+
* Shared store
|
|
329
|
+
* ---------------------------------------------------------------- */
|
|
330
|
+
|
|
331
|
+
let clientCtx = null
|
|
332
|
+
let state = {
|
|
333
|
+
open: false,
|
|
334
|
+
wide: true,
|
|
335
|
+
anchor: null,
|
|
336
|
+
entryEl: null,
|
|
337
|
+
platform: null,
|
|
338
|
+
collapsed: readCollapsed(),
|
|
339
|
+
primary: readPrimary(),
|
|
340
|
+
status: 'idle',
|
|
341
|
+
error: null,
|
|
342
|
+
usage: null,
|
|
343
|
+
usageError: null,
|
|
344
|
+
account: null,
|
|
345
|
+
accountError: null,
|
|
346
|
+
updatedAt: 0,
|
|
347
|
+
}
|
|
348
|
+
const listeners = new Set()
|
|
349
|
+
|
|
350
|
+
function setState(patch) {
|
|
351
|
+
state = { ...state, ...patch }
|
|
352
|
+
for (const listener of [...listeners]) listener()
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function subscribe(listener) {
|
|
356
|
+
listeners.add(listener)
|
|
357
|
+
return () => listeners.delete(listener)
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const getState = () => state
|
|
361
|
+
const useSnapshot = () => useSyncExternalStore(subscribe, getState)
|
|
362
|
+
|
|
363
|
+
/* The Desktop shell exposes a native Platform view over the page; a plain browser
|
|
364
|
+
has no such bridge, so the CTA falls back to an ordinary new tab. */
|
|
365
|
+
function platformBridge() {
|
|
366
|
+
const bridge = globalThis.dshPlatform
|
|
367
|
+
return bridge && typeof bridge.open === 'function' ? bridge : null
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
let inflight = null
|
|
371
|
+
let timer = null
|
|
372
|
+
|
|
373
|
+
function errorText(reason) {
|
|
374
|
+
if (!reason) return null
|
|
375
|
+
if (typeof reason === 'string') return reason
|
|
376
|
+
return String(reason.message || reason)
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async function fetchUsage() {
|
|
380
|
+
const options = { headers: { accept: 'application/json' }, cache: 'no-store' }
|
|
381
|
+
/* A hung Host route must not leave the panel spinning forever. */
|
|
382
|
+
if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
|
|
383
|
+
options.signal = AbortSignal.timeout(8000)
|
|
384
|
+
}
|
|
385
|
+
const response = await fetch(ROUTE, options)
|
|
386
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
|
387
|
+
const body = await response.json()
|
|
388
|
+
if (!body || body.ok !== true) throw new Error(body?.error || 'bad payload')
|
|
389
|
+
return body
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function clientVersion() {
|
|
393
|
+
try {
|
|
394
|
+
const env = typeof process !== 'undefined' ? process.env : undefined
|
|
395
|
+
if (env && typeof env.DSH_CLIENT_VERSION === 'string' && env.DSH_CLIENT_VERSION) return env.DSH_CLIENT_VERSION
|
|
396
|
+
} catch {
|
|
397
|
+
/* no process shim */
|
|
398
|
+
}
|
|
399
|
+
const boot = globalThis.__DSH_BOOT__
|
|
400
|
+
const candidate = boot?.clientVersion || boot?.version
|
|
401
|
+
if (typeof candidate === 'string' && candidate) return candidate
|
|
402
|
+
return 'web'
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function clientMetadata() {
|
|
406
|
+
return {
|
|
407
|
+
version: clientVersion(),
|
|
408
|
+
locale: activeLocale() || 'zh_CN',
|
|
409
|
+
timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
async function fetchAccount(ctx) {
|
|
414
|
+
const remote = ctx?.get?.('remote')
|
|
415
|
+
const account = remote?.account
|
|
416
|
+
if (!account) throw new Error(copy().accountUnavailable)
|
|
417
|
+
|
|
418
|
+
const meta = clientMetadata()
|
|
419
|
+
const view = await account.getState()
|
|
420
|
+
const snapshot = view && view.ok ? view.value : null
|
|
421
|
+
const signedIn = snapshot?.status === 'credential-stored'
|
|
422
|
+
const result = {
|
|
423
|
+
signedIn,
|
|
424
|
+
usageUrl: snapshot?.links?.usageUrl || null,
|
|
425
|
+
topUpUrl: snapshot?.links?.topUpUrl || null,
|
|
426
|
+
wallets: [],
|
|
427
|
+
bonusWallets: [],
|
|
428
|
+
}
|
|
429
|
+
if (!signedIn) return result
|
|
430
|
+
|
|
431
|
+
const balance = await account.getBalance(meta)
|
|
432
|
+
if (balance && balance.ok && balance.value && balance.value.status === 'ready') {
|
|
433
|
+
result.wallets = balance.value.value || []
|
|
434
|
+
result.bonusWallets = balance.value.bonusWallets || []
|
|
435
|
+
}
|
|
436
|
+
return result
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function load(ctx, options = {}) {
|
|
440
|
+
if (inflight) return inflight
|
|
441
|
+
const fresh = state.status === 'ready' && Date.now() - state.updatedAt < STALE_MS
|
|
442
|
+
if (!options.force && fresh) return Promise.resolve()
|
|
443
|
+
|
|
444
|
+
inflight = (async () => {
|
|
445
|
+
if (state.status !== 'ready') setState({ status: 'loading' })
|
|
446
|
+
const [usage, account] = await Promise.allSettled([fetchUsage(), fetchAccount(ctx)])
|
|
447
|
+
const patch = {}
|
|
448
|
+
/* Only a successful round refreshes the freshness stamp; a failed refresh keeps
|
|
449
|
+
the previous "updated at" so the panel never claims newer data than it has. */
|
|
450
|
+
if (usage.status === 'fulfilled' || account.status === 'fulfilled') patch.updatedAt = Date.now()
|
|
451
|
+
|
|
452
|
+
if (usage.status === 'fulfilled') {
|
|
453
|
+
patch.usage = usage.value
|
|
454
|
+
patch.usageError = null
|
|
455
|
+
} else {
|
|
456
|
+
patch.usageError = errorText(usage.reason)
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
if (account.status === 'fulfilled') {
|
|
460
|
+
patch.account = account.value
|
|
461
|
+
patch.accountError = null
|
|
462
|
+
} else {
|
|
463
|
+
patch.accountError = errorText(account.reason)
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
const failed = patch.usageError && patch.accountError
|
|
467
|
+
patch.status = failed ? 'error' : 'ready'
|
|
468
|
+
patch.error = failed ? patch.usageError : null
|
|
469
|
+
setState(patch)
|
|
470
|
+
})().finally(() => {
|
|
471
|
+
inflight = null
|
|
472
|
+
})
|
|
473
|
+
|
|
474
|
+
return inflight
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/* ---------------------------------------------------------------- *
|
|
478
|
+
* Derived data
|
|
479
|
+
* ---------------------------------------------------------------- */
|
|
480
|
+
|
|
481
|
+
function allModels(usage) {
|
|
482
|
+
if (!usage || !Array.isArray(usage.groups)) return []
|
|
483
|
+
const rows = []
|
|
484
|
+
for (const group of usage.groups) {
|
|
485
|
+
for (const model of group.models || []) {
|
|
486
|
+
rows.push({ ...model, provider: group.provider })
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
return rows
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function resolveMain(usage, primary) {
|
|
493
|
+
const rows = allModels(usage)
|
|
494
|
+
if (rows.length === 0) return null
|
|
495
|
+
if (primary) {
|
|
496
|
+
const hit = rows.find((row) => row.provider === primary.provider && row.model === primary.model)
|
|
497
|
+
if (hit) return { row: hit, explicit: true }
|
|
498
|
+
}
|
|
499
|
+
rows.sort((a, b) => b.tokens - a.tokens || b.lastUsed - a.lastUsed)
|
|
500
|
+
return { row: rows[0], explicit: false }
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/* ---------------------------------------------------------------- *
|
|
504
|
+
* Styles
|
|
505
|
+
* ---------------------------------------------------------------- */
|
|
506
|
+
|
|
507
|
+
const CSS = `
|
|
508
|
+
.dbu-entry{flex:0 1 auto;display:flex;align-items:center;gap:8px;min-width:0;max-width:100%;box-sizing:border-box;margin-top:4px;padding:4px 8px;border:0;border-radius:8px;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer;transition:background-color .12s ease,color .12s ease}
|
|
509
|
+
.dbu-entry:hover{background:var(--dsw-alias-bg-skeleton)}
|
|
510
|
+
.dbu-entry[data-wide="false"]{width:32px;height:32px;padding:0;justify-content:center;position:relative}
|
|
511
|
+
.dbu-entry__icon{flex:none;display:inline-flex;align-items:center;color:var(--dsw-alias-label-secondary)}
|
|
512
|
+
.dbu-entry:hover .dbu-entry__icon{color:var(--dsw-alias-label-primary)}
|
|
513
|
+
.dbu-entry__body{display:flex;flex-direction:column;min-width:0;line-height:1.3}
|
|
514
|
+
.dbu-entry__money{font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
515
|
+
.dbu-entry__meta{font-size:11px;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
516
|
+
.dbu-entry__dot{position:absolute;top:1px;right:1px;width:7px;height:7px;border-radius:50%;background:var(--dsw-alias-chart-messages);box-shadow:0 0 0 2px var(--dsw-alias-bg-layer-1)}
|
|
517
|
+
.dbu-entry__dot[data-state="error"]{background:var(--dsw-alias-state-error-primary)}
|
|
518
|
+
.dbu-scrim{position:fixed;inset:0;z-index:998;background:transparent}
|
|
519
|
+
.dbu-platform{position:fixed;top:0;bottom:0;z-index:1100;box-sizing:border-box;display:flex;flex-direction:column;background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);box-shadow:-1px 0 0 0 var(--dsw-alias-border-l1)}
|
|
520
|
+
.dbu-platform__bar{flex:none;display:flex;align-items:center;gap:8px;height:44px;box-sizing:border-box;padding:0 12px;border-bottom:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-base)}
|
|
521
|
+
.dbu-platform__tab{display:inline-flex;align-items:center;gap:6px;max-width:100%;height:28px;box-sizing:border-box;padding:0 4px 0 10px;border-radius:8px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1)}
|
|
522
|
+
.dbu-platform__tabdot{flex:none;width:6px;height:6px;border-radius:50%;background:var(--dsw-alias-chart-messages)}
|
|
523
|
+
.dbu-platform__tablabel{font-size:12px;font-weight:550;color:var(--dsw-alias-label-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
524
|
+
.dbu-platform__close{flex:none;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;padding:0;border:0;border-radius:5px;background:transparent;color:var(--dsw-alias-label-primary);opacity:.7;cursor:pointer}
|
|
525
|
+
.dbu-platform__close:hover{background:var(--dsw-alias-bg-skeleton);opacity:1}
|
|
526
|
+
.dbu-platform__close:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
|
|
527
|
+
.dbu-platform__viewport{position:relative;flex:1;min-height:0}
|
|
528
|
+
.dbu-platform__status{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:24px;text-align:center;font-size:12px;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base)}
|
|
529
|
+
.dbu-platform__fail{opacity:.85}
|
|
530
|
+
.dbu-platform__actions{display:flex;align-items:center;gap:8px}
|
|
531
|
+
.dbu-platform__actions .dbu-retry{text-decoration:none}
|
|
532
|
+
.dbu-platform__spinner{width:18px;height:18px;border-radius:50%;border:2px solid var(--dsw-alias-bg-skeleton);border-top-color:var(--dsw-alias-brand-primary);animation:dbu-spin .9s linear infinite}
|
|
533
|
+
.dbu-panel{position:fixed;z-index:999;box-sizing:border-box;display:flex;flex-direction:column;width:336px;max-width:calc(100vw - 24px);max-height:72vh;border-radius:14px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-overlay);box-shadow:0 18px 48px rgba(0,0,0,.32);color:var(--dsw-alias-label-primary);font:inherit;overflow:hidden}
|
|
534
|
+
.dbu-panel:focus{outline:none}
|
|
535
|
+
.dbu-panel:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:2px}
|
|
536
|
+
.dbu-head{display:flex;align-items:center;gap:6px;padding:12px 12px 6px 14px}
|
|
537
|
+
.dbu-head__title{font-size:13px;font-weight:600;margin:0}
|
|
538
|
+
.dbu-head__time{font-size:11px;color:var(--dsw-alias-label-primary);opacity:.8;margin:0 auto 0 6px;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
539
|
+
.dbu-iconbtn{flex:none;display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;padding:0;border:0;border-radius:7px;background:transparent;color:var(--dsw-alias-label-primary);opacity:.75;cursor:pointer}
|
|
540
|
+
.dbu-iconbtn:hover{background:var(--dsw-alias-bg-skeleton);opacity:1}
|
|
541
|
+
.dbu-iconbtn[data-busy="true"]{opacity:1;cursor:progress}
|
|
542
|
+
.dbu-iconbtn[data-busy="true"] svg{animation:dbu-spin .9s linear infinite}
|
|
543
|
+
@keyframes dbu-spin{to{transform:rotate(360deg)}}
|
|
544
|
+
@media (prefers-reduced-motion: reduce){.dbu-iconbtn[data-busy="true"] svg{animation:none}}
|
|
545
|
+
.dbu-body{display:flex;flex-direction:column;gap:10px;padding:2px 14px 14px;overflow-y:auto;scrollbar-width:thin}
|
|
546
|
+
.dbu-card{border-radius:10px;background:var(--dsw-alias-bg-layer-1);padding:10px 12px}
|
|
547
|
+
.dbu-card__label{display:flex;align-items:center;gap:6px;font-size:11px;color:var(--dsw-alias-label-primary);opacity:.8;margin-bottom:4px}
|
|
548
|
+
.dbu-money{font-size:22px;font-weight:650;letter-spacing:-.01em;font-variant-numeric:tabular-nums;line-height:1.2}
|
|
549
|
+
.dbu-chip{font-size:11px;padding:1px 7px;border-radius:999px;background:var(--dsw-alias-bg-skeleton);color:var(--dsw-alias-label-primary);white-space:nowrap;max-width:100%;overflow:hidden;text-overflow:ellipsis}
|
|
550
|
+
.dbu-chip--main{background:var(--dsw-alias-brand-primary);color:var(--dsw-alias-bg-base)}
|
|
551
|
+
.dbu-muted{font-size:11px;color:var(--dsw-alias-label-primary);opacity:.88}
|
|
552
|
+
.dbu-big{font-size:18px;font-weight:600;font-variant-numeric:tabular-nums;line-height:1.25}
|
|
553
|
+
.dbu-big--sub{font-size:15px;font-weight:500;color:var(--dsw-alias-label-primary);opacity:.85}
|
|
554
|
+
.dbu-row{display:flex;align-items:baseline;gap:8px}
|
|
555
|
+
.dbu-row--between{display:flex;align-items:baseline;justify-content:space-between;gap:8px}
|
|
556
|
+
.dbu-stats{display:grid;grid-template-columns:repeat(3,1fr);gap:6px;margin-top:8px}
|
|
557
|
+
.dbu-stat{font-size:10px;color:var(--dsw-alias-label-primary);opacity:.8}
|
|
558
|
+
.dbu-stat b{display:block;font-size:12px;font-weight:600;color:var(--dsw-alias-label-primary);font-variant-numeric:tabular-nums}
|
|
559
|
+
.dbu-chart{display:flex;align-items:flex-end;gap:3px;height:32px;margin-top:10px}
|
|
560
|
+
.dbu-chart i{flex:1;border-radius:2px 2px 0 0;background:var(--dsw-alias-chart-messages);opacity:.55}
|
|
561
|
+
.dbu-chart i[data-empty="true"]{height:2px!important;background:var(--dsw-alias-bg-skeleton);opacity:1;border-radius:1px}
|
|
562
|
+
.dbu-chart i[data-today="true"]{opacity:1}
|
|
563
|
+
.dbu-section{display:flex;flex-direction:column;gap:2px}
|
|
564
|
+
.dbu-section__head{display:flex;align-items:center;gap:6px;font-size:11px;color:var(--dsw-alias-label-primary);opacity:.8;padding:0 2px 2px}
|
|
565
|
+
.dbu-section__hint{font-size:10.5px;color:var(--dsw-alias-label-primary);opacity:.6}
|
|
566
|
+
.dbu-group__row{display:flex;align-items:center;gap:6px;width:100%;box-sizing:border-box;padding:5px 6px;border:0;border-radius:6px;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}
|
|
567
|
+
.dbu-group__row:hover{background:var(--dsw-alias-bg-skeleton)}
|
|
568
|
+
.dbu-group__name{font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
569
|
+
.dbu-group__val{margin-left:auto;font-size:11px;color:var(--dsw-alias-label-primary);opacity:.8;font-variant-numeric:tabular-nums;white-space:nowrap}
|
|
570
|
+
.dbu-chevron{flex:none;display:inline-flex;color:var(--dsw-alias-label-primary);opacity:.6;transition:transform .12s ease}
|
|
571
|
+
.dbu-chevron[data-open="true"]{transform:rotate(90deg)}
|
|
572
|
+
.dbu-models{display:flex;flex-direction:column;padding-left:12px}
|
|
573
|
+
.dbu-model{display:flex;align-items:center;gap:6px;width:100%;box-sizing:border-box;padding:5px 6px;border-radius:6px;color:inherit;font:inherit;text-align:left;cursor:default}
|
|
574
|
+
.dbu-model[data-main="true"]{box-shadow:inset 2px 0 0 0 var(--dsw-alias-chart-messages)}
|
|
575
|
+
.dbu-model__name{font-size:11px;color:var(--dsw-alias-label-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
576
|
+
.dbu-model[data-main="true"] .dbu-model__name{font-weight:600}
|
|
577
|
+
.dbu-model__val{margin-left:auto;font-size:11px;color:var(--dsw-alias-label-primary);opacity:.75;font-variant-numeric:tabular-nums;white-space:nowrap}
|
|
578
|
+
.dbu-star{flex:none;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;padding:0;border:0;border-radius:6px;background:transparent;color:var(--dsw-alias-label-tertiary);cursor:pointer}
|
|
579
|
+
.dbu-star:hover{background:var(--dsw-alias-bg-skeleton);color:var(--dsw-alias-label-secondary)}
|
|
580
|
+
.dbu-star[data-active="true"]{color:var(--dsw-alias-state-warn-label)}
|
|
581
|
+
.dbu-cta{display:flex;align-items:center;justify-content:center;gap:6px;width:100%;box-sizing:border-box;padding:8px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:transparent;color:var(--dsw-alias-label-primary);font-size:12px;font-family:inherit;cursor:pointer;text-decoration:none}
|
|
582
|
+
.dbu-cta:hover{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary)}
|
|
583
|
+
.dbu-note{font-size:11px;color:var(--dsw-alias-label-primary);opacity:.8;padding:2px}
|
|
584
|
+
.dbu-danger{display:flex;align-items:flex-start;gap:6px;font-size:11.5px;font-weight:500;line-height:1.5;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-skeleton);border-left:2px solid var(--dsw-alias-state-error-primary);border-radius:4px;padding:5px 7px}
|
|
585
|
+
.dbu-danger b{color:var(--dsw-alias-state-error-primary);font-weight:600;flex:none}
|
|
586
|
+
.dbu-retry{flex:none;margin-left:auto;padding:1px 7px;border:1px solid var(--dsw-alias-border-l2);border-radius:6px;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:11px;cursor:pointer}
|
|
587
|
+
.dbu-retry:hover{border-color:var(--dsw-alias-brand-primary)}
|
|
588
|
+
.dbu-skel{border-radius:6px;background:var(--dsw-alias-bg-skeleton);animation:dbu-pulse 1.4s ease-in-out infinite}
|
|
589
|
+
.dbu-skel--line{height:18px}
|
|
590
|
+
.dbu-skel--line-lg{height:26px}
|
|
591
|
+
@keyframes dbu-pulse{0%,100%{opacity:.6}50%{opacity:1}}
|
|
592
|
+
@media (prefers-reduced-motion: reduce){.dbu-skel{animation:none}}
|
|
593
|
+
.dbu-sr{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
|
|
594
|
+
.dbu-entry:focus-visible,.dbu-iconbtn:focus-visible,.dbu-group__row:focus-visible,.dbu-star:focus-visible,.dbu-cta:focus-visible,.dbu-retry:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:1px}
|
|
595
|
+
`
|
|
596
|
+
|
|
597
|
+
function installStyles() {
|
|
598
|
+
const existing = document.getElementById('dsh-balance-usage-style')
|
|
599
|
+
if (existing) return () => {}
|
|
600
|
+
const style = document.createElement('style')
|
|
601
|
+
style.id = 'dsh-balance-usage-style'
|
|
602
|
+
style.textContent = CSS
|
|
603
|
+
document.head.appendChild(style)
|
|
604
|
+
return () => style.remove()
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/* ---------------------------------------------------------------- *
|
|
608
|
+
* Icons
|
|
609
|
+
* ---------------------------------------------------------------- */
|
|
610
|
+
|
|
611
|
+
function Svg({ size = 16, children, ...rest }) {
|
|
612
|
+
return h(
|
|
613
|
+
'svg',
|
|
614
|
+
{
|
|
615
|
+
width: size,
|
|
616
|
+
height: size,
|
|
617
|
+
viewBox: '0 0 24 24',
|
|
618
|
+
fill: 'none',
|
|
619
|
+
stroke: 'currentColor',
|
|
620
|
+
strokeWidth: 1.7,
|
|
621
|
+
strokeLinecap: 'round',
|
|
622
|
+
strokeLinejoin: 'round',
|
|
623
|
+
'aria-hidden': true,
|
|
624
|
+
focusable: false,
|
|
625
|
+
...rest,
|
|
626
|
+
},
|
|
627
|
+
children,
|
|
628
|
+
)
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
function WalletIcon({ size = 16 }) {
|
|
632
|
+
return h(
|
|
633
|
+
Svg,
|
|
634
|
+
{ size },
|
|
635
|
+
h('path', { d: 'M3.5 8.2A2.7 2.7 0 0 1 6.2 5.5h11.3a3 3 0 0 1 3 3v7.2a2.8 2.8 0 0 1-2.8 2.8H6.3a2.8 2.8 0 0 1-2.8-2.8z' }),
|
|
636
|
+
h('path', { d: 'M3.5 9.4h14.6' }),
|
|
637
|
+
h('circle', { cx: 17.1, cy: 14.1, r: 1.15, fill: 'currentColor', stroke: 'none' }),
|
|
638
|
+
)
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function RefreshIcon() {
|
|
642
|
+
return h(Svg, { size: 14 }, h('path', { d: 'M20 11.5a8 8 0 1 0-2.3 5.7' }), h('path', { d: 'M20 5.5v6h-6' }))
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
function CloseIcon() {
|
|
646
|
+
return h(Svg, { size: 14 }, h('path', { d: 'M6 6l12 12M18 6L6 18' }))
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
function ChevronIcon({ open }) {
|
|
650
|
+
return h(Svg, { size: 12, className: 'dbu-chevron', 'data-open': open ? 'true' : 'false', style: { transform: open ? 'rotate(90deg)' : 'none' } }, h('path', { d: 'M9 6l6 6-6 6' }))
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
function ExternalIcon() {
|
|
654
|
+
return h(Svg, { size: 13 }, h('path', { d: 'M14 4h6v6' }), h('path', { d: 'M20 4l-8.5 8.5' }), h('path', { d: 'M18.5 14v4.5a2 2 0 0 1-2 2H5.5a2 2 0 0 1-2-2V7.5a2 2 0 0 1 2-2H10' }))
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function StarIcon({ filled }) {
|
|
658
|
+
return h(
|
|
659
|
+
Svg,
|
|
660
|
+
{ size: 12, fill: filled ? 'currentColor' : 'none' },
|
|
661
|
+
h('path', { d: 'M12 4.2l2.4 4.9 5.4.8-3.9 3.8.9 5.4-4.8-2.5-4.8 2.5.9-5.4L4.2 9.9l5.4-.8z' }),
|
|
662
|
+
)
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/* ---------------------------------------------------------------- *
|
|
666
|
+
* Sidebar footer entry
|
|
667
|
+
* ---------------------------------------------------------------- */
|
|
668
|
+
|
|
669
|
+
function FooterAction(props) {
|
|
670
|
+
const snapshot = useSnapshot()
|
|
671
|
+
const t = copy()
|
|
672
|
+
const wide = props?.wide !== false
|
|
673
|
+
const usage = snapshot.usage
|
|
674
|
+
const account = snapshot.account
|
|
675
|
+
const wallet = mainWallet(account?.wallets)
|
|
676
|
+
const todayTokens = usage?.today?.tokens || 0
|
|
677
|
+
|
|
678
|
+
const money = wallet ? fmtWallet(wallet) : account?.signedIn === false ? t.signedOutShort : '—'
|
|
679
|
+
const meta = usage ? `${t.today} ${fmtTokens(todayTokens)}` : snapshot.status === 'loading' ? t.loading : snapshot.status === 'error' ? t.failed : '—'
|
|
680
|
+
const dotState = snapshot.status === 'error' ? 'error' : 'ok'
|
|
681
|
+
|
|
682
|
+
const title = [t.entryTitle, wallet ? `${t.balance} ${fmtWallet(wallet)}` : null, usage ? `${t.total} ${fmtTokens(usage.totals?.tokens || 0)} tok` : null]
|
|
683
|
+
.filter(Boolean)
|
|
684
|
+
.join('\n')
|
|
685
|
+
|
|
686
|
+
function onClick(event) {
|
|
687
|
+
const rect = event.currentTarget.getBoundingClientRect()
|
|
688
|
+
/* The entry is content-sized, so hang the panel off the sidebar column it sits in.
|
|
689
|
+
Only ancestors that still look like a sidebar count: a full-width shell row
|
|
690
|
+
would push the panel off-screen. */
|
|
691
|
+
let columnRight = rect.right
|
|
692
|
+
let node = event.currentTarget.parentElement
|
|
693
|
+
for (let depth = 0; node && depth < 8; depth += 1) {
|
|
694
|
+
const bounds = node.getBoundingClientRect()
|
|
695
|
+
if (bounds.width > 520) break
|
|
696
|
+
if (bounds.right > columnRight + 16) {
|
|
697
|
+
columnRight = bounds.right
|
|
698
|
+
break
|
|
699
|
+
}
|
|
700
|
+
node = node.parentElement
|
|
701
|
+
}
|
|
702
|
+
const next = !state.open
|
|
703
|
+
setState({
|
|
704
|
+
open: next,
|
|
705
|
+
wide,
|
|
706
|
+
entryEl: next ? event.currentTarget : state.entryEl,
|
|
707
|
+
anchor: next ? { left: rect.left, right: columnRight, top: rect.top, bottom: rect.bottom, width: rect.width } : state.anchor,
|
|
708
|
+
})
|
|
709
|
+
if (next) load(clientCtx, { force: Date.now() - state.updatedAt > STALE_MS })
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
return h(
|
|
713
|
+
'button',
|
|
714
|
+
{
|
|
715
|
+
type: 'button',
|
|
716
|
+
className: 'dbu-entry',
|
|
717
|
+
'data-wide': wide ? 'true' : 'false',
|
|
718
|
+
title,
|
|
719
|
+
'aria-label': `${t.entry} ${money} ${meta}`,
|
|
720
|
+
'aria-haspopup': 'dialog',
|
|
721
|
+
'aria-controls': PANEL_ID,
|
|
722
|
+
'aria-expanded': snapshot.open ? 'true' : 'false',
|
|
723
|
+
onClick,
|
|
724
|
+
},
|
|
725
|
+
h('span', { className: 'dbu-entry__icon' }, h(WalletIcon, { size: wide ? 16 : 18 })),
|
|
726
|
+
wide
|
|
727
|
+
? h(
|
|
728
|
+
'span',
|
|
729
|
+
{ className: 'dbu-entry__body' },
|
|
730
|
+
h('span', { className: 'dbu-entry__money' }, money),
|
|
731
|
+
h('span', { className: 'dbu-entry__meta' }, meta),
|
|
732
|
+
)
|
|
733
|
+
: todayTokens > 0
|
|
734
|
+
? h('span', { className: 'dbu-entry__dot', 'data-state': dotState })
|
|
735
|
+
: null,
|
|
736
|
+
)
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/* ---------------------------------------------------------------- *
|
|
740
|
+
* Panel
|
|
741
|
+
* ---------------------------------------------------------------- */
|
|
742
|
+
|
|
743
|
+
function Stat({ label, value }) {
|
|
744
|
+
return h('div', { className: 'dbu-stat' }, h('b', null, value), label)
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
function MiniChart({ series, label }) {
|
|
748
|
+
if (!Array.isArray(series) || series.length === 0) return null
|
|
749
|
+
const max = Math.max(...series.map((point) => point.tokens || 0), 1)
|
|
750
|
+
const last = series.length - 1
|
|
751
|
+
return h(
|
|
752
|
+
'div',
|
|
753
|
+
{ className: 'dbu-chart', role: 'img', 'aria-label': label || undefined },
|
|
754
|
+
series.map((point, index) => {
|
|
755
|
+
const tokens = point.tokens || 0
|
|
756
|
+
// Square-root scaling keeps small days visible next to a heavy today bar;
|
|
757
|
+
// empty days keep a 2px track so the band reads as a day axis, not a rule.
|
|
758
|
+
const height = tokens === 0 ? 0 : Math.max(4, Math.round(Math.sqrt(tokens / max) * 28))
|
|
759
|
+
return h('i', {
|
|
760
|
+
key: point.date,
|
|
761
|
+
'data-today': index === last ? 'true' : 'false',
|
|
762
|
+
'data-empty': tokens === 0 ? 'true' : 'false',
|
|
763
|
+
style: { height: `${height}px` },
|
|
764
|
+
title: `${point.date} · ${fmtTokens(tokens)}`,
|
|
765
|
+
})
|
|
766
|
+
}),
|
|
767
|
+
)
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
function GroupRow({ group, collapsed, onToggle, main, primary, onStar, condensed }) {
|
|
771
|
+
const regionId = `dbu-models-${group.provider}`
|
|
772
|
+
/* With a single provider/model the totals would just repeat the headline number,
|
|
773
|
+
so the row keeps only the name and the pin control. */
|
|
774
|
+
const showTotals = condensed !== true
|
|
775
|
+
return h(
|
|
776
|
+
'div',
|
|
777
|
+
null,
|
|
778
|
+
h(
|
|
779
|
+
'button',
|
|
780
|
+
{
|
|
781
|
+
type: 'button',
|
|
782
|
+
className: 'dbu-group__row',
|
|
783
|
+
'aria-expanded': collapsed ? 'false' : 'true',
|
|
784
|
+
'aria-controls': regionId,
|
|
785
|
+
onClick: onToggle,
|
|
786
|
+
},
|
|
787
|
+
h(ChevronIcon, { open: !collapsed }),
|
|
788
|
+
h('span', { className: 'dbu-group__name' }, providerLabel(group.provider)),
|
|
789
|
+
showTotals ? h('span', { className: 'dbu-group__val' }, fmtTokens(group.tokens)) : null,
|
|
790
|
+
),
|
|
791
|
+
collapsed
|
|
792
|
+
? null
|
|
793
|
+
: h(
|
|
794
|
+
'div',
|
|
795
|
+
{ className: 'dbu-models', id: regionId },
|
|
796
|
+
(group.models || []).map((model) => {
|
|
797
|
+
const isMain = Boolean(main && main.model === model.model && main.provider === group.provider)
|
|
798
|
+
/* The star is an explicit choice: auto resolution keeps it hollow so the
|
|
799
|
+
click still reads as "make this the main line". */
|
|
800
|
+
const pinned = Boolean(primary && primary.model === model.model && primary.provider === group.provider)
|
|
801
|
+
const starLabel = pinned ? copy().clearPrimary : copy().setPrimary
|
|
802
|
+
return h(
|
|
803
|
+
'div',
|
|
804
|
+
{ key: model.model, className: 'dbu-model', 'data-main': isMain ? 'true' : 'false' },
|
|
805
|
+
h('span', { className: 'dbu-model__name', title: `${model.model} · ${fmtTokens(model.tokens)}` }, model.model),
|
|
806
|
+
showTotals
|
|
807
|
+
? h('span', { className: 'dbu-model__val' }, `${fmtTokens(model.tokens)} · ${fmtRelative(model.lastUsed)}`)
|
|
808
|
+
: null,
|
|
809
|
+
h(
|
|
810
|
+
'button',
|
|
811
|
+
{
|
|
812
|
+
type: 'button',
|
|
813
|
+
className: 'dbu-star',
|
|
814
|
+
'data-active': pinned ? 'true' : 'false',
|
|
815
|
+
'aria-pressed': pinned ? 'true' : 'false',
|
|
816
|
+
'aria-label': starLabel,
|
|
817
|
+
title: starLabel,
|
|
818
|
+
onClick: (event) => {
|
|
819
|
+
event.stopPropagation()
|
|
820
|
+
onStar(group.provider, model.model)
|
|
821
|
+
},
|
|
822
|
+
},
|
|
823
|
+
h(StarIcon, { filled: pinned }),
|
|
824
|
+
),
|
|
825
|
+
)
|
|
826
|
+
}),
|
|
827
|
+
),
|
|
828
|
+
)
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
function panelFocusables(node) {
|
|
832
|
+
if (!node) return []
|
|
833
|
+
return [...node.querySelectorAll('button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])')].filter(
|
|
834
|
+
(element) => element.offsetParent !== null || element.getClientRects().length > 0,
|
|
835
|
+
)
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
function Panel() {
|
|
839
|
+
const snapshot = useSnapshot()
|
|
840
|
+
const t = copy()
|
|
841
|
+
const [, forceViewport] = useState(0)
|
|
842
|
+
|
|
843
|
+
useEffect(() => {
|
|
844
|
+
if (!snapshot.open) {
|
|
845
|
+
/* Returning focus keeps the keyboard loop closed when the popover closes. */
|
|
846
|
+
const entry = state.entryEl
|
|
847
|
+
if (entry && typeof entry.focus === 'function') entry.focus()
|
|
848
|
+
return undefined
|
|
849
|
+
}
|
|
850
|
+
const panel = () => document.getElementById(PANEL_ID)
|
|
851
|
+
const onKey = (event) => {
|
|
852
|
+
if (event.defaultPrevented) return
|
|
853
|
+
if (event.key === 'Escape') {
|
|
854
|
+
setState({ open: false })
|
|
855
|
+
return
|
|
856
|
+
}
|
|
857
|
+
if (event.key !== 'Tab') return
|
|
858
|
+
const items = panelFocusables(panel())
|
|
859
|
+
if (items.length === 0) return
|
|
860
|
+
const first = items[0]
|
|
861
|
+
const last = items[items.length - 1]
|
|
862
|
+
const active = document.activeElement
|
|
863
|
+
if (event.shiftKey && (active === first || active === panel())) {
|
|
864
|
+
event.preventDefault()
|
|
865
|
+
last.focus()
|
|
866
|
+
} else if (!event.shiftKey && active === last) {
|
|
867
|
+
event.preventDefault()
|
|
868
|
+
first.focus()
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
const onResize = () => forceViewport((value) => value + 1)
|
|
872
|
+
window.addEventListener('keydown', onKey)
|
|
873
|
+
window.addEventListener('resize', onResize)
|
|
874
|
+
load(clientCtx)
|
|
875
|
+
/* Move focus into the popover so Escape and Tab act on it, not on the page behind. */
|
|
876
|
+
const focusTimer = window.setTimeout(() => {
|
|
877
|
+
const node = panel()
|
|
878
|
+
if (node) {
|
|
879
|
+
node.focus()
|
|
880
|
+
if (document.activeElement !== node) panelFocusables(node)[0]?.focus()
|
|
881
|
+
}
|
|
882
|
+
}, 0)
|
|
883
|
+
return () => {
|
|
884
|
+
window.removeEventListener('keydown', onKey)
|
|
885
|
+
window.removeEventListener('resize', onResize)
|
|
886
|
+
window.clearTimeout(focusTimer)
|
|
887
|
+
}
|
|
888
|
+
}, [snapshot.open])
|
|
889
|
+
|
|
890
|
+
if (!snapshot.open) return snapshot.platform ? h(PlatformSurface, { page: snapshot.platform }) : null
|
|
891
|
+
|
|
892
|
+
const account = snapshot.account
|
|
893
|
+
const usage = snapshot.usage
|
|
894
|
+
const main = resolveMain(usage, snapshot.primary)
|
|
895
|
+
const wallet = mainWallet(account?.wallets)
|
|
896
|
+
const bonus = bonusTotal(account?.bonusWallets)
|
|
897
|
+
const totals = usage?.totals
|
|
898
|
+
const today = usage?.today
|
|
899
|
+
|
|
900
|
+
const anchor = snapshot.anchor
|
|
901
|
+
const viewportWidth = window.innerWidth || 1280
|
|
902
|
+
const viewportHeight = window.innerHeight || 800
|
|
903
|
+
const compact = viewportWidth < 760
|
|
904
|
+
const width = compact ? Math.max(240, viewportWidth - 16) : Math.min(336, viewportWidth - 24)
|
|
905
|
+
/* Wide sidebar: hang the panel off the entry's right edge so the session list
|
|
906
|
+
stays readable. Narrow rail: the same rule clears the 56px rail. Falls back
|
|
907
|
+
to covering the entry when neither side has room. */
|
|
908
|
+
const gutters = 8
|
|
909
|
+
const beside = anchor ? anchor.right + gutters : gutters
|
|
910
|
+
const above = anchor ? Math.max(gutters, viewportHeight - anchor.top + gutters) : 72
|
|
911
|
+
const besideFits = beside + width + gutters <= viewportWidth
|
|
912
|
+
const left = compact ? 8 : besideFits ? beside : Math.max(gutters, Math.min(anchor ? anchor.left : 12, viewportWidth - width - gutters))
|
|
913
|
+
const bottom = compact ? gutters : above
|
|
914
|
+
const maxHeight = Math.max(200, Math.min(viewportHeight * (compact ? 0.62 : 0.68), viewportHeight - bottom - 12))
|
|
915
|
+
|
|
916
|
+
function toggleGroup(provider) {
|
|
917
|
+
const collapsed = state.collapsed.includes(provider)
|
|
918
|
+
? state.collapsed.filter((item) => item !== provider)
|
|
919
|
+
: [...state.collapsed, provider]
|
|
920
|
+
writeCollapsed(collapsed)
|
|
921
|
+
setState({ collapsed })
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
function onStar(provider, model) {
|
|
925
|
+
const active = state.primary && state.primary.provider === provider && state.primary.model === model
|
|
926
|
+
const next = active ? null : { provider, model }
|
|
927
|
+
writePrimary(next)
|
|
928
|
+
setState({ primary: next })
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
const loadingFirst = !usage && (snapshot.status === 'loading' || snapshot.status === 'idle')
|
|
932
|
+
|
|
933
|
+
function retryButton() {
|
|
934
|
+
return h('button', {
|
|
935
|
+
type: 'button',
|
|
936
|
+
className: 'dbu-retry',
|
|
937
|
+
onClick: () => load(clientCtx, { force: true }),
|
|
938
|
+
}, t.retry)
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
const statusNote = () => {
|
|
942
|
+
if (!snapshot.usageError) return null
|
|
943
|
+
const routeMissing = /HTTP 404|HTTP 405|Failed to fetch|NetworkError/i.test(snapshot.usageError)
|
|
944
|
+
return h(
|
|
945
|
+
'div',
|
|
946
|
+
{ className: 'dbu-danger', role: 'status' },
|
|
947
|
+
h('b', null, routeMissing ? t.noUsageRoute : t.failed),
|
|
948
|
+
h('span', { style: { minWidth: 0, wordBreak: 'break-word' } }, snapshot.usageError),
|
|
949
|
+
retryButton(),
|
|
950
|
+
)
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
const accountErrorBlock = () =>
|
|
954
|
+
snapshot.accountError
|
|
955
|
+
? h(
|
|
956
|
+
'div',
|
|
957
|
+
{ className: 'dbu-danger', style: { marginTop: '6px' }, role: 'status' },
|
|
958
|
+
h('b', null, t.failed),
|
|
959
|
+
h('span', { style: { minWidth: 0, wordBreak: 'break-word' } }, snapshot.accountError),
|
|
960
|
+
retryButton(),
|
|
961
|
+
)
|
|
962
|
+
: null
|
|
963
|
+
|
|
964
|
+
const cacheShare = totals && totals.tokens ? Math.round(((totals.cacheReadTokens || 0) / totals.tokens) * 100) : 0
|
|
965
|
+
const chartsLabel = `${t.last14}: ${t.today} ${fmtTokens(today?.tokens || 0)} · ${t.total} ${fmtTokens(totals?.tokens || 0)}`
|
|
966
|
+
|
|
967
|
+
return h(
|
|
968
|
+
React.Fragment,
|
|
969
|
+
null,
|
|
970
|
+
h('div', { className: 'dbu-scrim', onPointerDown: () => setState({ open: false }) }),
|
|
971
|
+
h(
|
|
972
|
+
'section',
|
|
973
|
+
{
|
|
974
|
+
id: PANEL_ID,
|
|
975
|
+
className: 'dbu-panel',
|
|
976
|
+
role: 'dialog',
|
|
977
|
+
tabIndex: -1,
|
|
978
|
+
'aria-modal': 'true',
|
|
979
|
+
'aria-labelledby': PANEL_TITLE_ID,
|
|
980
|
+
style: { left: `${left}px`, bottom: `${bottom}px`, width: `${width}px`, maxHeight: `${maxHeight}px` },
|
|
981
|
+
},
|
|
982
|
+
h(
|
|
983
|
+
'header',
|
|
984
|
+
{ className: 'dbu-head' },
|
|
985
|
+
h('h2', { className: 'dbu-head__title', id: PANEL_TITLE_ID }, t.title),
|
|
986
|
+
h(
|
|
987
|
+
'span',
|
|
988
|
+
{ className: 'dbu-head__time' },
|
|
989
|
+
snapshot.updatedAt ? `${t.updated} ${fmtClock(snapshot.updatedAt)}` : '',
|
|
990
|
+
snapshot.updatedAt && (snapshot.usageError || snapshot.accountError) ? t.stale : '',
|
|
991
|
+
),
|
|
992
|
+
h(
|
|
993
|
+
'button',
|
|
994
|
+
{
|
|
995
|
+
type: 'button',
|
|
996
|
+
className: 'dbu-iconbtn',
|
|
997
|
+
title: t.refresh,
|
|
998
|
+
'aria-label': t.refresh,
|
|
999
|
+
'aria-busy': snapshot.status === 'loading' ? 'true' : 'false',
|
|
1000
|
+
'data-busy': snapshot.status === 'loading' ? 'true' : 'false',
|
|
1001
|
+
onClick: () => load(clientCtx, { force: true }),
|
|
1002
|
+
},
|
|
1003
|
+
h(RefreshIcon),
|
|
1004
|
+
),
|
|
1005
|
+
h(
|
|
1006
|
+
'button',
|
|
1007
|
+
{ type: 'button', className: 'dbu-iconbtn', title: t.close, 'aria-label': t.close, onClick: () => setState({ open: false }) },
|
|
1008
|
+
h(CloseIcon),
|
|
1009
|
+
),
|
|
1010
|
+
),
|
|
1011
|
+
h(
|
|
1012
|
+
'div',
|
|
1013
|
+
{ className: 'dbu-body' },
|
|
1014
|
+
h(
|
|
1015
|
+
'div',
|
|
1016
|
+
{ className: 'dbu-card' },
|
|
1017
|
+
h('div', { className: 'dbu-card__label' }, t.balance),
|
|
1018
|
+
account?.signedIn === false
|
|
1019
|
+
? h('div', { className: 'dbu-muted', style: { lineHeight: 1.45 } }, t.signedOut)
|
|
1020
|
+
: loadingFirst
|
|
1021
|
+
? h('div', { className: 'dbu-skel dbu-skel--line-lg', style: { width: '52%' } })
|
|
1022
|
+
: h(
|
|
1023
|
+
React.Fragment,
|
|
1024
|
+
null,
|
|
1025
|
+
h('div', { className: 'dbu-money' }, wallet ? fmtWallet(wallet) : '—'),
|
|
1026
|
+
bonus && bonus.total > 0
|
|
1027
|
+
? h(
|
|
1028
|
+
'div',
|
|
1029
|
+
{ className: 'dbu-row', style: { marginTop: '4px' } },
|
|
1030
|
+
h('span', { className: 'dbu-muted' }, t.bonus),
|
|
1031
|
+
h('span', { className: 'dbu-muted', style: { marginLeft: 'auto' } }, fmtWallet({ currency: bonus.currency, balance: String(bonus.total) })),
|
|
1032
|
+
)
|
|
1033
|
+
: null,
|
|
1034
|
+
accountErrorBlock(),
|
|
1035
|
+
),
|
|
1036
|
+
),
|
|
1037
|
+
h(
|
|
1038
|
+
'div',
|
|
1039
|
+
{ className: 'dbu-card' },
|
|
1040
|
+
h(
|
|
1041
|
+
'div',
|
|
1042
|
+
{ className: 'dbu-card__label' },
|
|
1043
|
+
t.usage,
|
|
1044
|
+
main
|
|
1045
|
+
? h('span', { className: 'dbu-chip', title: `${providerLabel(main.row.provider)} · ${main.row.model}` }, `${providerLabel(main.row.provider)} · ${main.row.model}`)
|
|
1046
|
+
: h('span', { className: 'dbu-chip' }, t.auto),
|
|
1047
|
+
),
|
|
1048
|
+
loadingFirst
|
|
1049
|
+
? h(
|
|
1050
|
+
React.Fragment,
|
|
1051
|
+
null,
|
|
1052
|
+
h('div', { className: 'dbu-skel dbu-skel--line-lg', style: { width: '38%' } }),
|
|
1053
|
+
h('div', { className: 'dbu-skel dbu-skel--line', style: { marginTop: '10px', width: '100%' } }),
|
|
1054
|
+
h('div', { className: 'dbu-skel dbu-skel--line', style: { marginTop: '6px', width: '100%', height: '32px' } }),
|
|
1055
|
+
)
|
|
1056
|
+
: usage
|
|
1057
|
+
? h(
|
|
1058
|
+
React.Fragment,
|
|
1059
|
+
null,
|
|
1060
|
+
h(
|
|
1061
|
+
'div',
|
|
1062
|
+
{ className: 'dbu-row--between' },
|
|
1063
|
+
h('div', null, h('div', { className: 'dbu-big' }, fmtTokens(today?.tokens || 0)), h('div', { className: 'dbu-muted' }, t.today)),
|
|
1064
|
+
h(
|
|
1065
|
+
'div',
|
|
1066
|
+
{ style: { textAlign: 'right' } },
|
|
1067
|
+
h('div', { className: 'dbu-big--sub' }, fmtTokens(totals?.tokens || 0)),
|
|
1068
|
+
h('div', { className: 'dbu-muted' }, t.total),
|
|
1069
|
+
),
|
|
1070
|
+
),
|
|
1071
|
+
h(
|
|
1072
|
+
'div',
|
|
1073
|
+
{ className: 'dbu-stats' },
|
|
1074
|
+
h(Stat, { label: t.input, value: fmtTokens(totals?.inputTokens || 0) }),
|
|
1075
|
+
h(Stat, { label: t.output, value: fmtTokens(totals?.outputTokens || 0) }),
|
|
1076
|
+
h(Stat, { label: cacheShare ? `${t.cache} ${cacheShare}%` : t.cache, value: fmtTokens(totals?.cacheReadTokens || 0) }),
|
|
1077
|
+
),
|
|
1078
|
+
h(MiniChart, { series: usage.series, label: chartsLabel }),
|
|
1079
|
+
h(
|
|
1080
|
+
'div',
|
|
1081
|
+
{ className: 'dbu-muted', style: { marginTop: '4px' } },
|
|
1082
|
+
`${t.last14} · ${(totals?.requests || 0).toLocaleString()} ${t.requestsSuffix}`,
|
|
1083
|
+
),
|
|
1084
|
+
)
|
|
1085
|
+
: h('div', { className: 'dbu-note' }, t.empty),
|
|
1086
|
+
),
|
|
1087
|
+
statusNote(),
|
|
1088
|
+
usage && usage.groups && usage.groups.length > 0
|
|
1089
|
+
? h(
|
|
1090
|
+
'div',
|
|
1091
|
+
{ className: 'dbu-section' },
|
|
1092
|
+
h(
|
|
1093
|
+
'div',
|
|
1094
|
+
{ className: 'dbu-section__head' },
|
|
1095
|
+
t.groups,
|
|
1096
|
+
h('span', { className: 'dbu-section__hint' }, t.starHint),
|
|
1097
|
+
),
|
|
1098
|
+
usage.groups.map((group) =>
|
|
1099
|
+
h(GroupRow, {
|
|
1100
|
+
key: group.provider,
|
|
1101
|
+
group,
|
|
1102
|
+
main: main?.row,
|
|
1103
|
+
primary: snapshot.primary,
|
|
1104
|
+
condensed: usage.groups.length === 1 && (group.models || []).length === 1,
|
|
1105
|
+
collapsed: snapshot.collapsed.includes(group.provider),
|
|
1106
|
+
onToggle: () => toggleGroup(group.provider),
|
|
1107
|
+
onStar,
|
|
1108
|
+
}),
|
|
1109
|
+
),
|
|
1110
|
+
)
|
|
1111
|
+
: null,
|
|
1112
|
+
platformBridge()
|
|
1113
|
+
? h(
|
|
1114
|
+
'button',
|
|
1115
|
+
{
|
|
1116
|
+
type: 'button',
|
|
1117
|
+
className: 'dbu-cta',
|
|
1118
|
+
title: t.openUsage,
|
|
1119
|
+
onClick: () => setState({ open: false, platform: 'usage' }),
|
|
1120
|
+
},
|
|
1121
|
+
h(ExternalIcon),
|
|
1122
|
+
t.openUsage,
|
|
1123
|
+
)
|
|
1124
|
+
: h(
|
|
1125
|
+
'a',
|
|
1126
|
+
{
|
|
1127
|
+
className: 'dbu-cta',
|
|
1128
|
+
href: account?.usageUrl || FALLBACK_USAGE_URL,
|
|
1129
|
+
target: '_blank',
|
|
1130
|
+
rel: 'noopener noreferrer',
|
|
1131
|
+
title: `${t.openUsage} · ${account?.usageUrl || FALLBACK_USAGE_URL}`,
|
|
1132
|
+
},
|
|
1133
|
+
h(ExternalIcon),
|
|
1134
|
+
t.openUsage,
|
|
1135
|
+
h('span', { className: 'dbu-sr' }, ` (${t.newWindow})`),
|
|
1136
|
+
),
|
|
1137
|
+
),
|
|
1138
|
+
),
|
|
1139
|
+
snapshot.platform ? h(PlatformSurface, { page: snapshot.platform }) : null,
|
|
1140
|
+
)
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
/* ---------------------------------------------------------------- *
|
|
1144
|
+
* Native Platform page (Desktop only)
|
|
1145
|
+
* ---------------------------------------------------------------- */
|
|
1146
|
+
|
|
1147
|
+
/* The Desktop shell owns one WebContentsView that renders the official Platform
|
|
1148
|
+
document above the page, with the account session injected by the main process.
|
|
1149
|
+
The view takes the main content area beside the sidebar — the strip on top is
|
|
1150
|
+
dressed as a page tab, so the sidebar and the rest of the shell stay usable. */
|
|
1151
|
+
function contentAreaRect() {
|
|
1152
|
+
const entry = state.entryEl
|
|
1153
|
+
let left = 0
|
|
1154
|
+
if (entry) {
|
|
1155
|
+
left = entry.getBoundingClientRect().right
|
|
1156
|
+
/* Walk out to the sidebar column, but stop before the column that spans the
|
|
1157
|
+
whole window (that is the app shell, not the sidebar). */
|
|
1158
|
+
let node = entry.parentElement
|
|
1159
|
+
for (let depth = 0; node && depth < 8; depth += 1) {
|
|
1160
|
+
const bounds = node.getBoundingClientRect()
|
|
1161
|
+
if (bounds.width > 480) break
|
|
1162
|
+
if (bounds.right > left) left = bounds.right
|
|
1163
|
+
node = node.parentElement
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
const viewport = window.innerWidth || 1280
|
|
1167
|
+
return { left, width: Math.max(320, viewport - left) }
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
function PlatformSurface({ page }) {
|
|
1171
|
+
const t = copy()
|
|
1172
|
+
const hostRef = useRef(null)
|
|
1173
|
+
const [status, setStatus] = useState('loading')
|
|
1174
|
+
const [attempt, setAttempt] = useState(0)
|
|
1175
|
+
const [area, setArea] = useState(contentAreaRect)
|
|
1176
|
+
const bridge = platformBridge()
|
|
1177
|
+
const usageUrl = state.account?.usageUrl || FALLBACK_USAGE_URL
|
|
1178
|
+
|
|
1179
|
+
function closePlatform() {
|
|
1180
|
+
setState({ platform: null, open: true })
|
|
1181
|
+
load(clientCtx, { force: true })
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
/* Keep clearing the sidebar when the window is resized or the sidebar toggles. */
|
|
1185
|
+
useEffect(() => {
|
|
1186
|
+
const onResize = () => setArea(contentAreaRect())
|
|
1187
|
+
window.addEventListener('resize', onResize)
|
|
1188
|
+
return () => window.removeEventListener('resize', onResize)
|
|
1189
|
+
}, [])
|
|
1190
|
+
|
|
1191
|
+
useEffect(() => {
|
|
1192
|
+
const node = hostRef.current
|
|
1193
|
+
if (!node || !bridge) return undefined
|
|
1194
|
+
let closed = false
|
|
1195
|
+
const bounds = () => {
|
|
1196
|
+
const rect = node.getBoundingClientRect()
|
|
1197
|
+
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height }
|
|
1198
|
+
}
|
|
1199
|
+
const fail = () => {
|
|
1200
|
+
if (!closed) setStatus('failed')
|
|
1201
|
+
}
|
|
1202
|
+
setStatus('loading')
|
|
1203
|
+
Promise.resolve()
|
|
1204
|
+
.then(() => bridge.open(page, bounds()))
|
|
1205
|
+
.then(() => {
|
|
1206
|
+
if (!closed) setStatus('loaded')
|
|
1207
|
+
})
|
|
1208
|
+
.catch(fail)
|
|
1209
|
+
const observer = typeof ResizeObserver === 'function'
|
|
1210
|
+
? new ResizeObserver(() => {
|
|
1211
|
+
Promise.resolve(bridge.setBounds(bounds())).catch(fail)
|
|
1212
|
+
})
|
|
1213
|
+
: null
|
|
1214
|
+
observer?.observe(node)
|
|
1215
|
+
return () => {
|
|
1216
|
+
closed = true
|
|
1217
|
+
observer?.disconnect()
|
|
1218
|
+
/* The window teardown may drop the IPC receiver before React unmounts. */
|
|
1219
|
+
Promise.resolve(bridge.close()).catch(() => {})
|
|
1220
|
+
}
|
|
1221
|
+
}, [bridge, page, attempt])
|
|
1222
|
+
|
|
1223
|
+
useEffect(() => {
|
|
1224
|
+
const onKey = (event) => {
|
|
1225
|
+
if (event.defaultPrevented || event.key !== 'Escape') return
|
|
1226
|
+
event.preventDefault()
|
|
1227
|
+
closePlatform()
|
|
1228
|
+
}
|
|
1229
|
+
window.addEventListener('keydown', onKey)
|
|
1230
|
+
const focusTimer = window.setTimeout(() => {
|
|
1231
|
+
const close = document.getElementById(PLATFORM_BACK_ID)
|
|
1232
|
+
if (close) close.focus()
|
|
1233
|
+
}, 0)
|
|
1234
|
+
return () => {
|
|
1235
|
+
window.removeEventListener('keydown', onKey)
|
|
1236
|
+
window.clearTimeout(focusTimer)
|
|
1237
|
+
}
|
|
1238
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
1239
|
+
}, [])
|
|
1240
|
+
|
|
1241
|
+
/* Clicking anywhere else in the shell hands the page back to the app. */
|
|
1242
|
+
useEffect(() => {
|
|
1243
|
+
const onPointer = (event) => {
|
|
1244
|
+
const surface = document.querySelector('.dbu-platform')
|
|
1245
|
+
if (!surface || surface.contains(event.target)) return
|
|
1246
|
+
closePlatform()
|
|
1247
|
+
}
|
|
1248
|
+
window.addEventListener('pointerdown', onPointer, true)
|
|
1249
|
+
return () => window.removeEventListener('pointerdown', onPointer, true)
|
|
1250
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
1251
|
+
}, [])
|
|
1252
|
+
|
|
1253
|
+
return h(
|
|
1254
|
+
'div',
|
|
1255
|
+
{
|
|
1256
|
+
className: 'dbu-platform',
|
|
1257
|
+
style: { left: `${area.left}px`, width: `${area.width}px` },
|
|
1258
|
+
role: 'region',
|
|
1259
|
+
'aria-label': t.usagePage,
|
|
1260
|
+
},
|
|
1261
|
+
h(
|
|
1262
|
+
'div',
|
|
1263
|
+
{ className: 'dbu-platform__bar' },
|
|
1264
|
+
h(
|
|
1265
|
+
'div',
|
|
1266
|
+
{ className: 'dbu-platform__tab' },
|
|
1267
|
+
h('span', { className: 'dbu-platform__tabdot', 'aria-hidden': 'true' }),
|
|
1268
|
+
h('span', { className: 'dbu-platform__tablabel' }, t.usagePage),
|
|
1269
|
+
h(
|
|
1270
|
+
'button',
|
|
1271
|
+
{
|
|
1272
|
+
id: PLATFORM_BACK_ID,
|
|
1273
|
+
type: 'button',
|
|
1274
|
+
className: 'dbu-platform__close',
|
|
1275
|
+
title: t.close,
|
|
1276
|
+
'aria-label': t.close,
|
|
1277
|
+
onClick: closePlatform,
|
|
1278
|
+
},
|
|
1279
|
+
h(CloseIcon),
|
|
1280
|
+
),
|
|
1281
|
+
),
|
|
1282
|
+
),
|
|
1283
|
+
h(
|
|
1284
|
+
'div',
|
|
1285
|
+
{ ref: hostRef, className: 'dbu-platform__viewport' },
|
|
1286
|
+
status === 'loaded'
|
|
1287
|
+
? null
|
|
1288
|
+
: h(
|
|
1289
|
+
'div',
|
|
1290
|
+
{ className: 'dbu-platform__status', role: 'status' },
|
|
1291
|
+
status === 'failed'
|
|
1292
|
+
? h(
|
|
1293
|
+
React.Fragment,
|
|
1294
|
+
null,
|
|
1295
|
+
h('span', { className: 'dbu-platform__fail' }, t.platformFailed),
|
|
1296
|
+
h(
|
|
1297
|
+
'div',
|
|
1298
|
+
{ className: 'dbu-platform__actions' },
|
|
1299
|
+
h(
|
|
1300
|
+
'button',
|
|
1301
|
+
{ type: 'button', className: 'dbu-retry', onClick: () => setAttempt((value) => value + 1) },
|
|
1302
|
+
t.retry,
|
|
1303
|
+
),
|
|
1304
|
+
h(
|
|
1305
|
+
'a',
|
|
1306
|
+
{ className: 'dbu-retry', href: usageUrl, target: '_blank', rel: 'noopener noreferrer' },
|
|
1307
|
+
t.browser,
|
|
1308
|
+
),
|
|
1309
|
+
),
|
|
1310
|
+
)
|
|
1311
|
+
: h(
|
|
1312
|
+
React.Fragment,
|
|
1313
|
+
null,
|
|
1314
|
+
h('span', { className: 'dbu-platform__spinner', 'aria-hidden': 'true' }),
|
|
1315
|
+
h('span', null, t.platformLoading),
|
|
1316
|
+
),
|
|
1317
|
+
),
|
|
1318
|
+
),
|
|
1319
|
+
)
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
/* ---------------------------------------------------------------- *
|
|
1323
|
+
* Plugin
|
|
1324
|
+
* ---------------------------------------------------------------- */
|
|
1325
|
+
|
|
1326
|
+
return {
|
|
1327
|
+
inject: ['slots', 'locale', 'remote', 'remote.account'],
|
|
1328
|
+
|
|
1329
|
+
apply(ctx) {
|
|
1330
|
+
clientCtx = ctx
|
|
1331
|
+
|
|
1332
|
+
ctx.effect(installStyles)
|
|
1333
|
+
|
|
1334
|
+
/* Repaint copy when the reader switches the UI language. */
|
|
1335
|
+
ctx.effect(() => {
|
|
1336
|
+
if (typeof ctx.on !== 'function') return () => {}
|
|
1337
|
+
const dispose = ctx.on('locale/change', () => setState({}))
|
|
1338
|
+
return () => dispose()
|
|
1339
|
+
})
|
|
1340
|
+
|
|
1341
|
+
ctx.slots.inject('sidebar.footer.action', () =>
|
|
1342
|
+
ctx.slots.register(
|
|
1343
|
+
{
|
|
1344
|
+
name: 'sidebar.footer.action',
|
|
1345
|
+
id: 'balance-usage',
|
|
1346
|
+
order: 40,
|
|
1347
|
+
label: () => copy().entryTitle,
|
|
1348
|
+
},
|
|
1349
|
+
FooterAction,
|
|
1350
|
+
),
|
|
1351
|
+
)
|
|
1352
|
+
|
|
1353
|
+
ctx.slots.inject('shell.overlay', () =>
|
|
1354
|
+
ctx.slots.register({ name: 'shell.overlay', id: 'balance-usage-panel', order: 40 }, Panel),
|
|
1355
|
+
)
|
|
1356
|
+
|
|
1357
|
+
/* Settings are authoritative on the Host; localStorage is only the fallback
|
|
1358
|
+
for a build whose Host half predates the prefs route. */
|
|
1359
|
+
ctx.effect(() => {
|
|
1360
|
+
let alive = true
|
|
1361
|
+
readPrefs()
|
|
1362
|
+
.then((values) => {
|
|
1363
|
+
if (!alive || !values) return
|
|
1364
|
+
const patch = {}
|
|
1365
|
+
if (values.primary && typeof values.primary.provider === 'string') {
|
|
1366
|
+
patch.primary = values.primary
|
|
1367
|
+
try {
|
|
1368
|
+
globalThis.localStorage?.setItem(KEY_PRIMARY, JSON.stringify(values.primary))
|
|
1369
|
+
} catch {
|
|
1370
|
+
/* ignore */
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
if (Array.isArray(values.collapsed)) {
|
|
1374
|
+
patch.collapsed = values.collapsed
|
|
1375
|
+
try {
|
|
1376
|
+
globalThis.localStorage?.setItem(KEY_COLLAPSED, JSON.stringify(values.collapsed))
|
|
1377
|
+
} catch {
|
|
1378
|
+
/* ignore */
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
if (Object.keys(patch).length > 0) setState(patch)
|
|
1382
|
+
})
|
|
1383
|
+
.catch(() => {})
|
|
1384
|
+
return () => {
|
|
1385
|
+
alive = false
|
|
1386
|
+
}
|
|
1387
|
+
})
|
|
1388
|
+
|
|
1389
|
+
ctx.effect(() => {
|
|
1390
|
+
const warm = setTimeout(() => load(ctx).catch(() => {}), 1_500)
|
|
1391
|
+
|
|
1392
|
+
const due = () => Date.now() - state.updatedAt >= (state.open ? REFRESH_OPEN_MS : REFRESH_IDLE_MS)
|
|
1393
|
+
|
|
1394
|
+
timer = setInterval(() => {
|
|
1395
|
+
if (due()) load(ctx).catch(() => {})
|
|
1396
|
+
}, TICK_MS)
|
|
1397
|
+
|
|
1398
|
+
/* Coming back to the app should never show numbers from the last time it was
|
|
1399
|
+
in front, even if the interval has not elapsed yet. */
|
|
1400
|
+
const wake = () => {
|
|
1401
|
+
if (document.visibilityState === 'hidden') return
|
|
1402
|
+
if (Date.now() - state.updatedAt < 2_000) return
|
|
1403
|
+
load(ctx, { force: true }).catch(() => {})
|
|
1404
|
+
}
|
|
1405
|
+
window.addEventListener('focus', wake)
|
|
1406
|
+
document.addEventListener('visibilitychange', wake)
|
|
1407
|
+
|
|
1408
|
+
return () => {
|
|
1409
|
+
clearTimeout(warm)
|
|
1410
|
+
if (timer) clearInterval(timer)
|
|
1411
|
+
timer = null
|
|
1412
|
+
window.removeEventListener('focus', wake)
|
|
1413
|
+
document.removeEventListener('visibilitychange', wake)
|
|
1414
|
+
}
|
|
1415
|
+
})
|
|
1416
|
+
},
|
|
1417
|
+
}
|
|
1418
|
+
},
|
|
1419
|
+
})
|