| 1 | import { UsageProviderKind } from "@t3tools/contracts"; |
| 2 | import * as Schema from "effect/Schema"; |
| 3 | |
| 4 | import { getLocalStorageItem, setLocalStorageItem } from "../../hooks/useLocalStorage"; |
| 5 | |
| 6 | const STORAGE_KEY = "t3code:usage-page-preferences:v1"; |
| 7 | const UsagePagePreferencesSchema = Schema.Struct({ |
| 8 | metric: Schema.Literals(["cost", "tokens", "limits"]), |
| 9 | windowDays: Schema.Literals([1, 7, 30, 90]), |
| 10 | /** Providers filtered out of the page. Stored as hidden so new providers show by default. */ |
| 11 | hiddenProviders: Schema.optional(Schema.Array(UsageProviderKind)), |
| 12 | }); |
| 13 | export type UsagePagePreferences = Omit<typeof UsagePagePreferencesSchema.Type, "metric"> & { |
| 14 | readonly metric: "cost" | "tokens"; |
| 15 | }; |
| 16 | |
| 17 | const DEFAULT_PREFERENCES: UsagePagePreferences = { metric: "cost", windowDays: 30 }; |
| 18 | |
| 19 | export function readUsagePagePreferences(): UsagePagePreferences { |
| 20 | try { |
| 21 | const saved = getLocalStorageItem(STORAGE_KEY, UsagePagePreferencesSchema); |
| 22 | return saved === null |
| 23 | ? DEFAULT_PREFERENCES |
| 24 | : { ...saved, metric: saved.metric === "limits" ? "cost" : saved.metric }; |
| 25 | } catch (error) { |
| 26 | console.error("Could not read Usage page preferences.", error); |
| 27 | return DEFAULT_PREFERENCES; |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | export function saveUsagePagePreferences(preferences: UsagePagePreferences): void { |
| 32 | try { |
| 33 | setLocalStorageItem(STORAGE_KEY, preferences, UsagePagePreferencesSchema); |
| 34 | } catch (error) { |
| 35 | console.error("Could not save Usage page preferences.", error); |
| 36 | } |
| 37 | } |