Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(mobile): redesign account tab and settings tests
Richie McIlroy55cf9c1426a7
diff --git a/apps/mobile/app/(tabs)/account.tsx b/apps/mobile/app/(tabs)/account.tsxindex 7bb19f2b0..b3779465e 100644--- a/apps/mobile/app/(tabs)/account.tsx+++ b/apps/mobile/app/(tabs)/account.tsx@@ -1,8 +1,14 @@import Constants from "expo-constants";import { Image } from "expo-image";+import { router } from "expo-router";import { type SFSymbol, SymbolView } from "expo-symbols";-import * as WebBrowser from "expo-web-browser";-import { type ReactNode, useRef, useState } from "react";+import {+ type ReactNode,+ useCallback,+ useEffect,+ useRef,+ useState,+} from "react";import {ActionSheetIOS,ActivityIndicator,@@ -16,6 +22,7 @@ import {} from "react-native";import { apiBaseUrl, useAuth } from "@/auth/AuthContext";import { SignInPanel } from "@/auth/SignInPanel";+import { getProPlan } from "@/billing/pro";import { GlassSurface } from "@/components/GlassSurface";import { OrgSwitcher } from "@/components/OrgSwitcher";import { Screen } from "@/components/Screen";@@ -154,18 +161,141 @@ function SettingsSection({);}-type AccountAction =- | "appSettings"- | "organizationSettings"- | "refresh"- | "signOut";+type AccountAction = "appSettings" | "refresh" | "signOut";++type PlanStatus = "loading" | "free" | "pro" | "error";++const openExternalPage = async (path: string) => {+ try {+ await Linking.openURL(new URL(path, apiBaseUrl).toString());+ } catch {+ Alert.alert("Unable to open page", "Check your connection and try again.");+ }+};++function PlanStatusButton({+ status,+ disabled,+ onRefresh,+}: {+ status: PlanStatus;+ disabled: boolean;+ onRefresh: () => void;+}) {+ if (status === "loading") {+ return (+ <View style={styles.planSection}>+ <Text style={styles.sectionTitle}>Plan</Text>+ <View+ accessibilityLabel="Checking Cap plan"+ accessibilityRole="summary"+ style={styles.planStatusButton}+ >+ <View pointerEvents="none" style={styles.planStatusInsetHighlight} />+ <View style={styles.planStatusIcon}>+ <ActivityIndicator color={colors.white} size="small" />+ </View>+ <View style={styles.planStatusText}>+ <Text style={styles.planStatusTitle}>Checking your plan...</Text>+ </View>+ </View>+ </View>+ );+ }++ if (status === "error") {+ return (+ <View style={styles.planSection}>+ <Text style={styles.sectionTitle}>Plan</Text>+ <Pressable+ accessibilityHint="Checks your Cap plan again"+ accessibilityLabel="Cap plan unavailable"+ accessibilityRole="button"+ accessibilityState={{ disabled }}+ disabled={disabled}+ onPress={onRefresh}+ style={({ pressed }) => [+ styles.planStatusButton,+ disabled && styles.planStatusButtonDisabled,+ pressed && !disabled && styles.planStatusButtonPressed,+ ]}+ >+ <View pointerEvents="none" style={styles.planStatusInsetHighlight} />+ <View style={styles.planStatusIcon}>+ <SymbolView+ name="arrow.clockwise"+ size={18}+ tintColor={colors.white}+ weight="semibold"+ />+ </View>+ <View style={styles.planStatusText}>+ <Text style={styles.planStatusTitle}>Plan unavailable</Text>+ <Text style={styles.planStatusDetail}>Tap to try again</Text>+ </View>+ <SymbolView+ name="chevron.right"+ size={14}+ tintColor={colors.white}+ weight="semibold"+ />+ </Pressable>+ </View>+ );+ }++ const isPro = status === "pro";++ const content = (+ <>+ <View pointerEvents="none" style={styles.planStatusInsetHighlight} />+ <View style={styles.planStatusIcon}>+ <SymbolView+ name={isPro ? "checkmark" : "sparkles"}+ size={18}+ tintColor={colors.white}+ weight="semibold"+ />+ </View>+ <View style={styles.planStatusText}>+ <Text style={styles.planStatusTitle}>+ {isPro ? "Cap Pro" : "Free plan"}+ </Text>+ <Text style={styles.planStatusDetail}>+ {isPro+ ? "Unlimited recording time"+ : "Free plan · Recordings are limited to 5 minutes"}+ </Text>+ </View>+ </>+ );++ return (+ <View style={styles.planSection}>+ <Text style={styles.sectionTitle}>Plan</Text>+ <View+ accessibilityLabel={`Cap plan: ${isPro ? "Cap Pro" : "Free"}`}+ accessibilityRole="summary"+ accessibilityValue={{+ text: isPro+ ? "Cap Pro. Unlimited recording time"+ : "Free plan. Recordings are limited to 5 minutes",+ }}+ style={styles.planStatusButton}+ >+ {content}+ </View>+ </View>+ );+}export default function AccountScreen() {const auth = useAuth();- const appVersion = Constants.expoConfig?.version ?? "0.1.0";+ const appVersion = Constants.expoConfig?.version ?? "1.0.0";const [accountAction, setAccountAction] = useState<AccountAction | null>(null,);+ const [planStatus, setPlanStatus] = useState<PlanStatus>("loading");const accountActionRef = useRef<AccountAction | null>(null);const accountActionHint =accountAction === "refresh"@@ -177,6 +307,23 @@ export default function AccountScreen() {: null;const accountActionDisabled = accountAction !== null;+ const refreshPlan = useCallback(async () => {+ if (!auth.apiKey) return;+ setPlanStatus("loading");+ try {+ const input = { apiKey: auth.apiKey, baseUrl: apiBaseUrl };+ const plan = await getProPlan(input);+ setPlanStatus(plan.upgraded ? "pro" : "free");+ } catch {+ setPlanStatus("error");+ }+ }, [auth.apiKey]);++ useEffect(() => {+ if (auth.status !== "signedIn" || !auth.apiKey) return;+ void refreshPlan();+ }, [auth.apiKey, auth.status, refreshPlan]);+const runAccountAction = async (action: AccountAction,operation: () => Promise<unknown>,@@ -238,12 +385,12 @@ export default function AccountScreen() {</Screen>);}-return (<Screentitle="Account"subtitle={auth.bootstrap?.user.email ?? null}scroll+ contentInsetBottom={112}>{auth.bootstrap ? (<GlassSurface@@ -269,7 +416,9 @@ export default function AccountScreen() {</View><View style={styles.identityText}><Text numberOfLines={1} style={styles.name}>- {auth.bootstrap.user.name ?? "Cap user"}+ {[auth.bootstrap.user.name, auth.bootstrap.user.lastName]+ .filter(Boolean)+ .join(" ") || "Cap user"}</Text><Text numberOfLines={1} style={styles.email}>{auth.bootstrap.user.email}@@ -282,34 +431,38 @@ export default function AccountScreen() {/></GlassSurface>) : null}- <SettingsSection title="Organization">+ <SettingsSection title="Profile"><SettingsRow- accessibilityValueText={- accountAction === "organizationSettings"- ? "Opening organization settings"+ accessibilityHint="Opens native profile settings"+ disabled={accountActionDisabled}+ label="Name and Profile Image"+ symbol="person.crop.circle"+ onPress={() => router.push("/profile-settings")}+ value={+ auth.bootstrap+ ? [auth.bootstrap.user.name, auth.bootstrap.user.lastName]+ .filter(Boolean)+ .join(" ") || undefined: undefined}+ />+ </SettingsSection>+ <PlanStatusButton+ disabled={accountActionDisabled}+ onRefresh={() => {+ void refreshPlan();+ }}+ status={planStatus}+ />+ <SettingsSection title="Organization">+ <SettingsRowaccessibilityHint={- accountActionHint ??- "Opens organization settings in a browser sheet"+ accountActionHint ?? "Opens native organization settings"}- busy={accountAction === "organizationSettings"}disabled={accountActionDisabled}label="Organization Settings"symbol="building.2"- onPress={() => {- void runAccountAction("organizationSettings", () =>- WebBrowser.openBrowserAsync(- new URL(- "/dashboard/settings/organization",- apiBaseUrl,- ).toString(),- ),- );- }}- value={- accountAction === "organizationSettings" ? "Opening..." : undefined- }+ onPress={() => router.push("/organization-settings")}/></SettingsSection><SettingsSection title="App">@@ -323,7 +476,9 @@ export default function AccountScreen() {label="Refresh"symbol="arrow.clockwise"onPress={() => {- void runAccountAction("refresh", auth.refresh);+ void runAccountAction("refresh", () =>+ Promise.all([auth.refresh(), refreshPlan()]),+ );}}value={accountAction === "refresh" ? "Refreshing..." : undefined}/>@@ -369,11 +524,111 @@ export default function AccountScreen() {value={accountAction === "signOut" ? "Signing out..." : undefined}/></SettingsSection>+ <SettingsSection title="Help & Legal">+ <SettingsRow+ accessibilityHint="Opens Cap help and support"+ disabled={accountActionDisabled}+ label="Help & Support"+ symbol="questionmark.circle"+ onPress={() => {+ void openExternalPage("/docs");+ }}+ />+ <View style={styles.separator} />+ <SettingsRow+ accessibilityHint="Opens the Cap privacy policy"+ disabled={accountActionDisabled}+ label="Privacy Policy"+ symbol="hand.raised"+ onPress={() => {+ void openExternalPage("/privacy");+ }}+ />+ <View style={styles.separator} />+ <SettingsRow+ accessibilityHint="Opens the Cap terms of service"+ disabled={accountActionDisabled}+ label="Terms of Service"+ symbol="doc.text"+ onPress={() => {+ void openExternalPage("/terms");+ }}+ />+ </SettingsSection>+ <SettingsSection title="Danger Zone">+ <SettingsRow+ accessibilityHint="Opens permanent account deletion"+ disabled={accountActionDisabled}+ label="Delete account"+ symbol="trash"+ onPress={() => router.push("/delete-account")}+ tintColor={colors.red9}+ destructive+ />+ </SettingsSection></Screen>);}const styles = StyleSheet.create({+ planSection: {+ marginTop: 16,+ gap: 8,+ },+ planStatusButton: {+ minHeight: 68,+ flexDirection: "row",+ alignItems: "center",+ gap: 12,+ borderRadius: radius.full,+ borderWidth: 1,+ borderColor: colors.buttonBlueBorder,+ backgroundColor: colors.buttonBlue,+ paddingHorizontal: 16,+ paddingVertical: 12,+ ...squircle,+ },+ planStatusInsetHighlight: {+ position: "absolute",+ top: 0,+ left: 0,+ right: 0,+ height: 1.5,+ backgroundColor: "rgba(255, 255, 255, 0.4)",+ },+ planStatusButtonPressed: {+ backgroundColor: colors.buttonBlueHover,+ },+ planStatusButtonDisabled: {+ borderColor: colors.gray8,+ backgroundColor: colors.gray7,+ },+ planStatusIcon: {+ width: 34,+ height: 34,+ borderRadius: radius.full,+ alignItems: "center",+ justifyContent: "center",+ backgroundColor: "rgba(255, 255, 255, 0.16)",+ ...squircle,+ },+ planStatusText: {+ flex: 1,+ minWidth: 0,+ gap: 1,+ },+ planStatusTitle: {+ fontFamily: fonts.bold,+ fontSize: 16,+ lineHeight: 20,+ color: colors.white,+ },+ planStatusDetail: {+ fontFamily: fonts.regular,+ fontSize: 13,+ lineHeight: 17,+ color: "rgba(255, 255, 255, 0.82)",+ },card: {borderRadius: radius.md,borderWidth: StyleSheet.hairlineWidth,diff --git a/apps/mobile/src/screens/account-settings.test.tsx b/apps/mobile/src/screens/account-settings.test.tsxindex ad331a8bc..7fe78eaa2 100644--- a/apps/mobile/src/screens/account-settings.test.tsx+++ b/apps/mobile/src/screens/account-settings.test.tsx@@ -17,11 +17,13 @@ type JsonNode = ReactTestRendererJSON | ReactTestRendererJSON[] | string | null;const auth = vi.hoisted(() => ({value: {status: "signedIn" as const,+ apiKey: "mobile-key",bootstrap: {activeOrganizationId: "org_123",user: {email: "[email protected]",imageUrl: null,+ lastName: "McIlroy",name: "Richie",},organizations: [@@ -40,6 +42,32 @@ const auth = vi.hoisted(() => ({},}));+const billing = vi.hoisted(() => ({+ getProPlan: vi.fn(+ (): Promise<{+ upgraded: boolean;+ stripeSubscriptionStatus: string | null;+ }> =>+ Promise.resolve({+ upgraded: false,+ stripeSubscriptionStatus: null,+ }),+ ),+}));++const actionSheet = vi.hoisted(() => ({+ showActionSheetWithOptions: vi.fn(),+}));++const linking = vi.hoisted(() => ({+ openSettings: vi.fn(() => Promise.resolve()),+ openURL: vi.fn(() => Promise.resolve()),+}));++const router = vi.hoisted(() => ({+ push: vi.fn(),+}));+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -77,19 +105,11 @@ vi.mock("react-native", async () => {React.createElement(name, props, children);return {- ActionSheetIOS: {- showActionSheetWithOptions: vi.fn(),- },+ ActionSheetIOS: actionSheet,ActivityIndicator: createHost("ActivityIndicator"),- Alert: {- alert: vi.fn(),- },- Linking: {- openSettings: vi.fn(),- },- Platform: {- OS: "ios",- },+ Alert: { alert: vi.fn() },+ Linking: linking,+ Platform: { OS: "ios" },Pressable: createHost("Pressable"),StyleSheet: {create: <T extends Record<string, unknown>>(styles: T) => styles,@@ -103,7 +123,7 @@ vi.mock("react-native", async () => {vi.mock("expo-constants", () => ({default: {expoConfig: {- version: "0.1.0",+ version: "1.0.0",},},}));@@ -124,15 +144,15 @@ vi.mock("expo-symbols", async () => {};});-vi.mock("expo-web-browser", () => ({- openBrowserAsync: vi.fn(),-}));+vi.mock("expo-router", () => ({ router }));vi.mock("@/auth/AuthContext", () => ({apiBaseUrl: "https://cap.so",useAuth: () => auth.value,}));+vi.mock("@/billing/pro", () => billing);+vi.mock("@/auth/SignInPanel", async () => {const React = await import("react");return {@@ -179,61 +199,108 @@ vi.mock("@/components/Screen", async () => {describe("AccountScreen", () => {beforeEach(() => {- auth.value.refresh.mockReset();+ vi.clearAllMocks();+ billing.getProPlan.mockResolvedValue({+ upgraded: false,+ stripeSubscriptionStatus: null,+ });auth.value.refresh.mockResolvedValue(undefined);- auth.value.setActiveOrganization.mockReset();auth.value.setActiveOrganization.mockResolvedValue(undefined);- auth.value.signOut.mockReset();auth.value.signOut.mockResolvedValue(undefined);});- it("opens organization settings in the native browser sheet", async () => {+ it("shows the Free plan limit without an external purchase action", async () => {const renderer = await renderComponent(React.createElement(AccountScreen));const text = getTextNodes(renderer.toJSON());- const [organizationSettings] = renderer.root.findAllByProps({- accessibilityLabel: "Organization Settings",+ const [freePlan] = renderer.root.findAllByProps({+ accessibilityLabel: "Cap plan: Free",});- if (!organizationSettings) {- throw new Error("Organization Settings row was not rendered");- }-- expect(text).toContain("Account");- expect(text).toContain("Organization Settings");- expect(organizationSettings.props.accessibilityHint).toBe(- "Opens organization settings in a browser sheet",- );- const WebBrowser = await import("expo-web-browser");- const openBrowserAsync = vi.mocked(WebBrowser.openBrowserAsync);- const openDeferred =- createDeferred<Awaited<ReturnType<typeof WebBrowser.openBrowserAsync>>>();- openBrowserAsync.mockClear();- openBrowserAsync.mockReturnValueOnce(openDeferred.promise);-- await act(async () => {- organizationSettings.props.onPress();- await Promise.resolve();+ expect(freePlan).toBeDefined();+ expect(text).toContain("Free plan");+ expect(text).toContain("Free plan · Recordings are limited to 5 minutes");+ expect(+ renderer.root.findAllByProps({+ accessibilityLabel: "Upgrade to Cap Pro",+ }),+ ).toHaveLength(0);+ expect(billing.getProPlan).toHaveBeenCalledWith({+ apiKey: "mobile-key",+ baseUrl: "https://cap.so",});+ });- expect(openBrowserAsync).toHaveBeenCalledWith(- "https://cap.so/dashboard/settings/organization",- );- const [openingOrganizationSettings] = renderer.root.findAllByProps({- accessibilityLabel: "Organization Settings",+ it("shows existing Cap Pro access without a purchase action", async () => {+ billing.getProPlan.mockResolvedValueOnce({+ upgraded: true,+ stripeSubscriptionStatus: "active",});- expect(openingOrganizationSettings?.props.accessibilityValue).toEqual({- text: "Opening organization settings",+ const renderer = await renderComponent(React.createElement(AccountScreen));+ const text = getTextNodes(renderer.toJSON());++ expect(+ renderer.root.findAllByProps({ accessibilityLabel: "Cap plan: Cap Pro" }),+ ).not.toHaveLength(0);+ expect(text).toContain("Cap Pro");+ expect(text).toContain("Unlimited recording time");+ });++ it("offers plan retry without guessing a Free or Pro state", async () => {+ billing.getProPlan.mockRejectedValueOnce(new Error("offline"));+ const renderer = await renderComponent(React.createElement(AccountScreen));+ const [unavailable] = renderer.root.findAllByProps({+ accessibilityLabel: "Cap plan unavailable",});+ expect(unavailable).toBeDefined();+ expect(getTextNodes(renderer.toJSON())).toContain("Tap to try again");await act(async () => {- openDeferred.resolve({- type: "dismiss",- } as Awaited<ReturnType<typeof WebBrowser.openBrowserAsync>>);- await openDeferred.promise;+ unavailable?.props.onPress();});+ expect(billing.getProPlan).toHaveBeenCalledTimes(2);});- it("marks app settings as opening with a native value", async () => {+ it("opens native profile, organization, and account deletion screens", async () => {+ const renderer = await renderComponent(React.createElement(AccountScreen));+ const routes = [+ ["Name and Profile Image", "/profile-settings"],+ ["Organization Settings", "/organization-settings"],+ ["Delete account", "/delete-account"],+ ] as const;++ for (const [label, route] of routes) {+ const [row] = renderer.root.findAllByProps({+ accessibilityLabel: label,+ });+ if (!row) throw new Error(`${label} row was not rendered`);+ await act(async () => {+ row.props.onPress();+ });+ expect(router.push).toHaveBeenLastCalledWith(route);+ }+ });++ it("opens help, privacy, and terms from the signed-in account", async () => {+ const renderer = await renderComponent(React.createElement(AccountScreen));+ const pages = [+ ["Help & Support", "https://cap.so/docs"],+ ["Privacy Policy", "https://cap.so/privacy"],+ ["Terms of Service", "https://cap.so/terms"],+ ] as const;++ for (const [label, url] of pages) {+ const [row] = renderer.root.findAllByProps({+ accessibilityLabel: label,+ });+ if (!row) throw new Error(`${label} row was not rendered`);+ await act(async () => {+ row.props.onPress();+ });+ expect(linking.openURL).toHaveBeenLastCalledWith(url);+ }+ });++ it("marks app settings as busy while the native view opens", async () => {const renderer = await renderComponent(React.createElement(AccountScreen));const [appSettings] = renderer.root.findAllByProps({accessibilityLabel: "App Settings",@@ -243,7 +310,6 @@ describe("AccountScreen", () => {const { Linking } = await import("react-native");const openSettings = vi.mocked(Linking.openSettings);const openDeferred = createDeferred<void>();- openSettings.mockClear();openSettings.mockReturnValueOnce(openDeferred.promise);await act(async () => {@@ -264,7 +330,7 @@ describe("AccountScreen", () => {});});- it("locks account settings rows while refresh is in progress", async () => {+ it("locks account actions while refresh is in progress", async () => {const refreshDeferred = createDeferred<void>();auth.value.refresh.mockReturnValueOnce(refreshDeferred.promise);const renderer = await renderComponent(React.createElement(AccountScreen));@@ -278,45 +344,16 @@ describe("AccountScreen", () => {await Promise.resolve();});- const [loadingRefreshRow] = renderer.root.findAllByProps({- accessibilityLabel: "Refresh",- });- const [organizationSettings] = renderer.root.findAllByProps({- accessibilityLabel: "Organization Settings",- });- const [appSettings] = renderer.root.findAllByProps({- accessibilityLabel: "App Settings",- });- const [signOut] = renderer.root.findAllByProps({- accessibilityLabel: "Sign out",- });- if (- !loadingRefreshRow ||- !organizationSettings ||- !appSettings ||- !signOut- ) {- throw new Error("Account action rows were not rendered");- }-- expect(loadingRefreshRow.props.accessibilityState).toEqual({- busy: true,- disabled: true,- });- expect(loadingRefreshRow.props.accessibilityHint).toBe(- "Refresh is in progress",- );- expect(loadingRefreshRow.props.accessibilityValue).toEqual({- text: "Refreshing account data",- });- expect(getTextNodes(renderer.toJSON())).toContain("Refreshing...");- for (const row of [organizationSettings, appSettings, signOut]) {- expect(row.props.disabled).toBe(true);- expect(row.props.accessibilityState).toEqual({- busy: false,- disabled: true,+ for (const label of [+ "Organization Settings",+ "App Settings",+ "Sign out",+ "Delete account",+ ]) {+ const [row] = renderer.root.findAllByProps({+ accessibilityLabel: label,});- expect(row.props.accessibilityHint).toBe("Refresh is in progress");+ expect(row?.props.disabled).toBe(true);}await act(async () => {@@ -334,17 +371,11 @@ describe("AccountScreen", () => {});if (!signOut) throw new Error("Sign out row was not rendered");- const { ActionSheetIOS } = await import("react-native");- const showActionSheetWithOptions = vi.mocked(- ActionSheetIOS.showActionSheetWithOptions,- );- showActionSheetWithOptions.mockClear();-await act(async () => {signOut.props.onPress();});-- const [, callback] = showActionSheetWithOptions.mock.calls[0] ?? [];+ const callback = actionSheet.showActionSheetWithOptions.mock+ .calls[0]?.[1] as ((index: number) => void) | undefined;if (!callback)throw new Error("Sign-out confirmation callback was not set");@@ -352,21 +383,13 @@ describe("AccountScreen", () => {callback(0);await Promise.resolve();});-const [loadingSignOut] = renderer.root.findAllByProps({accessibilityLabel: "Sign out",});- if (!loadingSignOut) throw new Error("Sign out row was not rendered");- expect(loadingSignOut.props.accessibilityState).toEqual({+ expect(loadingSignOut?.props.accessibilityState).toEqual({busy: true,disabled: true,});- expect(loadingSignOut.props.accessibilityHint).toBe(- "Sign out is in progress",- );- expect(loadingSignOut.props.accessibilityValue).toEqual({- text: "Signing out of Cap",- });expect(getTextNodes(renderer.toJSON())).toContain("Signing out...");await act(async () => {