The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 321 lines 11.5 KB
Raw
1 import { HStack, ProgressView, Spacer, Text, VStack } from "@expo/ui/swift-ui";
2 import {
3 accessibilityElement,
4 accessibilityLabel,
5 containerBackground,
6 environment,
7 fixedSize,
8 font,
9 foregroundStyle,
10 frame,
11 layoutPriority,
12 lineLimit,
13 progressViewStyle,
14 tint,
15 widgetURL,
16 } from "@expo/ui/swift-ui/modifiers";
17 import { createWidget, type WidgetEnvironment } from "expo-widgets";
18
19 import type { SubscriptionUsageSnapshot as SubscriptionUsageProps } from "./subscriptionUsageSnapshot";
20
21 type UsageConfiguration = {
22 codexPeriod?: "auto" | "session" | "weekly";
23 claudePeriod?: "auto" | "session" | "weekly";
24 };
25
26 function SubscriptionUsage(
27 props: SubscriptionUsageProps,
28 widgetEnvironment: WidgetEnvironment<UsageConfiguration> & {
29 showsContainerBackground?: boolean;
30 },
31 ) {
32 "widget";
33 // The extension evaluates this function without the app's module scope.
34 const family = widgetEnvironment.widgetFamily;
35 // Gallery snapshots can render an old timeline entry after it has expired.
36 const now = Math.max(widgetEnvironment.date?.getTime() ?? 0, Date.now());
37 const accessory = family === "accessoryRectangular";
38 const compact =
39 family === "systemSmall" || accessory || widgetEnvironment.levelOfDetail === "simplified";
40 const dense = family === "systemSmall" || family === "systemMedium";
41 const limit = family === "systemExtraLarge" ? 6 : family === "systemLarge" ? 4 : 2;
42 const monochrome =
43 widgetEnvironment.widgetRenderingMode !== "fullColor" || widgetEnvironment.isLuminanceReduced;
44 const mode = props.theme?.mode;
45 const appearance =
46 mode === "light" || mode === "dark"
47 ? mode
48 : widgetEnvironment.colorScheme === "dark"
49 ? "dark"
50 : "light";
51 // StandBy can remove the card even in full color; text must then follow the host.
52 const palette =
53 !accessory && !monochrome && widgetEnvironment.showsContainerBackground !== false
54 ? props.theme?.[appearance]
55 : undefined;
56 const primary = palette?.foreground ?? "primary";
57 const secondary = palette?.secondary ?? "secondary";
58 // English until the app publishes its first snapshot in the UI language.
59 const text = props.text ?? {
60 refresh: "Open T3 to refresh",
61 noSessionLimit: "No session limit reported",
62 noWeeklyLimit: "No weekly limit reported",
63 subscriptionRemaining: "Subscription remaining",
64 percentLeft: "{remaining}% left",
65 windowPercentLeft: "{window} · {remaining}% left",
66 notApplicable: "N/A",
67 openApp: "Open T3",
68 noLimits: "No subscription limits available.",
69 asOf: "As of {time}",
70 tapToConnect: "Tap to connect in T3",
71 providerAccessibility: "{provider}. {detail}.",
72 windowAccessibility: "{provider}, {window}, {remaining} percent remaining. {reset}. {detail}.",
73 moreInApp: {} as Record<string, string>,
74 };
75 const providers = props.providers ?? [
76 // oxlint-disable-next-line t3code/no-untranslated-copy -- widget fallback until the app publishes translated text
77 { name: "Codex", detail: "Open T3 to connect", windows: [], expiresAt: 0 },
78 // oxlint-disable-next-line t3code/no-untranslated-copy -- widget fallback until the app publishes translated text
79 { name: "Claude", detail: "Open T3 to connect", windows: [], expiresAt: 0 },
80 ];
81 const columns = providers.map((provider) => {
82 const stale = provider.windows.length > 0 && now >= provider.expiresAt;
83 const period =
84 widgetEnvironment.configuration?.[
85 provider.name === "Claude" ? "claudePeriod" : "codexPeriod"
86 ] ?? "auto";
87 const windows = stale
88 ? []
89 : provider.windows.filter((window) => period === "auto" || window.kind === period);
90 const tightest = windows.reduce<(typeof windows)[number] | undefined>(
91 (result, window) => (!result || window.remaining < result.remaining ? window : result),
92 undefined,
93 );
94 const compactWindows = [
95 windows.find((window) => window.kind === "session"),
96 windows.find((window) => window.kind === "weekly"),
97 ].filter((window) => window !== undefined);
98 const shown =
99 accessory || widgetEnvironment.levelOfDetail === "simplified"
100 ? tightest
101 ? [tightest]
102 : []
103 : family === "systemSmall" && compactWindows.length > 0
104 ? compactWindows
105 : period === "auto" && compactWindows.length > 0
106 ? [
107 ...compactWindows,
108 ...windows.filter((window) => !compactWindows.includes(window)),
109 ].slice(0, limit)
110 : windows.slice(0, limit);
111 const detail = stale
112 ? text.refresh
113 : period !== "auto" && windows.length === 0 && provider.windows.length > 0
114 ? period === "session"
115 ? text.noSessionLimit
116 : text.noWeeklyLimit
117 : provider.detail;
118 const hiddenCount =
119 (period === "auto" ? (provider.totalWindows ?? windows.length) : windows.length) - limit;
120 const barModifiers = [
121 progressViewStyle("linear"),
122 frame({ height: 4 }),
123 ...(monochrome ? [] : [tint(provider.name === "Claude" ? "#d97757" : "#8e8e93")]),
124 ];
125 if (accessory) {
126 return (
127 <VStack
128 key={provider.name}
129 alignment="leading"
130 spacing={2}
131 modifiers={[
132 accessibilityElement("ignore"),
133 accessibilityLabel(
134 tightest
135 ? text.windowAccessibility
136 .replace("{provider}", provider.name)
137 .replace("{window}", tightest.label)
138 .replace("{remaining}", String(tightest.remaining))
139 .replace("{reset}", tightest.reset)
140 .replace("{detail}", provider.detail)
141 : text.providerAccessibility
142 .replace("{provider}", provider.name)
143 .replace("{detail}", detail),
144 ),
145 ]}
146 >
147 <HStack spacing={4}>
148 <Text
149 modifiers={[
150 font({ textStyle: "caption", weight: "semibold" }),
151 lineLimit(1),
152 foregroundStyle(primary),
153 ]}
154 >
155 {provider.name}
156 {tightest ? ` · ${tightest.label}` : ""}
157 </Text>
158 <Spacer />
159 <Text
160 modifiers={[
161 font({ textStyle: "caption", weight: "semibold" }),
162 lineLimit(1),
163 layoutPriority(1),
164 foregroundStyle(primary),
165 ]}
166 >
167 {tightest
168 ? text.percentLeft.replace("{remaining}", String(tightest.remaining))
169 : period !== "auto" && !stale && provider.windows.length > 0
170 ? text.notApplicable
171 : text.openApp}
172 </Text>
173 </HStack>
174 {tightest ? (
175 <ProgressView value={tightest.remaining / 100} modifiers={barModifiers} />
176 ) : null}
177 </VStack>
178 );
179 }
180 return (
181 <VStack
182 key={provider.name}
183 alignment="leading"
184 spacing={dense ? 1 : compact ? 2 : 4}
185 modifiers={[
186 frame({ maxWidth: Infinity, alignment: "leading" }),
187 fixedSize({ horizontal: false, vertical: true }),
188 ]}
189 >
190 <Text
191 modifiers={[
192 font({ textStyle: compact ? "caption" : "headline", weight: "bold" }),
193 lineLimit(1),
194 foregroundStyle(primary),
195 ]}
196 >
197 {provider.name}
198 </Text>
199 {!compact || shown.length === 0 ? (
200 <Text
201 modifiers={[font({ textStyle: "caption2" }), foregroundStyle(secondary), lineLimit(1)]}
202 >
203 {detail === text.subscriptionRemaining ? " " : detail}
204 </Text>
205 ) : null}
206 {shown.map((window) => (
207 <VStack
208 key={window.label}
209 alignment="leading"
210 spacing={dense ? 1 : 2}
211 modifiers={[
212 accessibilityElement("ignore"),
213 accessibilityLabel(
214 text.windowAccessibility
215 .replace("{provider}", provider.name)
216 .replace("{window}", window.label)
217 .replace("{remaining}", String(window.remaining))
218 .replace("{reset}", window.reset)
219 .replace("{detail}", provider.detail),
220 ),
221 ]}
222 >
223 <HStack spacing={4}>
224 <Text
225 modifiers={[
226 font({ textStyle: compact || dense ? "caption2" : "caption" }),
227 foregroundStyle(secondary),
228 lineLimit(1),
229 ]}
230 >
231 {window.label}
232 </Text>
233 <Spacer />
234 <Text
235 modifiers={[
236 font({
237 textStyle: compact || dense ? "caption2" : "caption",
238 weight: "semibold",
239 }),
240 lineLimit(1),
241 layoutPriority(1),
242 foregroundStyle(
243 window.remaining <= 10 && !monochrome
244 ? (palette?.danger ??
245 (widgetEnvironment.colorScheme === "light" ? "#dc2626" : "#fca5a5"))
246 : primary,
247 ),
248 ]}
249 >
250 {text.percentLeft.replace("{remaining}", String(window.remaining))}
251 </Text>
252 </HStack>
253 <ProgressView value={window.remaining / 100} modifiers={barModifiers} />
254 {!compact ? (
255 <Text modifiers={[font({ size: 10 }), foregroundStyle(secondary), lineLimit(1)]}>
256 {window.reset}
257 </Text>
258 ) : null}
259 </VStack>
260 ))}
261 {!compact && !stale && hiddenCount > 0 ? (
262 <Text
263 modifiers={[font({ textStyle: "caption2" }), foregroundStyle(secondary), lineLimit(1)]}
264 >
265 {/* oxlint-disable-next-line t3code/no-untranslated-copy -- widget fallback until the app publishes translated text */}
266 {text.moreInApp[String(hiddenCount)] ?? `${hiddenCount} more in T3`}
267 </Text>
268 ) : null}
269 </VStack>
270 );
271 });
272 return (
273 <VStack
274 alignment="leading"
275 spacing={accessory || dense ? 2 : 6}
276 modifiers={[
277 ...(props.url ? [widgetURL(props.url)] : []),
278 ...(palette
279 ? [
280 containerBackground(palette.background, "widget"),
281 environment("colorScheme", appearance),
282 ]
283 : []),
284 ]}
285 >
286 {providers.length === 0 ? (
287 <Text modifiers={[font({ textStyle: "caption" }), foregroundStyle(secondary)]}>
288 {text.noLimits}
289 </Text>
290 ) : compact ? (
291 <VStack alignment="leading" spacing={accessory || dense ? 4 : 8}>
292 {columns}
293 </VStack>
294 ) : (
295 <HStack alignment="top" spacing={16}>
296 {columns}
297 </HStack>
298 )}
299 {!accessory ? <Spacer /> : null}
300 {!accessory ? (
301 <Text
302 modifiers={[font({ textStyle: "caption2" }), foregroundStyle(secondary), lineLimit(1)]}
303 >
304 {props.checkedAt
305 ? text.asOf.replace(
306 "{time}",
307 new Date(props.checkedAt).toLocaleString(undefined, {
308 hour: "numeric",
309 minute: "2-digit",
310 month: "short",
311 day: "numeric",
312 }),
313 )
314 : text.tapToConnect}
315 </Text>
316 ) : null}
317 </VStack>
318 );
319 }
320
321 export default createWidget("SubscriptionUsage", SubscriptionUsage);