From 41c0637652082ee93ecd199b64bcaf691f361cad Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:45:36 +0000 Subject: [PATCH 01/18] fix(layouts): type contentContainerStyle from the Tamagui View The props used React Native's ViewProps style, which stops type-checking against @tamagui/tailwind's View once expo/types (web CSS) is loaded by expo-env.d.ts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- src/components/layouts/types.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/components/layouts/types.ts b/src/components/layouts/types.ts index 68b4e5b..0e43e9f 100644 --- a/src/components/layouts/types.ts +++ b/src/components/layouts/types.ts @@ -1,9 +1,12 @@ -import type { ReactNode } from "react"; -import type { ViewProps } from "react-native"; +import type { View } from "@tamagui/tailwind"; +import type { ComponentProps, ReactNode } from "react"; + +/** Style accepted by the `@tamagui/tailwind` `View` that hosts layout content. */ +type ContentStyle = ComponentProps["style"]; export interface BareLayoutProps { children?: ReactNode; - contentContainerStyle?: ViewProps["style"]; + contentContainerStyle?: ContentStyle; safeAreaEdges?: ("top" | "bottom" | "left" | "right")[]; } @@ -14,7 +17,7 @@ export interface BaseLayoutProps { safeAreaEdges?: ("top" | "bottom" | "left" | "right")[]; onBack?: () => void; callToAction?: ReactNode; - contentContainerStyle?: ViewProps["style"]; + contentContainerStyle?: ContentStyle; } export interface ModalLayoutProps { From cf8e4cac2ca8e68fe6105f6a08fa07c7755dd51a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:45:38 +0000 Subject: [PATCH 02/18] feat(router): enable typed routes and generate them before typecheck typegen runs expo customize tsconfig.json, which writes .expo/types without starting Metro, so CI and the pre-commit hook check hrefs too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- app.json | 3 ++- package.json | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/app.json b/app.json index 3491950..764a694 100644 --- a/app.json +++ b/app.json @@ -7,7 +7,8 @@ "scheme": "mytemplateproject", "userInterfaceStyle": "automatic", "experiments": { - "reactCompiler": true + "reactCompiler": true, + "typedRoutes": true }, "assetBundlePatterns": ["**/*"], "ios": { diff --git a/package.json b/package.json index 6b35426..71f981c 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,8 @@ "codegen": "bun ./scripts/codegen.mjs", "lint": "oxlint .", "format": "bun fmt", - "typecheck": "bun check", + "typegen": "expo customize tsconfig.json", + "typecheck": "bun run typegen && bun check", "verify:locales": "bun ./scripts/verify-locales.mjs", "prebuild": "bunx expo prebuild --clean", "prebuild:dev": "APP_VARIANT=development bunx expo prebuild --clean", From 56862441a879444aeb4c234d1c63452136d018e7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:46:41 +0000 Subject: [PATCH 03/18] chore(lint): forbid any and enable suspicious and perf rules Turns on oxlint's suspicious and perf categories and makes no-explicit-any an error, matching AGENTS.md. Rules that only flag the new JSX transform, StatusBar's string style or WatermelonDB's _getRaw are off; tabBarIcon render props are allowed. Fixes what the new rules found: styledNative no longer takes any, layouts share a stable default safe-area edge list, the locale script uses toSorted, and system theme tracking is one effect driven by useColorScheme instead of a duplicate Appearance listener. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- .oxlintrc.json | 28 ++++++++++++++++++++++---- scripts/verify-locales.mjs | 10 ++++----- src/components/common/styled-native.ts | 6 +++--- src/components/layouts/Bare.tsx | 4 ++-- src/components/layouts/Base.tsx | 4 ++-- src/components/layouts/safe-screen.tsx | 5 +++++ src/components/layouts/types.ts | 6 ++++-- src/theme/stores/useThemeStore.ts | 23 ++++++++------------- 8 files changed, 53 insertions(+), 33 deletions(-) diff --git a/.oxlintrc.json b/.oxlintrc.json index 69b90b8..19e1634 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -1,13 +1,33 @@ { "$schema": "./node_modules/oxlint/configuration_schema.json", - "plugins": ["typescript", "unicorn", "oxc", "react", "react-hooks"], + "plugins": [ + "typescript", + "unicorn", + "oxc", + "react", + "react-hooks" + ], "categories": { - "correctness": "error" + "correctness": "error", + "suspicious": "error", + "perf": "error" }, "rules": { - "no-explicit-any": "off" + "typescript/no-explicit-any": "error", + "react/react-in-jsx-scope": "off", + "react/style-prop-object": "off", + "react/no-unstable-nested-components": [ + "error", + { + "allowAsProps": true + } + ], + "no-underscore-dangle": "off" }, - "ignorePatterns": [".agents/**"], + "ignorePatterns": [ + ".agents/**", + ".expo/**" + ], "env": { "builtin": true } diff --git a/scripts/verify-locales.mjs b/scripts/verify-locales.mjs index 6103cfb..32b879f 100644 --- a/scripts/verify-locales.mjs +++ b/scripts/verify-locales.mjs @@ -44,7 +44,7 @@ const namespacesDir = path.join(import.meta.dirname, "../src/i18n/locales"); const languages = fs .readdirSync(namespacesDir) .filter((f) => fs.statSync(path.join(namespacesDir, f)).isDirectory()) - .sort(); + .toSorted(); if (languages.length === 0) { process.stderr.write("❌ No language directories found\n"); @@ -62,7 +62,7 @@ const namespaces = fs .readdirSync(referenceLangDir) .filter((f) => f.endsWith(".json")) .map((f) => path.basename(f, ".json")) - .sort(); + .toSorted(); if (namespaces.length === 0) { process.stderr.write(`❌ No namespace files found in ${referenceLanguage}\n`); @@ -78,7 +78,7 @@ for (const lang of languages) { .readdirSync(langDir) .filter((f) => f.endsWith(".json")) .map((f) => path.basename(f, ".json")) - .sort(); + .toSorted(); const missingNamespaces = namespaces.filter((ns) => !langNamespaces.includes(ns)); const extraNamespaces = langNamespaces.filter((ns) => !namespaces.includes(ns)); @@ -139,7 +139,7 @@ for (const namespace of namespaces) { hasErrors = true; const noun = missingKeys.length === 1 ? "key" : "keys"; process.stderr.write(`❌ ${namespace}.json (${lang}): Missing ${missingKeys.length} ${noun}\n`); - missingKeys.sort(); + missingKeys.toSorted(); const displayCount = isVerbose ? missingKeys.length : 5; for (const key of missingKeys.slice(0, displayCount)) { process.stderr.write(` ${key}\n`); @@ -159,7 +159,7 @@ for (const namespace of namespaces) { hasErrors = true; const noun = extraKeys.length === 1 ? "key" : "keys"; process.stderr.write(`❌ ${namespace}.json (${lang}): Extra ${extraKeys.length} ${noun}\n`); - extraKeys.sort(); + extraKeys.toSorted(); const displayCount = isVerbose ? extraKeys.length : 5; for (const key of extraKeys.slice(0, displayCount)) { process.stderr.write(` ${key}\n`); diff --git a/src/components/common/styled-native.ts b/src/components/common/styled-native.ts index 53ef7a5..9b199cd 100644 --- a/src/components/common/styled-native.ts +++ b/src/components/common/styled-native.ts @@ -1,11 +1,11 @@ import { styled, type TailwindComponent } from "@tamagui/tailwind"; -import type { ComponentProps, ComponentType } from "react"; +import type { ComponentType } from "react"; /** * `styled()` from `@tamagui/tailwind` for a third-party React Native component. * Its typings only accept Tamagui components, but at runtime Tamagui wraps any * component and resolves the class string into the `style` it receives. */ -export function styledNative>(component: Component, className: string) { - return styled(component as unknown as TailwindComponent>, className); +export function styledNative(component: ComponentType, className: string) { + return styled(component as unknown as TailwindComponent, className); } diff --git a/src/components/layouts/Bare.tsx b/src/components/layouts/Bare.tsx index b316dad..4e188b7 100644 --- a/src/components/layouts/Bare.tsx +++ b/src/components/layouts/Bare.tsx @@ -1,10 +1,10 @@ import { View } from "@tamagui/tailwind"; import type { FC } from "react"; -import { SafeScreen } from "./safe-screen"; +import { DEFAULT_SAFE_AREA_EDGES, SafeScreen } from "./safe-screen"; import type { BareLayoutProps } from "./types"; -export const BareLayout: FC = ({ children, contentContainerStyle, safeAreaEdges = ["top"] }) => { +export const BareLayout: FC = ({ children, contentContainerStyle, safeAreaEdges = DEFAULT_SAFE_AREA_EDGES }) => { return ( diff --git a/src/components/layouts/Base.tsx b/src/components/layouts/Base.tsx index b20b0d7..dc0a68c 100644 --- a/src/components/layouts/Base.tsx +++ b/src/components/layouts/Base.tsx @@ -7,7 +7,7 @@ import { useTranslation } from "react-i18next"; import { Icon } from "@/components/common/icon"; import { IconButton } from "@/components/common/icon-button"; import { useTheme } from "@/theme/hooks/useTheme"; -import { SafeScreen } from "./safe-screen"; +import { DEFAULT_SAFE_AREA_EDGES, SafeScreen } from "./safe-screen"; import type { BaseLayoutProps } from "./types"; export const BaseLayout: FC = ({ @@ -16,7 +16,7 @@ export const BaseLayout: FC = ({ onBack, children, contentContainerStyle, - safeAreaEdges = ["top"], + safeAreaEdges = DEFAULT_SAFE_AREA_EDGES, callToAction, }) => { const router = useRouter(); diff --git a/src/components/layouts/safe-screen.tsx b/src/components/layouts/safe-screen.tsx index 2c7d51c..0bfc860 100644 --- a/src/components/layouts/safe-screen.tsx +++ b/src/components/layouts/safe-screen.tsx @@ -3,3 +3,8 @@ import { SafeAreaView } from "react-native-safe-area-context"; import { styledNative } from "@/components/common/styled-native"; export const SafeScreen = styledNative(SafeAreaView, "flex-1 bg-background-primary"); + +export type SafeAreaEdge = "top" | "bottom" | "left" | "right"; + +/** Stable default so layouts don't pass a new array to SafeAreaView each render. */ +export const DEFAULT_SAFE_AREA_EDGES: readonly SafeAreaEdge[] = ["top"]; diff --git a/src/components/layouts/types.ts b/src/components/layouts/types.ts index 0e43e9f..82567ab 100644 --- a/src/components/layouts/types.ts +++ b/src/components/layouts/types.ts @@ -1,20 +1,22 @@ import type { View } from "@tamagui/tailwind"; import type { ComponentProps, ReactNode } from "react"; +import type { SafeAreaEdge } from "./safe-screen"; + /** Style accepted by the `@tamagui/tailwind` `View` that hosts layout content. */ type ContentStyle = ComponentProps["style"]; export interface BareLayoutProps { children?: ReactNode; contentContainerStyle?: ContentStyle; - safeAreaEdges?: ("top" | "bottom" | "left" | "right")[]; + safeAreaEdges?: readonly SafeAreaEdge[]; } export interface BaseLayoutProps { children: ReactNode; title?: string; showBack?: boolean; - safeAreaEdges?: ("top" | "bottom" | "left" | "right")[]; + safeAreaEdges?: readonly SafeAreaEdge[]; onBack?: () => void; callToAction?: ReactNode; contentContainerStyle?: ContentStyle; diff --git a/src/theme/stores/useThemeStore.ts b/src/theme/stores/useThemeStore.ts index aa0ae28..5023418 100644 --- a/src/theme/stores/useThemeStore.ts +++ b/src/theme/stores/useThemeStore.ts @@ -134,22 +134,15 @@ export function useSystemThemeTracking() { const systemColorScheme = useColorScheme(); const followSystemTheme = useSelector(() => themePrefs$.followSystemTheme.get()); + // useColorScheme re-renders on system changes, so one effect covers both + // the initial sync and later Appearance updates. React.useEffect(() => { - if (followSystemTheme) { - themeActions.updateTheme(); + if (!followSystemTheme || !systemColorScheme) { + return; + } + const systemMode: ThemeMode = systemColorScheme === "dark" ? "dark" : "light"; + if (systemMode !== themePrefs$.mode.get()) { + applyMode(systemMode); } }, [followSystemTheme, systemColorScheme]); - - React.useEffect(() => { - const subscription = Appearance.addChangeListener(({ colorScheme }) => { - if (followSystemTheme && colorScheme) { - const systemMode = colorScheme === "dark" ? "dark" : "light"; - if (systemMode !== themePrefs$.mode.get()) { - applyMode(systemMode); - } - } - }); - - return () => subscription.remove(); - }, [followSystemTheme]); } From eba007988d8027a9aee96e7c6c1b6a41bb6c0460 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:46:43 +0000 Subject: [PATCH 04/18] chore(ts): enable noUncheckedIndexedAccess and drop redundant flags strict already sets the flags that were listed one by one. Adds noUncheckedIndexedAccess, noFallthroughCasesInSwitch and noImplicitOverride, and fixes the index reads and overrides they flag. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- src/components/common/error-boundary.tsx | 4 ++-- src/data/define-columns.ts | 3 +-- src/data/models/note.ts | 2 +- src/i18n/index.ts | 2 +- src/theme/hooks/useResponsiveTypography.ts | 2 +- src/utils/date.ts | 2 +- tsconfig.json | 13 ++++--------- 7 files changed, 11 insertions(+), 17 deletions(-) diff --git a/src/components/common/error-boundary.tsx b/src/components/common/error-boundary.tsx index 82e4c36..97be0a2 100644 --- a/src/components/common/error-boundary.tsx +++ b/src/components/common/error-boundary.tsx @@ -77,7 +77,7 @@ export class ErrorBoundary extends Component[1]; */ export function defineColumns(spec: Record): PropertyDescriptorMap { const descriptors: PropertyDescriptorMap = {}; - for (const property of Object.keys(spec)) { - const column = spec[property]; + for (const [property, column] of Object.entries(spec)) { descriptors[property] = { configurable: true, enumerable: true, diff --git a/src/data/models/note.ts b/src/data/models/note.ts index 19aaa72..bc4c430 100644 --- a/src/data/models/note.ts +++ b/src/data/models/note.ts @@ -3,7 +3,7 @@ import { Model } from "react-native-watermelondb"; import { defineColumns } from "../define-columns"; export class Note extends Model { - static table = "notes"; + static override table = "notes"; title!: string; /** Epoch ms; WatermelonDB fills `created_at` / `updated_at` automatically. */ diff --git a/src/i18n/index.ts b/src/i18n/index.ts index 4238b32..e1d0548 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -17,7 +17,7 @@ const extractLanguageCode = (locale: string | undefined): string => { if (!locale || typeof locale !== "string") { return FALLBACK_LANGUAGE; } - const languageCode = locale.split("_")[0].split("-")[0].toLowerCase(); + const languageCode = locale.split(/[-_]/)[0]?.toLowerCase() ?? FALLBACK_LANGUAGE; return SUPPORTED_LANGUAGES.includes(languageCode as Languages) ? languageCode : FALLBACK_LANGUAGE; }; diff --git a/src/theme/hooks/useResponsiveTypography.ts b/src/theme/hooks/useResponsiveTypography.ts index f714657..e039651 100644 --- a/src/theme/hooks/useResponsiveTypography.ts +++ b/src/theme/hooks/useResponsiveTypography.ts @@ -38,7 +38,7 @@ const shiftFontSize = (size: FontSize, shift: number): FontSize => { } const nextIndex = Math.min(Math.max(currentIndex + shift, 0), FONT_SIZE_ORDER.length - 1); - return FONT_SIZE_ORDER[nextIndex]; + return FONT_SIZE_ORDER[nextIndex] ?? size; }; const applyTextSizePreference = (size: FontSize, preference: TextSizePreference): FontSize => { diff --git a/src/utils/date.ts b/src/utils/date.ts index 0dee544..53a4d7d 100644 --- a/src/utils/date.ts +++ b/src/utils/date.ts @@ -48,7 +48,7 @@ const getUserDateFormat = (): string => { const getUserDateFnsFormat = (userFormat?: string): string => { const userFormatString = userFormat || getUserDateFormat(); - return USER_FORMATS[userFormatString] || USER_FORMATS["DD/MM/YYYY"]; + return USER_FORMATS[userFormatString] ?? "DD/MM/YYYY"; }; // Core formatting function diff --git a/tsconfig.json b/tsconfig.json index 4cb4831..e910191 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,18 +2,13 @@ "extends": "expo/tsconfig.base", "compilerOptions": { "strict": true, + "noUncheckedIndexedAccess": true, + "noFallthroughCasesInSwitch": true, + "noImplicitOverride": true, "types": ["node"], "paths": { "@/*": ["./src/*"] - }, - "strictNullChecks": true, - "noImplicitAny": true, - "strictFunctionTypes": true, - "strictBindCallApply": true, - "strictPropertyInitialization": true, - "noImplicitThis": true, - "useUnknownInCatchVariables": true, - "alwaysStrict": true + } }, "include": ["**/*.ts", "**/*.tsx", "**/*.d.ts", ".expo/types/**/*.ts", "expo-env.d.ts"] } From 87da48c89fe0c552d097fd1e351a0c9b90e7cb0e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:46:51 +0000 Subject: [PATCH 05/18] fix(error-boundary): use the shared gesture-handler Pressable Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- src/components/common/error-boundary.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/components/common/error-boundary.tsx b/src/components/common/error-boundary.tsx index 97be0a2..5576230 100644 --- a/src/components/common/error-boundary.tsx +++ b/src/components/common/error-boundary.tsx @@ -1,10 +1,11 @@ import { router } from "expo-router"; import { Component, type ErrorInfo, type FC, type ReactNode } from "react"; import { useTranslation } from "react-i18next"; -import { Pressable, ScrollView } from "react-native"; +import { ScrollView } from "react-native"; import { Text, View } from "@tamagui/tailwind"; import { getTokenValue } from "tamagui"; +import { Pressable } from "@/components/common/pressable"; import { logger } from "@/utils/logger"; import { captureException } from "@/utils/sentry"; From 11975525a19ef1dee35be2afb4143c6264f6d615 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:47:16 +0000 Subject: [PATCH 06/18] feat(i18n): type translation keys from the English locale Augments i18next's CustomTypeOptions with the en resources, so t() keys and namespaces are checked at compile time. Date utilities take keys of the date namespace instead of any string. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- src/i18n/i18next.d.ts | 10 ++++++++++ src/types/date.ts | 7 ++++++- src/utils/date.ts | 4 ++-- 3 files changed, 18 insertions(+), 3 deletions(-) create mode 100644 src/i18n/i18next.d.ts diff --git a/src/i18n/i18next.d.ts b/src/i18n/i18next.d.ts new file mode 100644 index 0000000..f6dc59f --- /dev/null +++ b/src/i18n/i18next.d.ts @@ -0,0 +1,10 @@ +import type { resources } from "./index"; + +// Types `t()` keys and namespaces from the English JSON, so a typo or a key +// missing from `locales/en` is a compile error. +declare module "i18next" { + interface CustomTypeOptions { + defaultNS: "common"; + resources: (typeof resources)["en"]; + } +} diff --git a/src/types/date.ts b/src/types/date.ts index 28503f3..c6a91ee 100644 --- a/src/types/date.ts +++ b/src/types/date.ts @@ -1,5 +1,7 @@ import type { Dayjs } from "dayjs"; +import type { resources } from "@/i18n"; + export type ValidDateFormat = "DD/MM/YYYY" | "MM/DD/YYYY" | "YYYY/MM/DD"; // Date input types that our utilities can accept @@ -8,8 +10,11 @@ export type DateInput = Date | number | string | Dayjs; // Locale codes supported by the application export type SupportedLocale = "en"; +// Keys of the `date` namespace, prefixed the way date utilities pass them to `t()` +export type DateTranslationKey = `date:${keyof (typeof resources)["en"]["date"]}`; + // Translation function type for date utilities -export type TranslationFunction = (key: string) => string; +export type TranslationFunction = (key: DateTranslationKey) => string; // Date formatter function type export type DateFormatterFunction = (date: DateInput, lang?: string) => string; diff --git a/src/utils/date.ts b/src/utils/date.ts index 53a4d7d..299ea77 100644 --- a/src/utils/date.ts +++ b/src/utils/date.ts @@ -98,7 +98,7 @@ export const formatRelativeDate = (timestamp: DateInput, t?: TranslationFunction const now = dayjs(); const diffInDays = now.diff(date, "day"); - const translate = t || getI18nInstance().t.bind(getI18nInstance()); + const translate: TranslationFunction = t ?? ((key) => getI18nInstance().t(key)); if (diffInDays === 0) { return formatDate(date, DateFormats.TIME, lang); @@ -152,7 +152,7 @@ export const formatDateRange = ( const startFormatted = formatDate(start, DateFormats.MEDIUM, lang); const endFormatted = formatDate(end, DateFormats.MEDIUM, lang); - const translate = t || getI18nInstance().t.bind(getI18nInstance()); + const translate: TranslationFunction = t ?? ((key) => getI18nInstance().t(key)); const separator = translate("date:range_separator") || " - "; return `${startFormatted}${separator}${endFormatted}`; From 9a83a68ea100ac242a4fb37174b0b9da72484c96 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:47:38 +0000 Subject: [PATCH 07/18] feat(env): read runtime config through a typed env module RevenueCat and Sentry read their keys from src/utils/env.ts, which also exposes the build variant and app version. .env.example documents SENTRY_AUTH_TOKEN for source map uploads. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- .env.example | 8 +++++++- src/utils/env.ts | 27 +++++++++++++++++++++++++++ src/utils/revenuecat.ts | 10 +++------- src/utils/sentry.ts | 3 ++- 4 files changed, 39 insertions(+), 9 deletions(-) create mode 100644 src/utils/env.ts diff --git a/.env.example b/.env.example index 25e5069..dc18694 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,10 @@ -#DO NOT COMMIT THIS +# Copy to .env and fill in. Never commit .env. + +# Read by the app at runtime (inlined at build time); see src/utils/env.ts. EXPO_PUBLIC_REVENUECAT_IOS_API_KEY= EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY= EXPO_PUBLIC_SENTRY_DSN= + +# Build-time only: lets the Sentry Expo plugin upload source maps during +# EAS / release builds. Store it as an EAS secret for cloud builds. +SENTRY_AUTH_TOKEN= diff --git a/src/utils/env.ts b/src/utils/env.ts new file mode 100644 index 0000000..a0f264e --- /dev/null +++ b/src/utils/env.ts @@ -0,0 +1,27 @@ +import Constants from "expo-constants"; + +/** + * Runtime configuration, read in one place. + * + * Expo inlines `EXPO_PUBLIC_*` variables at build time only for literal + * `process.env.EXPO_PUBLIC_NAME` reads, so keep each one spelled out here. + * Values are trimmed; a missing value is an empty string and the consumer + * decides whether to skip its setup. + */ + +export type AppVariant = "development" | "preview" | "production"; + +const read = (value: string | undefined): string => value?.trim() ?? ""; + +const resolveVariant = (value: unknown): AppVariant => + value === "production" || value === "preview" ? value : "development"; + +export const env = { + /** Build variant from `app.config.ts` (`APP_VARIANT`). */ + appVariant: resolveVariant(Constants.expoConfig?.extra?.variant), + /** App version from `app.json`, used for Sentry releases. */ + appVersion: Constants.expoConfig?.version ?? "0.0.0", + revenueCatIosApiKey: read(process.env.EXPO_PUBLIC_REVENUECAT_IOS_API_KEY), + revenueCatAndroidApiKey: read(process.env.EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY), + sentryDsn: read(process.env.EXPO_PUBLIC_SENTRY_DSN), +} as const; diff --git a/src/utils/revenuecat.ts b/src/utils/revenuecat.ts index 6ab7a65..fe84b3d 100644 --- a/src/utils/revenuecat.ts +++ b/src/utils/revenuecat.ts @@ -5,6 +5,7 @@ import RevenueCatUI, { PAYWALL_RESULT } from "react-native-purchases-ui"; import { useSettingsStore } from "@/stores/settings"; +import { env } from "./env"; import { logger } from "./logger"; export const PREMIUM_ENTITLEMENT_ID = "premium"; @@ -20,13 +21,8 @@ type PurchaseActionResult = PurchaseActionSuccess | PurchaseActionFailure; let isConfigured = false; -const getPlatformApiKey = () => { - if (Platform.OS === "android") { - return process.env.EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY?.trim() ?? ""; - } - - return process.env.EXPO_PUBLIC_REVENUECAT_IOS_API_KEY?.trim() ?? ""; -}; +const getPlatformApiKey = () => + Platform.OS === "android" ? env.revenueCatAndroidApiKey : env.revenueCatIosApiKey; const getErrorMessage = (error: unknown, fallback: string) => { const errorObj = error as { message?: string }; diff --git a/src/utils/sentry.ts b/src/utils/sentry.ts index 69afd36..85b4146 100644 --- a/src/utils/sentry.ts +++ b/src/utils/sentry.ts @@ -1,8 +1,9 @@ import { captureException as sentryCaptureException, init } from "@sentry/react-native"; +import { env } from "./env"; import { logger } from "./logger"; -const sentryDsn = process.env.EXPO_PUBLIC_SENTRY_DSN?.trim() ?? ""; +const sentryDsn = env.sentryDsn; let initialized = false; From 04cded58dc2112af41fda46dbec8df083e75c843 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:47:47 +0000 Subject: [PATCH 08/18] perf(startup): stop holding the splash screen for RevenueCat initializeRevenueCat waits for a customer-info request, which kept the splash up on slow networks. It now runs in the background and the customer-info listener sets premium when the answer arrives; only i18n gates the first render. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- app/_layout.tsx | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/app/_layout.tsx b/app/_layout.tsx index f1e168d..2076a95 100644 --- a/app/_layout.tsx +++ b/app/_layout.tsx @@ -77,9 +77,16 @@ function RootLayout() { } didInitRef.current = true; + // RevenueCat fetches customer info over the network, so it runs in the + // background; its listener updates `premium` when the answer arrives. + initializeRevenueCat().catch((error: unknown) => { + logger.error("RevenueCat initialization failed:", error); + captureException(error); + }); + (async () => { try { - const [language] = await Promise.all([initializeI18n(), initializeRevenueCat()]); + const language = await initializeI18n(); settings$.language.set(language); } catch (error) { logger.error("Root initialization failed:", error); From be50ad65a523c5ae83cea3c8588024ebcb81b0d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:47:58 +0000 Subject: [PATCH 09/18] fix(revenuecat): give the limit paywall its own placement Both placements pointed at "settings", so the limit paywall could never show a different offering. Also reads error messages without a cast. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- src/utils/revenuecat.ts | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/utils/revenuecat.ts b/src/utils/revenuecat.ts index fe84b3d..96b6d46 100644 --- a/src/utils/revenuecat.ts +++ b/src/utils/revenuecat.ts @@ -9,8 +9,15 @@ import { env } from "./env"; import { logger } from "./logger"; export const PREMIUM_ENTITLEMENT_ID = "premium"; +/** + * Placement identifiers. Each must match a placement in the RevenueCat + * dashboard so it can show its own offering; an unknown placement falls back + * to the offering with that id, then the current offering. + */ export const PAYWALL_PLACEMENTS = { - limit: "settings", + /** Shown when a free user hits a feature limit. */ + limit: "feature_limit", + /** Shown from the settings screen's upgrade row. */ subscription: "settings", } as const; export const ONBOARDING_PLACEMENT = "onboarding_v1"; @@ -24,10 +31,8 @@ let isConfigured = false; const getPlatformApiKey = () => Platform.OS === "android" ? env.revenueCatAndroidApiKey : env.revenueCatIosApiKey; -const getErrorMessage = (error: unknown, fallback: string) => { - const errorObj = error as { message?: string }; - return errorObj.message || fallback; -}; +const getErrorMessage = (error: unknown, fallback: string) => + error instanceof Error && error.message ? error.message : fallback; const syncPremium = (customerInfo: CustomerInfo) => { const hasPremiumAccess = Boolean(customerInfo.entitlements.active[PREMIUM_ENTITLEMENT_ID]); From 88c5582efddf1b0d337219a176dc50c05aeb7a06 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:48:08 +0000 Subject: [PATCH 10/18] fix(revenuecat): read messages from plain PurchasesError objects Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- src/utils/revenuecat.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/utils/revenuecat.ts b/src/utils/revenuecat.ts index 96b6d46..f222e02 100644 --- a/src/utils/revenuecat.ts +++ b/src/utils/revenuecat.ts @@ -31,8 +31,11 @@ let isConfigured = false; const getPlatformApiKey = () => Platform.OS === "android" ? env.revenueCatAndroidApiKey : env.revenueCatIosApiKey; +// RevenueCat rejects with plain PurchasesError objects, not Error instances. const getErrorMessage = (error: unknown, fallback: string) => - error instanceof Error && error.message ? error.message : fallback; + typeof error === "object" && error !== null && "message" in error && typeof error.message === "string" && error.message + ? error.message + : fallback; const syncPremium = (customerInfo: CustomerInfo) => { const hasPremiumAccess = Boolean(customerInfo.entitlements.active[PREMIUM_ENTITLEMENT_ID]); From 677d2f3993c2181d5709029688dcb00ed5f7e5ec Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:48:22 +0000 Subject: [PATCH 11/18] refactor(storage): export the MMKV instance instead of a wrapper The wrapper duplicated MMKV's API under two names each (getItem and getString, remove and removeItem) and swallowed every error. Callers now use MMKV directly; the JSON helpers take a StorageKey and log unparsable values. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- src/i18n/index.ts | 2 +- src/utils/storage.ts | 134 +++++++------------------------------------ 2 files changed, 23 insertions(+), 113 deletions(-) diff --git a/src/i18n/index.ts b/src/i18n/index.ts index e1d0548..67a903d 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -82,7 +82,7 @@ export const setAppLanguage = async (language: string): Promise => { logger.warn("Unsupported language:", language); return; } - storage.setString(StorageKeys.LANGUAGE, language); + storage.set(StorageKeys.LANGUAGE, language); await i18n.changeLanguage(language); }; diff --git a/src/utils/storage.ts b/src/utils/storage.ts index 143da7e..9b41ebf 100644 --- a/src/utils/storage.ts +++ b/src/utils/storage.ts @@ -1,128 +1,38 @@ -import { createMMKV, type MMKV } from "react-native-mmkv"; +import { createMMKV } from "react-native-mmkv"; -// MMKV instance -const mmkvStorage: MMKV = createMMKV(); +import { logger } from "./logger"; -// Storage interface for backward compatibility -type StorageInterface = { - getItem: (key: string) => string | undefined; - setItem: (key: string, value: string) => void; - getString: (key: string) => string | undefined; - setString: (key: string, value: string) => void; - getBoolean: (key: string) => boolean | undefined; - set: (key: string, value: string | number | boolean) => void; - remove: (key: string) => void; - removeItem: (key: string) => void; - getAllKeys: () => string[]; - clear: () => void; -}; - -// Export storage object for backward compatibility -export const storage: StorageInterface = { - getItem: (key: string) => { - try { - return mmkvStorage.getString(key); - } catch { - return; - } - }, - setItem: (key: string, value: string) => { - try { - mmkvStorage.set(key, value); - } catch { - // Silent fail for storage operations - } - }, - getString: (key: string) => { - try { - return mmkvStorage.getString(key); - } catch { - return; - } - }, - setString: (key: string, value: string) => { - try { - mmkvStorage.set(key, value); - } catch { - // Silent fail for storage operations - } - }, - getBoolean: (key: string) => { - try { - return mmkvStorage.getBoolean(key); - } catch { - return; - } - }, - set: (key: string, value: string | number | boolean) => { - try { - mmkvStorage.set(key, value); - } catch { - // Silent fail for storage operations - } - }, - remove: (key: string) => { - try { - mmkvStorage.remove(key); - } catch { - // Silent fail for storage operations - } - }, - removeItem: (key: string) => { - try { - mmkvStorage.remove(key); - } catch { - // Silent fail for storage operations - } - }, - getAllKeys: () => { - try { - return mmkvStorage.getAllKeys(); - } catch { - return []; - } - }, - clear: () => { - try { - mmkvStorage.clearAll(); - } catch { - // Silent fail for storage operations - } - }, -}; +/** + * App-wide MMKV instance for one-off key/value data (see `StorageKeys`). + * Observables persist through Legend State's MMKV plugin instead. + */ +export const storage = createMMKV(); /** - * A utility function to get a JSON value from storage. - * @param key The key to retrieve. - * @returns The parsed JSON value or null if not found or on error. + * Keys written to `storage`. Add one here before reading or writing it. */ -export function getJSON(key: string): T | null { +export const StorageKeys = { + // Read by initializeI18n; written by setAppLanguage in src/i18n + LANGUAGE: "language", +} as const; + +export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys]; + +/** Reads and parses a JSON value; `null` when missing or unparsable. */ +export function getJSON(key: StorageKey): T | null { const value = storage.getString(key); - if (!value) { + if (value === undefined) { return null; } try { return JSON.parse(value) as T; - } catch { + } catch (error: unknown) { + logger.warn(`Ignoring unparsable JSON in storage key "${key}":`, error); return null; } } -/** - * A utility function to set a JSON value in storage. - * @param key The key to set. - * @param value The value to store. - */ -export function setJSON(key: string, value: T): void { +/** Serializes and writes a JSON value. */ +export function setJSON(key: StorageKey, value: unknown): void { storage.set(key, JSON.stringify(value)); } - -/** - * Storage keys constants for type safety. - */ -export const StorageKeys = { - // Read by initializeI18n; written by setLanguage in src/i18n - LANGUAGE: "language", -} as const; - -export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys]; From d0fb0c66782643f5c08e78538b7d7f2507f48c91 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:48:48 +0000 Subject: [PATCH 12/18] perf(settings): track only the fields a selector reads The hook spread settings$.get() before running the selector, so every selector subscribed to the whole store and re-ran on any change. Selectors now read through per-field getters; calling the hook without a selector still tracks everything. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- src/stores/settings.ts | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/stores/settings.ts b/src/stores/settings.ts index 095c477..8b98f3d 100644 --- a/src/stores/settings.ts +++ b/src/stores/settings.ts @@ -76,6 +76,22 @@ const settingsActions: SettingsActions = { }, }; +type SettingsFields = RuntimeSettings & PersistentSettings; + +const settingsKeys = Object.keys({ ...defaultRuntimeSettings, ...defaultPersistentSettings }) as (keyof SettingsFields)[]; + +/** + * Live view of the store: each field is a getter on its own child observable, + * so a selector inside `useSelector` only tracks the fields it reads. + */ +const settingsState = Object.defineProperties( + { ...settingsActions }, + Object.fromEntries( + settingsKeys.map((key) => [key, { enumerable: true, get: () => settings$[key].get() }]), + ), +) as SettingsState; + +/** Snapshot of every field plus the actions, for non-React callers. */ const getSettingsState = (): SettingsState => ({ ...settings$.get(), ...settingsActions, @@ -89,10 +105,8 @@ type SettingsStoreHook = { export const useSettingsStore = Object.assign( function useSettingsStore(selector?: (state: SettingsState) => T) { - return useSelector(() => { - const state = getSettingsState(); - return (selector ? selector(state) : state) as T; - }); + // Without a selector the caller asked for everything, so track every field. + return useSelector(() => (selector ? selector(settingsState) : getSettingsState()) as T); }, { getState: getSettingsState }, ) as SettingsStoreHook; From b030161e569d015e5db6d93d87df33b45ed85140 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:49:25 +0000 Subject: [PATCH 13/18] feat(data): add a useQuery hook for live WatermelonDB queries Waits for databaseReady, subscribes to the query and cleans up on unmount, so screens don't repeat that wiring. Clauses are compared by value, so inline Q calls don't resubscribe every render. useNotes now uses it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- AGENTS.md | 4 +-- src/hooks/useQuery.ts | 57 +++++++++++++++++++++++++++++++++ src/screens/tab-two/useNotes.ts | 29 ++--------------- 3 files changed, 62 insertions(+), 28 deletions(-) create mode 100644 src/hooks/useQuery.ts diff --git a/AGENTS.md b/AGENTS.md index 75ddf4a..356fb7f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,7 +59,7 @@ src/ │ ├── common/ # shared primitives (pressable, error-boundary, legend-list) │ └── layouts/ # Layout.Base / Bare / Modal ├── data/ # WatermelonDB schema, migrations, models/, database instance -├── hooks/ # app-wide hooks (refresh control) +├── hooks/ # app-wide hooks (refresh control, WatermelonDB useQuery) ├── i18n/ # initializeI18n + locales//.json ├── providers/ # MainProvider (TamaguiProvider + ErrorBoundary + DatabaseProvider + theme tracking) ├── stores/ # app observables (settings$) @@ -235,7 +235,7 @@ Do not persist derived data, functions, or React nodes. Do not create a new MMKV - Everything lives in `src/data/`: `schema.ts`, `migrations.ts`, `models/.ts`, `database.ts` (Nitro SQLite adapter, plus `define-columns.ts`). Export from `src/data/index.ts`; `DatabaseProvider` is composed into `MainProvider`. - Changing a table: bump `version` in `schema.ts` **and** add a step in `migrations.ts`. Register new models in `modelClasses`. - Models do not use decorators (`experimentalDecorators` is off). Declare typed fields on the class and bind them with `Object.defineProperties(Model.prototype, defineColumns({...}))` from `src/data/define-columns.ts` (see `models/note.ts`). -- Read via `useDatabase()` + `collection.query(...).observe()` (see `src/screens/tab-two/useNotes.ts`); write inside `database.write(...)`. +- Read with `useQuery("table", [Q...])` from `@/hooks/useQuery` (waits for `databaseReady`, subscribes, cleans up; see `src/screens/tab-two/useNotes.ts`); write inside `database.write(...)`. - Needs a development build (not Expo Go); the native engine is a Nitro module (`react-native-nitro-modules`, `rxjs` peer). Await `databaseReady` from `@/data` before the first query or write. - Do not put queryable/relational data in `settings$` or MMKV. diff --git a/src/hooks/useQuery.ts b/src/hooks/useQuery.ts new file mode 100644 index 0000000..fb6a10a --- /dev/null +++ b/src/hooks/useQuery.ts @@ -0,0 +1,57 @@ +import { useEffect, useState } from "react"; +import type { Model } from "react-native-watermelondb"; +import type { Clause } from "react-native-watermelondb/QueryDescription"; +import { useDatabase } from "react-native-watermelondb/react"; + +import { databaseReady } from "@/data"; +import { logger } from "@/utils/logger"; +import { captureException } from "@/utils/sentry"; + +/** + * Live WatermelonDB query: waits for `databaseReady`, subscribes to the + * results and unsubscribes on unmount or when the query changes. + * + * Clauses are compared by value, so inline `Q.where(...)` calls are fine. + * + * ```ts + * const notes = useQuery("notes", [Q.sortBy("created_at", Q.desc)]); + * ``` + */ +export function useQuery(table: string, clauses: readonly Clause[] = []): T[] { + const database = useDatabase(); + const [records, setRecords] = useState([]); + + // Q clauses are plain data, so their JSON is a stable identity for the query + // and round-trips back to the same clauses inside the effect. + const queryKey = JSON.stringify(clauses); + + useEffect(() => { + let cancelled = false; + let unsubscribe: (() => void) | undefined; + + databaseReady + .then(() => { + if (cancelled) { + return; + } + const queryClauses = JSON.parse(queryKey) as Clause[]; + const subscription = database + .get(table) + .query(...queryClauses) + .observe() + .subscribe(setRecords); + unsubscribe = () => subscription.unsubscribe(); + }) + .catch((error: unknown) => { + logger.error(`Query on "${table}" failed:`, error); + captureException(error); + }); + + return () => { + cancelled = true; + unsubscribe?.(); + }; + }, [database, table, queryKey]); + + return records; +} diff --git a/src/screens/tab-two/useNotes.ts b/src/screens/tab-two/useNotes.ts index bbd8269..3baae35 100644 --- a/src/screens/tab-two/useNotes.ts +++ b/src/screens/tab-two/useNotes.ts @@ -1,37 +1,14 @@ import { Q } from "react-native-watermelondb"; import { useDatabase } from "react-native-watermelondb/react"; -import { useCallback, useEffect, useState } from "react"; +import { useCallback } from "react"; import { databaseReady, type Note } from "@/data"; +import { useQuery } from "@/hooks/useQuery"; import { logger } from "@/utils/logger"; export function useNotes() { const database = useDatabase(); - const [notes, setNotes] = useState([]); - - useEffect(() => { - let cancelled = false; - let unsubscribe: (() => void) | undefined; - - databaseReady - .then(() => { - if (cancelled) { - return; - } - const subscription = database - .get("notes") - .query(Q.sortBy("created_at", Q.desc)) - .observe() - .subscribe(setNotes); - unsubscribe = () => subscription.unsubscribe(); - }) - .catch((error: unknown) => logger.error("Database not ready:", error)); - - return () => { - cancelled = true; - unsubscribe?.(); - }; - }, [database]); + const notes = useQuery("notes", [Q.sortBy("created_at", Q.desc)]); const addNote = useCallback( async (title: string): Promise => { From b7cec78da156ac9f0297349840830dedfafaa0ad Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:50:03 +0000 Subject: [PATCH 14/18] fix(logger): bind the standalone log functions to the logger Destructuring the methods off the instance lost `this`, so calling the exported warn() or error() threw. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- src/utils/logger.ts | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/utils/logger.ts b/src/utils/logger.ts index 80cd9d0..909cf5a 100644 --- a/src/utils/logger.ts +++ b/src/utils/logger.ts @@ -9,6 +9,16 @@ export interface LoggerConfig { timestamp?: boolean; } +/** Receives every debug/info/warn/error call, whether or not the console is enabled. */ +export type LogSink = (level: LogLevel, message: string, args: unknown[]) => void; + +let logSink: LogSink | undefined; + +/** Forwards log calls to another destination (Sentry registers one in `initSentry`). */ +export const setLogSink = (sink: LogSink | undefined): void => { + logSink = sink; +}; + const LOG_LEVELS: Record = { debug: 0, info: 1, @@ -32,6 +42,10 @@ class Logger { return this.config.enabled && LOG_LEVELS[level] >= LOG_LEVELS[this.config.minLevel]; } + private formatPrefix(): string { + return this.config.prefix ? `[${this.config.prefix}] ` : ""; + } + private formatMessage(level: LogLevel, message: string): string { const parts: string[] = []; @@ -49,24 +63,28 @@ class Logger { } debug(message: string, ...args: unknown[]): void { + logSink?.("debug", this.formatPrefix() + message, args); if (this.shouldLog("debug")) { console.log(this.formatMessage("debug", message), ...args); } } info(message: string, ...args: unknown[]): void { + logSink?.("info", this.formatPrefix() + message, args); if (this.shouldLog("info")) { console.info(this.formatMessage("info", message), ...args); } } warn(message: string, ...args: unknown[]): void { + logSink?.("warn", this.formatPrefix() + message, args); if (this.shouldLog("warn")) { console.warn(this.formatMessage("warn", message), ...args); } } error(message: string, ...args: unknown[]): void { + logSink?.("error", this.formatPrefix() + message, args); if (this.shouldLog("error")) { console.error(this.formatMessage("error", message), ...args); } @@ -129,4 +147,8 @@ export const createLogger = (prefix: string, config?: Partial): Lo }; // Simple functions that mirror console methods but respect dev mode -export const { log, debug, info, warn, error } = logger; +export const log = logger.log.bind(logger); +export const debug = logger.debug.bind(logger); +export const info = logger.info.bind(logger); +export const warn = logger.warn.bind(logger); +export const error = logger.error.bind(logger); From 6046acb6619bf376b35402c71ca115952563a304 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:50:13 +0000 Subject: [PATCH 15/18] feat(sentry): tag events by variant, trace routes and keep log breadcrumbs - environment comes from the build variant - performance traces are sampled per variant (all of preview, 20% of production, none in development) - expoRouterIntegration names navigation spans after routes - logger warnings and errors become breadcrumbs through the log sink added to @/utils/logger in the previous commit, so reports carry context even though release builds keep the console quiet release is left to the native default so source maps uploaded by the Expo plugin keep matching. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- src/utils/env.ts | 2 -- src/utils/sentry.ts | 29 ++++++++++++++++++++++++++--- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/src/utils/env.ts b/src/utils/env.ts index a0f264e..5f50753 100644 --- a/src/utils/env.ts +++ b/src/utils/env.ts @@ -19,8 +19,6 @@ const resolveVariant = (value: unknown): AppVariant => export const env = { /** Build variant from `app.config.ts` (`APP_VARIANT`). */ appVariant: resolveVariant(Constants.expoConfig?.extra?.variant), - /** App version from `app.json`, used for Sentry releases. */ - appVersion: Constants.expoConfig?.version ?? "0.0.0", revenueCatIosApiKey: read(process.env.EXPO_PUBLIC_REVENUECAT_IOS_API_KEY), revenueCatAndroidApiKey: read(process.env.EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY), sentryDsn: read(process.env.EXPO_PUBLIC_SENTRY_DSN), diff --git a/src/utils/sentry.ts b/src/utils/sentry.ts index 85b4146..24ce256 100644 --- a/src/utils/sentry.ts +++ b/src/utils/sentry.ts @@ -1,10 +1,22 @@ -import { captureException as sentryCaptureException, init } from "@sentry/react-native"; +import { + addBreadcrumb, + captureException as sentryCaptureException, + expoRouterIntegration, + init, +} from "@sentry/react-native"; import { env } from "./env"; -import { logger } from "./logger"; +import { logger, setLogSink } from "./logger"; const sentryDsn = env.sentryDsn; +// Share of sessions that record performance traces, per build variant. +const TRACES_SAMPLE_RATE: Record = { + development: 0, + preview: 1, + production: 0.2, +}; + let initialized = false; export const initSentry = (): void => { @@ -18,7 +30,18 @@ export const initSentry = (): void => { init({ dsn: sentryDsn, enabled: !__DEV__, - tracesSampleRate: 0, + environment: env.appVariant, + tracesSampleRate: TRACES_SAMPLE_RATE[env.appVariant], + // Names navigation spans and breadcrumbs after Expo Router routes. + integrations: [expoRouterIntegration()], + }); + + // Warnings and errors from @/utils/logger become breadcrumbs on the next + // reported event, even in release builds where the console is silent. + setLogSink((level, message) => { + if (level === "warn" || level === "error") { + addBreadcrumb({ category: "logger", level: level === "warn" ? "warning" : "error", message }); + } }); } catch (error) { logger.error("Failed to initialize Sentry:", error); From 603abb6451cec7e3d025c88b5c7c8f4a4bf864e7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:50:42 +0000 Subject: [PATCH 16/18] feat(icons): add a settings glyph to the ui icon font Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- assets/icons/nanoicons/ui.glyphmap.json | 2 +- assets/icons/nanoicons/ui.ttf | Bin 2064 -> 2336 bytes assets/icons/ui/settings.svg | 4 ++++ 3 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 assets/icons/ui/settings.svg diff --git a/assets/icons/nanoicons/ui.glyphmap.json b/assets/icons/nanoicons/ui.glyphmap.json index 63a578e..414b04c 100644 --- a/assets/icons/nanoicons/ui.glyphmap.json +++ b/assets/icons/nanoicons/ui.glyphmap.json @@ -1 +1 @@ -{"m":{"f":"ui-c5f20b27","u":1024,"z":1024,"s":59648,"h":"c5f20b27fe9971b2354e13971b9366bdfe82d51919eecb9a473e237bef63337b"},"i":{"chevron-left":[1024,[[59648,"currentColor"]]],"clock":[1024,[[59649,"currentColor"]]],"house":[1024,[[59650,"currentColor"]]],"x":[1024,[[59651,"currentColor"]]]}} \ No newline at end of file +{"m":{"f":"ui-071fbd38","u":1024,"z":1024,"s":59648,"h":"071fbd38d91bcd3158a95c56361ea6dfe16aa0c435cd8ad2d40724aefd4e2fae"},"i":{"chevron-left":[1024,[[59648,"currentColor"]]],"clock":[1024,[[59649,"currentColor"]]],"house":[1024,[[59650,"currentColor"]]],"settings":[1024,[[59651,"currentColor"]]],"x":[1024,[[59652,"currentColor"]]]}} \ No newline at end of file diff --git a/assets/icons/nanoicons/ui.ttf b/assets/icons/nanoicons/ui.ttf index bfe9f08d723c29a8ad7a506c1a4d2da14cb0f94d..407c6b32a8f79a7d967d9ff248817d8665585040 100644 GIT binary patch delta 736 zcmZva%WD%+6vofZokx`6OS)^;qTnA;gQqP*EWL0a-|u{fdpYO6cD$W1fB?Wn*aQl` z2M;6hIp@=_NZ#XIUajd(u>I%(5G&5RrRuZdi%25}U|9s92jzmEf3o}Q2!NYLzfwlP zA22siFQdLvuB~k_ctHIU7e}?Rs?)H=k9r5Sy{2!(n#2h!2;L#^)%9Azn0WIU^%uP4 zX0y>=0~>Gv7cdMyU}$#x!yI9@f6o)Z_txQfW~3r=aCSB*M^asmEwfzrKOpZ7dwba) z-S2ulR%MVGzdfEA%-B5ct+Rj{nrykh;C1CZ*LQ;6oXeYDkQ3?j2(TgfKI{=q>tUbF zN6a_oacU4Sr&;&qKK+AL8w1O6@o-?PPpWmgUZZ`p$c8SxB0o=KSZ56wbC*556;)%! zm3$((R48?-daF|j{Uakstgt!flEVB(0Pg=;f3>^^L_U__i)dp?|ila4!{&nz!2EpS&GEx_OD5~ zp*YN`VhP@lD}eJ*B=X9!{GMu809%UUxgd#0d!5f8fS)J-N`VCDt6d8WF)?>d!U9e_bhdw=Y4sen6Ov53# z<-sy|Y=N1#j<@w(RE~tQkyu*FR~6By7KM>AR%RrlT-3EdI2amJ%_rw(BZnwtL=Zxj uForZF + + + From 2b7f01c3a4ce73e4df2b2307328343ae28fe4a5d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:51:54 +0000 Subject: [PATCH 17/18] feat(settings): add a settings tab wired to the existing stores Uses @expo/ui FieldGroup rows for theme (match system, dark mode), language, text size and date format, the RevenueCat upgrade and restore actions, and the app version. Paywall results now report whether the user cancelled, so the screen only shows a toast for real failures. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012DRYTsbYhbXbbVqgg3dnYn --- AGENTS.md | 4 +- app/(tabs)/_layout.tsx | 7 ++ app/(tabs)/settings.tsx | 1 + src/i18n/locales/en/screens.json | 39 +++++++++ src/screens/settings/index.tsx | 145 +++++++++++++++++++++++++++++++ src/utils/env.ts | 2 + src/utils/revenuecat.ts | 11 ++- 7 files changed, 205 insertions(+), 4 deletions(-) create mode 100644 app/(tabs)/settings.tsx create mode 100644 src/screens/settings/index.tsx diff --git a/AGENTS.md b/AGENTS.md index 356fb7f..3cfc67b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -44,7 +44,8 @@ app/ ├── (tabs)/ │ ├── _layout.tsx # bottom tabs layout │ ├── index.tsx # route wrapper -> @/screens/tab-one -│ └── tab-two.tsx # route wrapper -> @/screens/tab-two +│ ├── tab-two.tsx # route wrapper -> @/screens/tab-two +│ └── settings.tsx # route wrapper -> @/screens/settings ├── stack-one.tsx # route wrapper -> @/screens/stack-one ├── modal-one.tsx # route wrapper -> @/screens/modal-one └── +not-found.tsx # route wrapper -> @/screens/not-found @@ -52,6 +53,7 @@ src/ ├── screens/ # screen UI rendered by routes │ ├── tab-one/ │ ├── tab-two/ +│ ├── settings/ │ ├── stack-one/ │ ├── modal-one/ │ └── not-found/ diff --git a/app/(tabs)/_layout.tsx b/app/(tabs)/_layout.tsx index ed2f092..614057b 100644 --- a/app/(tabs)/_layout.tsx +++ b/app/(tabs)/_layout.tsx @@ -35,6 +35,13 @@ export default function TabLayout() { tabBarIcon: ({ color, size }) => , }} /> + , + }} + /> ); } diff --git a/app/(tabs)/settings.tsx b/app/(tabs)/settings.tsx new file mode 100644 index 0000000..b6dac30 --- /dev/null +++ b/app/(tabs)/settings.tsx @@ -0,0 +1 @@ +export { SettingsScreen as default } from "@/screens/settings"; diff --git a/src/i18n/locales/en/screens.json b/src/i18n/locales/en/screens.json index 2b14734..478e125 100644 --- a/src/i18n/locales/en/screens.json +++ b/src/i18n/locales/en/screens.json @@ -35,5 +35,44 @@ "title": "Bottom sheet", "body": "The universal BottomSheet is a sibling of Host, not nested in it." } + }, + "settings": { + "title": "Settings", + "appearance": { + "title": "Appearance", + "followSystem": "Match system", + "darkMode": "Dark mode" + }, + "display": { + "title": "Display", + "language": "Language", + "textSize": "Text size", + "dateFormat": "Date format" + }, + "languages": { + "en": "English" + }, + "textSizes": { + "smaller": "Smaller", + "default": "Default", + "bigger": "Bigger" + }, + "subscription": { + "title": "Subscription", + "status": "Status", + "premium": "Premium", + "free": "Free", + "upgrade": "Upgrade to Premium", + "restore": "Restore purchases", + "purchased": "Welcome to Premium", + "restored": "Purchases restored", + "nothingToRestore": "No purchases to restore", + "paywallFailed": "Couldn't open the paywall. Try again.", + "restoreFailed": "Couldn't restore purchases. Try again." + }, + "about": { + "title": "About", + "version": "Version" + } } } diff --git a/src/screens/settings/index.tsx b/src/screens/settings/index.tsx new file mode 100644 index 0000000..255a076 --- /dev/null +++ b/src/screens/settings/index.tsx @@ -0,0 +1,145 @@ +import { Button, FieldGroup, Host, Picker, Row, Spacer, Switch, Text } from "@expo/ui"; +import { useBottomTabBarHeight } from "expo-router/tabs"; +import { useCallback, useState } from "react"; +import { useTranslation } from "react-i18next"; + +import { Toast } from "@/components/common/toast"; +import { SafeScreen } from "@/components/layouts/safe-screen"; +import { SUPPORTED_LANGUAGES } from "@/i18n"; +import { useSettingsStore } from "@/stores/settings"; +import { useThemeStore } from "@/theme/stores/useThemeStore"; +import type { TextSizePreference } from "@/theme/types"; +import type { ValidDateFormat } from "@/types/date"; +import { formatDate } from "@/utils/date"; +import { env } from "@/utils/env"; +import { hasPremiumEntitlement, PAYWALL_PLACEMENTS, presentPaywall, restorePurchases } from "@/utils/revenuecat"; + +const TEXT_SIZES: readonly TextSizePreference[] = ["smaller", "default", "bigger"]; +const DATE_FORMATS: readonly ValidDateFormat[] = ["DD/MM/YYYY", "MM/DD/YYYY", "YYYY/MM/DD"]; +const FILL = { flex: 1 } as const; +// Day 31 makes the day/month order of each format obvious in the picker. +const SAMPLE_DATE = new Date(2026, 11, 31); + +export function SettingsScreen() { + const { t } = useTranslation("screens"); + const tabBarHeight = useBottomTabBarHeight(); + const [toastMessage, setToastMessage] = useState(null); + const hideToast = useCallback(() => setToastMessage(null), []); + + const mode = useThemeStore((s) => s.mode); + const followSystemTheme = useThemeStore((s) => s.followSystemTheme); + const language = useSettingsStore((s) => s.language); + const textSizePreference = useSettingsStore((s) => s.textSizePreference); + const dateFormat = useSettingsStore((s) => s.dateFormat); + const premium = useSettingsStore((s) => s.premium); + const isDark = mode === "dark"; + + const handleFollowSystem = (value: boolean) => { + useThemeStore.getState().setConfig({ followSystemTheme: value, defaultMode: mode }); + }; + + const handleUpgrade = async () => { + const result = await presentPaywall(PAYWALL_PLACEMENTS.subscription); + if (result.success) { + setToastMessage(t("settings.subscription.purchased")); + } else if (!result.cancelled) { + setToastMessage(t("settings.subscription.paywallFailed")); + } + }; + + const handleRestore = async () => { + const result = await restorePurchases(); + if (!result.success) { + setToastMessage(t("settings.subscription.restoreFailed")); + } else if (hasPremiumEntitlement(result.customerInfo)) { + setToastMessage(t("settings.subscription.restored")); + } else { + setToastMessage(t("settings.subscription.nothingToRestore")); + } + }; + + return ( + + + + + + useThemeStore.getState().setMode(value ? "dark" : "light")} + /> + + + + + {t("settings.display.language")} + + useSettingsStore.getState().setLanguage(code)} + > + {SUPPORTED_LANGUAGES.map((code) => ( + + ))} + + + + {t("settings.display.textSize")} + + useSettingsStore.getState().setTextSizePreference(size)} + > + {TEXT_SIZES.map((size) => ( + + ))} + + + + {t("settings.display.dateFormat")} + + useSettingsStore.getState().setDateFormat(format)} + > + {DATE_FORMATS.map((format) => ( + + ))} + + + + + + + {t("settings.subscription.status")} + + {premium ? t("settings.subscription.premium") : t("settings.subscription.free")} + + {premium ? null : ( +