Files
codexHalo/src/composables/useUsage.js
T

57 lines
1.2 KiB
JavaScript
Raw Normal View History

import { onMounted, onUnmounted, readonly, shallowRef } from 'vue'
function demoSnapshot() {
const now = Date.now()
return {
shortWindow: null,
weekWindow: {
remainingPercent: 21,
usedPercent: 79,
resetsAt: now + 3 * 24 * 60 * 60 * 1000 + 8 * 60 * 60 * 1000,
},
status: '浏览器预览数据',
updatedAt: now,
}
}
export function useUsage() {
const snapshot = shallowRef(null)
const isRefreshing = shallowRef(false)
let unsubscribe
async function refresh() {
if (!window.codexHalo) {
snapshot.value = demoSnapshot()
return
}
isRefreshing.value = true
try {
snapshot.value = await window.codexHalo.refreshUsage()
} finally {
isRefreshing.value = false
}
}
onMounted(async () => {
if (!window.codexHalo) {
snapshot.value = demoSnapshot()
return
}
unsubscribe = window.codexHalo.onUsage((nextSnapshot) => {
snapshot.value = nextSnapshot
isRefreshing.value = false
})
snapshot.value = await window.codexHalo.getUsage()
})
onUnmounted(() => unsubscribe?.())
return {
snapshot: readonly(snapshot),
isRefreshing: readonly(isRefreshing),
refresh,
}
}