Skip to content
TypeScript

fix(mobile): match subscription widgets to app theme (#15941)

Alex Southwellc80cf02fb781
diff --git a/apps/mobile/src/widgets/SubscriptionUsage.android.tsx b/apps/mobile/src/widgets/SubscriptionUsage.android.tsx
index b137b9eb9c4..c29132af0ca 100644
--- a/apps/mobile/src/widgets/SubscriptionUsage.android.tsx
+++ b/apps/mobile/src/widgets/SubscriptionUsage.android.tsx
@@ -21,9 +21,24 @@ export function SubscriptionUsage(props: SubscriptionUsageProps, environment: Wi
// The widget runtime evaluates this function without the app's module scope.
const now = Date.now();
const limit = 2;
- const colors = getMaterialColors({
- scheme: environment.colorScheme === "dark" ? "dark" : "light",
- });
+ const mode = props.theme?.mode;
+ const appearance =
+ mode === "light" || mode === "dark"
+ ? mode
+ : environment.colorScheme === "dark"
+ ? "dark"
+ : "light";
+ const palette = props.theme?.[appearance];
+ const colors = palette
+ ? {
+ surface: palette.background,
+ onSurface: palette.foreground,
+ onSurfaceVariant: palette.secondary,
+ surfaceVariant: palette.track,
+ primary: palette.accent,
+ error: palette.danger,
+ }
+ : getMaterialColors({ scheme: appearance });
const muted = colors.onSurfaceVariant;
const providers = props.providers ?? [
{ name: "Codex", detail: "Open T3 to connect", windows: [], expiresAt: 0, totalWindows: 0 },
diff --git a/apps/mobile/src/widgets/SubscriptionUsage.tsx b/apps/mobile/src/widgets/SubscriptionUsage.tsx
index 0096e951af7..31b3b4caae4 100644
--- a/apps/mobile/src/widgets/SubscriptionUsage.tsx
+++ b/apps/mobile/src/widgets/SubscriptionUsage.tsx
@@ -2,6 +2,8 @@ import { HStack, ProgressView, Spacer, Text, VStack } from "@expo/ui/swift-ui";
import {
accessibilityElement,
accessibilityLabel,
+ containerBackground,
+ environment,
fixedSize,
font,
foregroundStyle,
@@ -23,20 +25,36 @@ type UsageConfiguration = {
function SubscriptionUsage(
props: SubscriptionUsageProps,
- environment: WidgetEnvironment<UsageConfiguration>,
+ widgetEnvironment: WidgetEnvironment<UsageConfiguration> & {
+ showsContainerBackground?: boolean;
+ },
) {
"widget";
// The extension evaluates this function without the app's module scope.
- const family = environment.widgetFamily;
+ const family = widgetEnvironment.widgetFamily;
// Gallery snapshots can render an old timeline entry after it has expired.
- const now = Math.max(environment.date?.getTime() ?? 0, Date.now());
+ const now = Math.max(widgetEnvironment.date?.getTime() ?? 0, Date.now());
const accessory = family === "accessoryRectangular";
const compact =
- family === "systemSmall" || accessory || environment.levelOfDetail === "simplified";
+ family === "systemSmall" || accessory || widgetEnvironment.levelOfDetail === "simplified";
const dense = family === "systemSmall" || family === "systemMedium";
const limit = family === "systemExtraLarge" ? 6 : family === "systemLarge" ? 4 : 2;
const monochrome =
- environment.widgetRenderingMode !== "fullColor" || environment.isLuminanceReduced;
+ widgetEnvironment.widgetRenderingMode !== "fullColor" || widgetEnvironment.isLuminanceReduced;
+ const mode = props.theme?.mode;
+ const appearance =
+ mode === "light" || mode === "dark"
+ ? mode
+ : widgetEnvironment.colorScheme === "dark"
+ ? "dark"
+ : "light";
+ // StandBy can remove the card even in full color; text must then follow the host.
+ const palette =
+ !accessory && !monochrome && widgetEnvironment.showsContainerBackground !== false
+ ? props.theme?.[appearance]
+ : undefined;
+ const primary = palette?.foreground ?? "primary";
+ const secondary = palette?.secondary ?? "secondary";
const providers = props.providers ?? [
{ name: "Codex", detail: "Open T3 to connect", windows: [], expiresAt: 0 },
{ name: "Claude", detail: "Open T3 to connect", windows: [], expiresAt: 0 },
@@ -44,8 +62,9 @@ function SubscriptionUsage(
const columns = providers.map((provider) => {
const stale = provider.windows.length > 0 && now >= provider.expiresAt;
const period =
- environment.configuration?.[provider.name === "Claude" ? "claudePeriod" : "codexPeriod"] ??
- "auto";
+ widgetEnvironment.configuration?.[
+ provider.name === "Claude" ? "claudePeriod" : "codexPeriod"
+ ] ?? "auto";
const windows = stale
? []
: provider.windows.filter((window) => period === "auto" || window.kind === period);
@@ -58,7 +77,7 @@ function SubscriptionUsage(
windows.find((window) => window.kind === "weekly"),
].filter((window) => window !== undefined);
const shown =
- accessory || environment.levelOfDetail === "simplified"
+ accessory || widgetEnvironment.levelOfDetail === "simplified"
? tightest
? [tightest]
: []
@@ -100,7 +119,7 @@ function SubscriptionUsage(
modifiers={[
font({ textStyle: "caption", weight: "semibold" }),
lineLimit(1),
- foregroundStyle("primary"),
+ foregroundStyle(primary),
]}
>
{provider.name}
@@ -112,7 +131,7 @@ function SubscriptionUsage(
font({ textStyle: "caption", weight: "semibold" }),
lineLimit(1),
layoutPriority(1),
- foregroundStyle("primary"),
+ foregroundStyle(primary),
]}
>
{tightest
@@ -142,18 +161,14 @@ function SubscriptionUsage(
modifiers={[
font({ textStyle: compact ? "caption" : "headline", weight: "bold" }),
lineLimit(1),
- foregroundStyle("primary"),
+ foregroundStyle(primary),
]}
>
{provider.name}
</Text>
{!compact || shown.length === 0 ? (
<Text
- modifiers={[
- font({ textStyle: "caption2" }),
- foregroundStyle("secondary"),
- lineLimit(1),
- ]}
+ modifiers={[font({ textStyle: "caption2" }), foregroundStyle(secondary), lineLimit(1)]}
>
{detail === "Subscription remaining" ? " " : detail}
</Text>
@@ -174,7 +189,7 @@ function SubscriptionUsage(
<Text
modifiers={[
font({ textStyle: compact || dense ? "caption2" : "caption" }),
- foregroundStyle("secondary"),
+ foregroundStyle(secondary),
lineLimit(1),
]}
>
@@ -191,10 +206,9 @@ function SubscriptionUsage(
layoutPriority(1),
foregroundStyle(
window.remaining <= 10 && !monochrome
- ? environment.colorScheme === "light"
- ? "#dc2626"
- : "#fca5a5"
- : "primary",
+ ? (palette?.danger ??
+ (widgetEnvironment.colorScheme === "light" ? "#dc2626" : "#fca5a5"))
+ : primary,
),
]}
>
@@ -203,7 +217,7 @@ function SubscriptionUsage(
</HStack>
<ProgressView value={window.remaining / 100} modifiers={barModifiers} />
{!compact ? (
- <Text modifiers={[font({ size: 10 }), foregroundStyle("secondary"), lineLimit(1)]}>
+ <Text modifiers={[font({ size: 10 }), foregroundStyle(secondary), lineLimit(1)]}>
{window.reset}
</Text>
) : null}
@@ -213,11 +227,7 @@ function SubscriptionUsage(
!stale &&
(period === "auto" ? (provider.totalWindows ?? windows.length) : windows.length) > limit ? (
<Text
- modifiers={[
- font({ textStyle: "caption2" }),
- foregroundStyle("secondary"),
- lineLimit(1),
- ]}
+ modifiers={[font({ textStyle: "caption2" }), foregroundStyle(secondary), lineLimit(1)]}
>
{(period === "auto" ? (provider.totalWindows ?? windows.length) : windows.length) -
limit}{" "}
@@ -231,10 +241,18 @@ function SubscriptionUsage(
<VStack
alignment="leading"
spacing={accessory || dense ? 2 : 6}
- modifiers={props.url ? [widgetURL(props.url)] : []}
+ modifiers={[
+ ...(props.url ? [widgetURL(props.url)] : []),
+ ...(palette
+ ? [
+ containerBackground(palette.background, "widget"),
+ environment("colorScheme", appearance),
+ ]
+ : []),
+ ]}
>
{providers.length === 0 ? (
- <Text modifiers={[font({ textStyle: "caption" }), foregroundStyle("secondary")]}>
+ <Text modifiers={[font({ textStyle: "caption" }), foregroundStyle(secondary)]}>
No subscription limits available.
</Text>
) : compact ? (
@@ -249,7 +267,7 @@ function SubscriptionUsage(
{!accessory ? <Spacer /> : null}
{!accessory ? (
<Text
- modifiers={[font({ textStyle: "caption2" }), foregroundStyle("secondary"), lineLimit(1)]}
+ modifiers={[font({ textStyle: "caption2" }), foregroundStyle(secondary), lineLimit(1)]}
>
{props.checkedAt
? `As of ${new Date(props.checkedAt).toLocaleString(undefined, { hour: "numeric", minute: "2-digit", month: "short", day: "numeric" })}`
diff --git a/apps/mobile/src/widgets/SubscriptionUsageCoordinator.tsx b/apps/mobile/src/widgets/SubscriptionUsageCoordinator.tsx
index 7283b66f7c3..a51395e66f4 100644
--- a/apps/mobile/src/widgets/SubscriptionUsageCoordinator.tsx
+++ b/apps/mobile/src/widgets/SubscriptionUsageCoordinator.tsx
@@ -3,11 +3,13 @@ import { Atom } from "effect/reactivity";
import * as Linking from "expo-linking";
import { useEffect } from "react";
import { Platform } from "react-native";
+import { useAppearancePreferences } from "../features/settings/appearance/AppearancePreferencesProvider";
import { environmentCatalog } from "../connection/catalog";
import { environmentPresentations } from "../state/presentation";
import { publishSubscriptionUsage } from "./publishSubscriptionUsage";
import { useSubscriptionUsage } from "./useSubscriptionUsage";
import { buildSubscriptionUsageSnapshot } from "./subscriptionUsageSnapshot";
+import { createWidgetTheme } from "./widgetTheme";
// Isolate quota changes from the much busier thread/config presentation stream.
const snapshotAtom = Atom.make((get) =>
@@ -19,16 +21,36 @@ const snapshotAtom = Atom.make((get) =>
).pipe(Atom.withEquality((a, b) => JSON.stringify(a) === JSON.stringify(b)));
export function SubscriptionUsageCoordinator() {
+ const {
+ themeMode,
+ themeAppearance,
+ themeVariablesByAppearance,
+ isReady: appearanceReady,
+ } = useAppearancePreferences();
const catalog = useAtomValue(environmentCatalog.catalogValueAtom);
const snapshot = useAtomValue(snapshotAtom);
useSubscriptionUsage(catalog.isReady);
+ const androidAppearance = Platform.OS === "android" ? themeAppearance : null;
useEffect(() => {
- if (!catalog.isReady) return;
+ if (!catalog.isReady || !appearanceReady) return;
void Promise.resolve()
- .then(() => publishSubscriptionUsage(snapshot))
+ .then(() =>
+ publishSubscriptionUsage({
+ ...snapshot,
+ theme: createWidgetTheme(themeMode, themeVariablesByAppearance),
+ }),
+ )
.catch((error: unknown) => {
console.warn("Could not update subscription usage widget", error);
});
- }, [catalog.isReady, snapshot]);
+ }, [
+ catalog.isReady,
+ appearanceReady,
+ snapshot,
+ themeMode,
+ themeVariablesByAppearance,
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Android stores resolved colors; System appearance changes must republish them.
+ androidAppearance,
+ ]);
return null;
}
diff --git a/apps/mobile/src/widgets/subscriptionUsageSnapshot.test.ts b/apps/mobile/src/widgets/subscriptionUsageSnapshot.test.ts
index 8ab3d6191ef..fbd5938d36a 100644
--- a/apps/mobile/src/widgets/subscriptionUsageSnapshot.test.ts
+++ b/apps/mobile/src/widgets/subscriptionUsageSnapshot.test.ts
@@ -6,13 +6,30 @@ import {
type ServerProvider,
} from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
+import { getMobileThemeRuntimeVariables } from "../lib/mobileThemeVariables";
+import { createWidgetTheme } from "./widgetTheme";
import {
+ type SubscriptionUsageSnapshot,
buildSubscriptionUsageSnapshot,
createWidgetRefresher,
WIDGET_REFRESH_INTERVAL,
subscriptionUsageTimeline,
} from "./subscriptionUsageSnapshot";
+function contrastRatio(first: string, second: string) {
+ const luminance = (color: string) => {
+ if (!/^#[0-9a-f]{6}(?:ff)?$/i.test(color)) throw new Error(`Expected opaque hex: ${color}`);
+ const linear = [1, 3, 5].map((offset) => {
+ const channel = Number.parseInt(color.slice(offset, offset + 2), 16) / 255;
+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
+ });
+ return 0.2126 * linear[0]! + 0.7152 * linear[1]! + 0.0722 * linear[2]!;
+ };
+ const a = luminance(first);
+ const b = luminance(second);
+ return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
+}
+
const checkedAt = "2026-09-05T12:00:00.000Z";
const now = Date.parse(checkedAt);
const window = {
@@ -221,12 +238,40 @@ describe("subscription widget snapshots", () => {
expect(snapshot.providers[0]?.expiresAt).toBe(now + 15 * 60_000);
expect(snapshot.providers[0]?.windows[0]?.reset).toBe("Reset time unavailable");
});
- it("schedules a reset boundary without inventing a zero quota", () => {
- const snapshot = buildSubscriptionUsageSnapshot(presentations(), deepLink);
+ it("preserves the saved appearance through a reset without inventing a zero quota", () => {
+ const light = getMobileThemeRuntimeVariables("t3-chat", "light", "ios");
+ const dark = getMobileThemeRuntimeVariables("t3-code", "dark", "ios");
+ const snapshot: SubscriptionUsageSnapshot = JSON.parse(
+ JSON.stringify({
+ ...buildSubscriptionUsageSnapshot(presentations(), deepLink),
+ theme: createWidgetTheme("dark", { light, dark }),
+ }),
+ );
const timeline = subscriptionUsageTimeline(snapshot, now);
expect(timeline.map((entry) => entry.date.getTime())).toEqual([now, now + 10 * 60_000]);
expect(timeline[1]?.props.providers[0]?.windows).toEqual([]);
expect(subscriptionUsageTimeline(snapshot, now + 60 * 60_000)).toHaveLength(1);
+ for (const entry of timeline) {
+ expect(JSON.parse(JSON.stringify(entry.props)).theme).toEqual({
+ mode: "dark",
+ light: expect.objectContaining({
+ background: light["--color-card"],
+ foreground: light["--color-foreground"],
+ }),
+ dark: expect.objectContaining({
+ background: dark["--color-card"],
+ foreground: dark["--color-foreground"],
+ }),
+ });
+ }
+ });
+ it("keeps the default Android unfilled track distinguishable from the card", () => {
+ const theme = createWidgetTheme("system", {
+ light: getMobileThemeRuntimeVariables("t3-code", "light", "android"),
+ dark: getMobileThemeRuntimeVariables("t3-code", "dark", "android"),
+ });
+ expect(contrastRatio(theme.dark.track, theme.dark.background)).toBeGreaterThanOrEqual(1.3);
+ expect(contrastRatio(theme.light.track, theme.light.background)).toBeGreaterThanOrEqual(1.3);
});
it("expires providers independently without inventing a refill", () => {
const snapshot = buildSubscriptionUsageSnapshot(
diff --git a/apps/mobile/src/widgets/subscriptionUsageSnapshot.ts b/apps/mobile/src/widgets/subscriptionUsageSnapshot.ts
index 9bf593fc21d..d3aa5797402 100644
--- a/apps/mobile/src/widgets/subscriptionUsageSnapshot.ts
+++ b/apps/mobile/src/widgets/subscriptionUsageSnapshot.ts
@@ -5,7 +5,10 @@ import {
type LimitPresentations,
} from "@t3tools/shared/usageLimits";
+import type { WidgetTheme } from "./widgetTheme";
+
export interface SubscriptionUsageSnapshot {
+ theme?: WidgetTheme;
url?: string;
checkedAt: number;
providers: Array<{
diff --git a/apps/mobile/src/widgets/widgetTheme.ts b/apps/mobile/src/widgets/widgetTheme.ts
new file mode 100644
index 00000000000..e240dbc5445
--- /dev/null
+++ b/apps/mobile/src/widgets/widgetTheme.ts
@@ -0,0 +1,40 @@
+import {
+ flattenThemeColor,
+ themeColorWithAlpha,
+ type MobileThemeMode,
+ type MobileThemeVariables,
+} from "../lib/mobileTheme";
+
+export interface WidgetPalette {
+ background: string;
+ foreground: string;
+ secondary: string;
+ accent: string;
+ track: string;
+ danger: string;
+}
+
+export interface WidgetTheme {
+ mode: MobileThemeMode;
+ light: WidgetPalette;
+ dark: WidgetPalette;
+}
+
+export function createWidgetTheme(
+ mode: MobileThemeMode,
+ palettes: Readonly<Record<"light" | "dark", MobileThemeVariables>>,
+): WidgetTheme {
+ const palette = (variables: MobileThemeVariables) => ({
+ background: variables["--color-card"],
+ foreground: variables["--color-foreground"],
+ secondary: variables["--color-foreground-secondary"],
+ accent: variables["--color-primary"],
+ // Surface tokens can coincide; a foreground blend keeps the unfilled track visible.
+ track: flattenThemeColor(
+ themeColorWithAlpha(variables["--color-foreground"], 0.16),
+ variables["--color-card"],
+ ),
+ danger: variables["--color-danger-foreground"],
+ });
+ return { mode, light: palette(palettes.light), dark: palette(palettes.dark) };
+}