-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpopup.tsx
More file actions
470 lines (416 loc) · 17.5 KB
/
popup.tsx
File metadata and controls
470 lines (416 loc) · 17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
import "./reset.css"
import eruda from "eruda"
import { useCallback, useEffect, useMemo, useState } from "react"
import { RefreshButton } from "./components/RefreshButton"
import { SettingsButton } from "./components/SettingsButton"
import { ServiceStatusButton } from "./components/ServiceStatusButton"
import { SettingsPanel } from "./components/SettingsPanel"
import { ServiceStatusView } from "./components/ServiceStatusView"
import { ThemeSwitcher } from "./components/ThemeSwitcher"
import LoginPrompt from "./components/LoginPrompt"
import {
SubscriptionCardSkeleton,
UsageDisplaySkeleton
} from "./components/Skeleton"
import { SubscriptionCard } from "./components/SubscriptionCard"
import { UsageDisplay } from "./components/UsageDisplay"
import { useAuth } from "./hooks/useAuth"
import { useDashboard } from "./hooks/useDashboard"
import { useSubscriptions } from "./hooks/useSubscriptions"
import { useSettings } from "./hooks/useSettings"
import { usePaygoUsageStats } from "./hooks/usePaygoUsageStats"
import { useServiceStatus } from "./hooks/useServiceStatus"
import packageJson from "./package.json"
import { useResetWindowTracker } from "./hooks/useResetWindowTracker"
import { useVersionCheck } from "./hooks/useVersionCheck"
import { browserAPI } from "./lib/browser-api"
import { extractResetTimes } from "./lib/utils/resetTime"
import { ViewType, ThemeType } from "./types"
// 在开发环境中启用 Eruda 调试工具
if (process.env.NODE_ENV === "development") {
eruda.init()
}
// 更新提示横幅24小时抑制配置
const UPDATE_BANNER_SUPPRESS_KEY = "update_banner_suppressed_until"
// 检查更新提示横幅是否在抑制期内
const isBannerSuppressed = (): boolean => {
try {
const suppressUntil = localStorage.getItem(UPDATE_BANNER_SUPPRESS_KEY)
if (suppressUntil && Date.now() < parseInt(suppressUntil)) {
return true
}
// 过期则清除
if (suppressUntil) {
localStorage.removeItem(UPDATE_BANNER_SUPPRESS_KEY)
}
} catch (error) {
// 忽略 localStorage 错误
}
return false
}
function IndexPopup() {
const [currentView, setCurrentView] = useState<ViewType>(ViewType.MAIN)
const [isRefreshing, setIsRefreshing] = useState(false)
const [updateBannerDismissed, setUpdateBannerDismissed] = useState(false)
const { tokenData, loading: authLoading, retry } = useAuth()
const { settings, loading: settingsLoading, saveSettings, resetSettings } = useSettings()
const { hasUpdate, latestVersion, releaseUrl } = useVersionCheck()
// 使用 Hook 获取数据
const {
dashboard,
loading: dashboardLoading,
error: dashboardError,
refresh: refreshDashboard
} = useDashboard(tokenData.isValid)
const {
subscriptions,
loading: subscriptionsLoading,
error: subscriptionsError,
refresh: refreshSubscriptions
} = useSubscriptions(tokenData.isValid)
const hasPaygo = useMemo(
() => subscriptions.some((sub) => sub.subscriptionPlanName.includes("PAYGO")),
[subscriptions]
)
const {
stats: paygoUsageStats,
loading: paygoUsageLoading,
error: paygoUsageError,
refresh: refreshPaygoUsage
} = usePaygoUsageStats(tokenData.isValid && hasPaygo)
const {
serviceStatus,
groupRatioConfig,
loading: serviceStatusLoading,
error: serviceStatusError,
refresh: refreshServiceStatus
} = useServiceStatus()
const loading = authLoading || dashboardLoading || subscriptionsLoading || isRefreshing
// 刷新所有数据 - 使用 useCallback 避免不必要的依赖更新
const handleRefresh = useCallback(async () => {
// 防止重复刷新
if (!tokenData.isValid || isRefreshing) {
return
}
setIsRefreshing(true)
try {
await Promise.all([
refreshDashboard(),
refreshSubscriptions(),
hasPaygo ? refreshPaygoUsage() : Promise.resolve()
])
} finally {
setIsRefreshing(false)
}
}, [tokenData.isValid, isRefreshing, refreshDashboard, refreshSubscriptions, hasPaygo, refreshPaygoUsage])
// 打开设置
const handleOpenSettings = () => {
setCurrentView(ViewType.SETTINGS)
}
// 关闭设置
const handleCloseSettings = () => {
setCurrentView(ViewType.MAIN)
}
// 打开服务状态监控
const handleOpenServiceStatus = () => {
setCurrentView(ViewType.SERVICE_STATUS)
}
// 关闭服务状态监控
const handleCloseServiceStatus = () => {
setCurrentView(ViewType.MAIN)
}
// 切换主题
const handleThemeChange = (theme: ThemeType) => {
console.log("[Popup] 用户点击主题切换按钮")
console.log("[Popup] 当前主题:", settings.theme)
console.log("[Popup] 目标主题:", theme)
saveSettings({ theme })
.then((success) => {
console.log("[Popup] 主题保存结果:", success)
if (success) {
console.log("[Popup] 主题切换成功,新主题:", theme)
} else {
console.error("[Popup] 主题切换失败")
}
})
.catch((error) => {
console.error("[Popup] 主题切换异常:", error)
})
}
// 处理"稍后提醒"按钮点击 - 24小时抑制
const handleRemindLater = () => {
const suppressUntil = Date.now() + 24 * 60 * 60 * 1000 // 24小时后
localStorage.setItem(UPDATE_BANNER_SUPPRESS_KEY, suppressUntil.toString())
setUpdateBannerDismissed(true) // 同时在当前会话中隐藏
}
// popup 打开时更新图标状态
// 注意:不再主动调用 handleRefresh(),因为优化后的 hooks 会自动从缓存加载数据
useEffect(() => {
// 非阻塞地通知 background 更新图标状态
// 使用 Promise 避免阻塞渲染
Promise.resolve().then(() => {
browserAPI.runtime.sendMessage({
action: "updateIcon",
isAuthenticated: tokenData.isValid,
token: tokenData.authToken
}).catch(() => {
// 忽略错误(background 可能还未初始化)
})
})
// Popup 已打开,hooks 将自动从缓存加载数据(秒开优化)
}, [tokenData.isValid])
// 统一的自动刷新定时器
useEffect(() => {
if (!tokenData.isValid) {
return
}
// 优先使用用户设置,否则使用默认30秒
const interval = settings.autoRefreshEnabled
? settings.autoRefreshInterval * 1000
: 30 * 1000
const timer = setInterval(() => {
// 直接调用刷新函数,避免依赖 handleRefresh 引用
refreshDashboard()
refreshSubscriptions()
if (hasPaygo) {
refreshPaygoUsage() // 自动刷新 PAYGO 用量统计
}
}, interval)
return () => clearInterval(timer)
}, [tokenData.isValid, settings.autoRefreshEnabled, settings.autoRefreshInterval, refreshDashboard, refreshSubscriptions, hasPaygo, refreshPaygoUsage])
// 检查是否有符合规则的套餐(非 PAYGO、活跃中、额度未满、有剩余重置次数)
const hasEligibleSubscriptions = (): boolean => {
return subscriptions.some((sub) => {
const basicCheck =
!sub.subscriptionPlanName.includes("PAYGO") &&
sub.isActive &&
sub.subscriptionStatus === "活跃中"
if (!basicCheck) return false
// 额度未满
const notFull = sub.currentCredits < sub.subscriptionPlan.creditLimit
// 有剩余重置次数
const hasResetTimes = sub.resetTimes > 0
return notFull && hasResetTimes
})
}
// 窗口开始时的统一刷新回调
const onWindowStartRefresh = async (): Promise<void> => {
await Promise.all([refreshDashboard(), refreshSubscriptions()])
}
// 重置窗口追踪器 - 只追踪符合条件的套餐
const resetTimes = useMemo(() => {
if (subscriptions.length === 0) return []
// 筛选符合条件的套餐
const eligibleSubs = subscriptions.filter((sub) => {
const basicCheck =
!sub.subscriptionPlanName.includes("PAYGO") &&
sub.isActive &&
sub.subscriptionStatus === "活跃中"
if (!basicCheck) return false
// 额度未满
const notFull = sub.currentCredits < sub.subscriptionPlan.creditLimit
// 有剩余重置次数
const hasResetTimes = sub.resetTimes > 0
return notFull && hasResetTimes
})
// 只提取符合条件的套餐的窗口内冷却时间
return extractResetTimes(eligibleSubs, true)
}, [subscriptions])
const resetWindowStatus = useResetWindowTracker({
enabled: settings.scheduledReset.enabled && tokenData.isValid,
onWindowStartRefresh: onWindowStartRefresh,
hasEligibleSubscriptions: hasEligibleSubscriptions,
onResetTriggered: () => {
handleRefresh()
},
cooldownEndTimes: resetTimes
})
// 首次加载时同步官网主题
useEffect(() => {
const syncWebsiteTheme = async () => {
try {
const result = await browserAPI.storage.local.get("88code_theme")
const websiteTheme = result["88code_theme"]
console.log("[Popup] 首次加载,读取到官网主题:", websiteTheme)
if (websiteTheme === "dark" && settings.theme !== ThemeType.DARK) {
console.log("[Popup] 同步官网深色主题")
await saveSettings({ theme: ThemeType.DARK })
} else if (websiteTheme === "light" && settings.theme !== ThemeType.LIGHT) {
console.log("[Popup] 同步官网浅色主题")
await saveSettings({ theme: ThemeType.LIGHT })
}
} catch (error) {
console.error("[Popup] 读取官网主题失败:", error)
}
}
// 只在首次加载时同步(settings.loading 变为 false 时)
if (!settingsLoading) {
syncWebsiteTheme()
}
}, [settingsLoading])
// 应用主题到 DOM
useEffect(() => {
const root = document.documentElement
console.log("[Popup] 应用主题到 DOM,theme:", settings.theme)
if (settings.theme === ThemeType.DARK) {
root.classList.add("dark")
console.log("[Popup] DOM 应用深色主题")
} else {
root.classList.remove("dark")
console.log("[Popup] DOM 应用浅色主题")
}
}, [settings.theme])
return (
<div className="min-w-[460px] w-[460px] h-[600px] bg-white dark:bg-gray-900">
{currentView === ViewType.SETTINGS ? (
<SettingsPanel
settings={settings}
onSave={saveSettings}
onReset={resetSettings}
onClose={handleCloseSettings}
/>
) : currentView === ViewType.SERVICE_STATUS ? (
<ServiceStatusView
serviceStatus={serviceStatus}
groupRatioConfig={groupRatioConfig}
loading={serviceStatusLoading}
error={serviceStatusError}
onBack={handleCloseServiceStatus}
onRefresh={refreshServiceStatus}
/>
) : (
<div className="flex flex-col h-full overflow-y-auto">
{!authLoading && !tokenData.isValid ? (
<LoginPrompt onRetry={retry} />
) : (
<div className="flex flex-col space-y-4 p-6">
{/* 头部 */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold tracking-tight">
<span className="bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent">
88Code
</span>
{" "}
<span className="text-orange-600 dark:text-orange-400">
Cost
</span>
</h1>
<div className="flex items-center space-x-2">
<ThemeSwitcher currentTheme={settings.theme} onThemeChange={handleThemeChange} />
<ServiceStatusButton onClick={handleOpenServiceStatus} />
<SettingsButton onClick={handleOpenSettings} />
{tokenData.isValid && (
<RefreshButton loading={loading} onRefresh={handleRefresh} />
)}
</div>
</div>
</div>
{/* 版本更新提示横幅 - 极简单行设计 */}
{tokenData.isValid && hasUpdate && !updateBannerDismissed && !isBannerSuppressed() && latestVersion && releaseUrl && (
<div className="rounded-lg border border-green-200 bg-green-50 px-4 py-3 dark:border-green-900 dark:bg-green-900/20">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
<span className="text-base">🎉</span>
<p className="text-sm font-medium text-green-800 dark:text-green-200">
新版本 {latestVersion} 可用
</p>
</div>
<div className="flex items-center gap-2">
<a
href={releaseUrl}
target="_blank"
rel="noopener noreferrer"
className="rounded-md bg-green-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-green-700 transition-colors whitespace-nowrap"
title="在GitHub查看更新详情"
>
前往更新
</a>
<button
onClick={handleRemindLater}
className="rounded-md px-3 py-1.5 text-xs font-medium text-green-700 hover:bg-green-100 dark:text-green-300 dark:hover:bg-green-900/40 transition-colors whitespace-nowrap"
title="点击后24小时内不再提醒"
>
稍后提醒
</button>
</div>
</div>
</div>
)}
{/* 使用情况 */}
{tokenData.isValid && dashboard && (
<UsageDisplay dashboard={dashboard} defaultExpanded={settings.showDetailedTokenStats} />
)}
{(authLoading || (tokenData.isValid && !dashboard && dashboardLoading)) && (
<UsageDisplaySkeleton />
)}
{/* 错误提示 */}
{tokenData.isValid && (dashboardError || subscriptionsError) && (
<div className="rounded-lg border border-red-200 bg-red-50 p-4 dark:border-red-900 dark:bg-red-900/20">
<p className="text-sm text-red-800 dark:text-red-200">
{dashboardError || subscriptionsError}
</p>
</div>
)}
{/* 套餐列表 */}
{tokenData.isValid && subscriptions.length > 0 && (
<div className="space-y-2">
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
套餐列表
</h2>
<div className="space-y-3">
{subscriptions.map((subscription) => (
<SubscriptionCard
key={subscription.id}
subscription={subscription}
onRefresh={handleRefresh}
paygoUsageStats={paygoUsageStats}
paygoUsageLoading={paygoUsageLoading}
paygoUsageError={paygoUsageError}
/>
))}
</div>
</div>
)}
{/* 套餐加载骨架屏 */}
{(authLoading ||
(tokenData.isValid &&
subscriptions.length === 0 &&
subscriptionsLoading)) && (
<div className="space-y-2">
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
套餐列表
</h2>
<div className="space-y-3">
<SubscriptionCardSkeleton />
<SubscriptionCardSkeleton />
</div>
</div>
)}
{/* 版本信息和 GitHub */}
<div className="border-t border-gray-200 pt-4 dark:border-gray-700">
<div className="flex items-center justify-center gap-2">
<p className="text-center text-xs text-gray-500 dark:text-gray-400">
88Code Cost v{packageJson.version}
</p>
<a
href="https://github.com/byebye-code/88code-cost"
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center justify-center w-8 h-8 rounded-full bg-gray-100 hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700 transition-all"
title="Star on GitHub"
>
<svg className="w-4 h-4 text-gray-700 dark:text-gray-300" viewBox="0 0 16 16" fill="currentColor">
<path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/>
</svg>
</a>
</div>
</div>
</div>
)}
</div>
)}
</div>
)
}
export default IndexPopup