Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(mobile): add analytics and account settings screens

Richie McIlroyd29a42dfe313
diff --git a/apps/mobile/app/analytics.tsx b/apps/mobile/app/analytics.tsx
new file mode 100644
index 000000000..12bd15453
--- /dev/null
+++ b/apps/mobile/app/analytics.tsx
@@ -0,0 +1,508 @@
+import { Stack, useLocalSearchParams } from "expo-router";
+import { SymbolView } from "expo-symbols";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { Pressable, StyleSheet, Text, View } from "react-native";
+import Svg, { Path } from "react-native-svg";
+import type { MobileAnalyticsData, MobileAnalyticsRange } from "@/api/mobile";
+import { MobileApiError } from "@/api/mobile";
+import { useAuth } from "@/auth/AuthContext";
+import { SignInPanel } from "@/auth/SignInPanel";
+import { ActionButton } from "@/components/ActionButton";
+import { CapLoadingIndicator } from "@/components/CapLoadingIndicator";
+import { GlassSurface } from "@/components/GlassSurface";
+import { Screen } from "@/components/Screen";
+import { colors, fonts, radius, squircle } from "@/theme";
+
+type AnalyticsPoint = MobileAnalyticsData["chart"][number];
+
+const ranges: Array<{ label: string; value: MobileAnalyticsRange }> = [
+ { label: "24H", value: "24h" },
+ { label: "7D", value: "7d" },
+ { label: "30D", value: "30d" },
+ { label: "All", value: "lifetime" },
+];
+
+const numberFormatter = new Intl.NumberFormat();
+
+export const downsampleAnalyticsChart = (
+ points: readonly AnalyticsPoint[],
+ limit = 48,
+) => {
+ if (points.length <= limit) return [...points];
+ const groupSize = Math.ceil(points.length / limit);
+ const sampled: AnalyticsPoint[] = [];
+ for (let index = 0; index < points.length; index += groupSize) {
+ const group = points.slice(index, index + groupSize);
+ const last = group.at(-1);
+ if (!last) continue;
+ sampled.push({
+ bucket: last.bucket,
+ caps: group.reduce((total, point) => total + point.caps, 0),
+ views: group.reduce((total, point) => total + point.views, 0),
+ comments: group.reduce((total, point) => total + point.comments, 0),
+ reactions: group.reduce((total, point) => total + point.reactions, 0),
+ });
+ }
+ return sampled;
+};
+
+const chartPath = (points: readonly AnalyticsPoint[]) => {
+ if (points.length === 0) return "";
+ const width = 320;
+ const height = 112;
+ const max = Math.max(...points.map((point) => point.views), 1);
+ return points
+ .map((point, index) => {
+ const x =
+ points.length === 1 ? width / 2 : (index / (points.length - 1)) * width;
+ const y = height - (point.views / max) * (height - 8) - 4;
+ return `${index === 0 ? "M" : "L"}${x.toFixed(2)} ${y.toFixed(2)}`;
+ })
+ .join(" ");
+};
+
+const errorMessage = (error: unknown) => {
+ if (error instanceof MobileApiError && error.status === 401) {
+ return "Your session expired. Sign in again.";
+ }
+ return "Analytics could not load. Check your connection and try again.";
+};
+
+function MetricCard({
+ label,
+ value,
+ symbol,
+}: {
+ label: string;
+ value: number;
+ symbol: "eye" | "text.bubble" | "face.smiling" | "video";
+}) {
+ return (
+ <GlassSurface
+ fallbackStyle={styles.cardFallback}
+ style={styles.metricCard}
+ tintColor={colors.gray1}
+ >
+ <View style={styles.metricLabelRow}>
+ <SymbolView name={symbol} size={15} tintColor={colors.gray9} />
+ <Text style={styles.metricLabel}>{label}</Text>
+ </View>
+ <Text style={styles.metricValue}>{numberFormatter.format(value)}</Text>
+ </GlassSurface>
+ );
+}
+
+function Breakdown({
+ label,
+ rows,
+}: {
+ label: string;
+ rows: MobileAnalyticsData["breakdowns"]["countries"];
+}) {
+ if (rows.length === 0) return null;
+ return (
+ <View style={styles.breakdownSection}>
+ <Text style={styles.sectionTitle}>{label}</Text>
+ <GlassSurface
+ fallbackStyle={styles.cardFallback}
+ style={styles.breakdownCard}
+ tintColor={colors.gray1}
+ >
+ {rows.slice(0, 5).map((row, index) => (
+ <View
+ key={`${row.name}-${index}`}
+ style={[styles.breakdownRow, index > 0 && styles.divider]}
+ >
+ <View style={styles.breakdownText}>
+ <Text numberOfLines={1} style={styles.breakdownName}>
+ {row.name || "Unknown"}
+ </Text>
+ {row.subtitle ? (
+ <Text numberOfLines={1} style={styles.breakdownSubtitle}>
+ {row.subtitle}
+ </Text>
+ ) : null}
+ </View>
+ <Text style={styles.breakdownValue}>
+ {numberFormatter.format(row.views)} · {Math.round(row.percentage)}
+ %
+ </Text>
+ </View>
+ ))}
+ </GlassSurface>
+ </View>
+ );
+}
+
+export default function AnalyticsScreen() {
+ const auth = useAuth();
+ const params = useLocalSearchParams<{ capId?: string | string[] }>();
+ const capId = Array.isArray(params.capId) ? params.capId[0] : params.capId;
+ const [range, setRange] = useState<MobileAnalyticsRange>("7d");
+ const [data, setData] = useState<MobileAnalyticsData | null>(null);
+ const [available, setAvailable] = useState(true);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const requestRef = useRef(0);
+
+ const load = useCallback(() => {
+ if (auth.status !== "signedIn" || !capId) {
+ setLoading(false);
+ return;
+ }
+ const requestId = ++requestRef.current;
+ setLoading(true);
+ setError(null);
+ auth.client
+ .getCapAnalytics(capId, range)
+ .then((response) => {
+ if (requestRef.current !== requestId) return;
+ setAvailable(response.available);
+ setData(response.data);
+ })
+ .catch((cause: unknown) => {
+ if (requestRef.current !== requestId) return;
+ setError(errorMessage(cause));
+ })
+ .finally(() => {
+ if (requestRef.current === requestId) setLoading(false);
+ });
+ }, [auth.client, auth.status, capId, range]);
+
+ useEffect(() => {
+ load();
+ return () => {
+ requestRef.current += 1;
+ };
+ }, [load]);
+
+ const points = useMemo(
+ () => downsampleAnalyticsChart(data?.chart ?? []),
+ [data?.chart],
+ );
+ const path = useMemo(() => chartPath(points), [points]);
+
+ if (auth.status === "signedOut") {
+ return (
+ <Screen scroll safeEdges={["left", "right", "bottom"]}>
+ <SignInPanel title="Sign in to view analytics" />
+ </Screen>
+ );
+ }
+
+ return (
+ <>
+ <Stack.Screen
+ options={{
+ headerShown: true,
+ title: "Analytics",
+ headerBackTitle: "Back",
+ headerShadowVisible: false,
+ headerStyle: { backgroundColor: colors.appBackground },
+ }}
+ />
+ <Screen scroll safeEdges={["left", "right", "bottom"]}>
+ <View style={styles.heading}>
+ <Text numberOfLines={2} style={styles.title}>
+ {data?.capName ?? "Cap analytics"}
+ </Text>
+ <Text style={styles.subtitle}>
+ Views and engagement for this Cap.
+ </Text>
+ </View>
+ <View accessibilityRole="tablist" style={styles.rangeSelector}>
+ {ranges.map((item) => {
+ const selected = item.value === range;
+ return (
+ <Pressable
+ accessibilityRole="tab"
+ accessibilityState={{ selected }}
+ disabled={loading}
+ key={item.value}
+ onPress={() => setRange(item.value)}
+ style={({ pressed }) => [
+ styles.rangeButton,
+ selected && styles.rangeButtonSelected,
+ pressed && styles.rangeButtonPressed,
+ ]}
+ >
+ <Text
+ style={[
+ styles.rangeLabel,
+ selected && styles.rangeLabelSelected,
+ ]}
+ >
+ {item.label}
+ </Text>
+ </Pressable>
+ );
+ })}
+ </View>
+ {loading ? (
+ <View style={styles.state}>
+ <CapLoadingIndicator />
+ <Text style={styles.stateText}>Loading analytics…</Text>
+ </View>
+ ) : error || !capId ? (
+ <View style={styles.state}>
+ <SymbolView
+ name="exclamationmark.triangle"
+ size={30}
+ tintColor={colors.red9}
+ />
+ <Text style={styles.stateTitle}>Analytics unavailable</Text>
+ <Text style={styles.stateText}>
+ {error ?? "This Cap could not be identified."}
+ </Text>
+ {capId ? (
+ <ActionButton
+ label="Try again"
+ onPress={load}
+ variant="secondary"
+ />
+ ) : null}
+ </View>
+ ) : !available ? (
+ <View style={styles.state}>
+ <SymbolView name="chart.bar" size={32} tintColor={colors.blue9} />
+ <Text style={styles.stateTitle}>Analytics is a Pro feature</Text>
+ <Text style={styles.stateText}>
+ Your current plan does not include analytics.
+ </Text>
+ </View>
+ ) : data ? (
+ <>
+ <View style={styles.metrics}>
+ <MetricCard
+ label="Views"
+ symbol="eye"
+ value={data.counts.views}
+ />
+ <MetricCard
+ label="Comments"
+ symbol="text.bubble"
+ value={data.counts.comments}
+ />
+ <MetricCard
+ label="Reactions"
+ symbol="face.smiling"
+ value={data.counts.reactions}
+ />
+ <MetricCard
+ label="Caps"
+ symbol="video"
+ value={data.counts.caps}
+ />
+ </View>
+ <View style={styles.chartSection}>
+ <Text style={styles.sectionTitle}>Views over time</Text>
+ <GlassSurface
+ fallbackStyle={styles.cardFallback}
+ style={styles.chartCard}
+ tintColor={colors.gray1}
+ >
+ {data.counts.views === 0 ? (
+ <View style={styles.emptyChart}>
+ <Text style={styles.stateText}>
+ No views in this range yet.
+ </Text>
+ </View>
+ ) : (
+ <Svg
+ accessibilityLabel="Views trend chart"
+ height={120}
+ viewBox="0 0 320 120"
+ width="100%"
+ >
+ <Path
+ d={path}
+ fill="none"
+ stroke={colors.blue9}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={3}
+ />
+ </Svg>
+ )}
+ </GlassSurface>
+ </View>
+ <Breakdown label="Countries" rows={data.breakdowns.countries} />
+ <Breakdown label="Cities" rows={data.breakdowns.cities} />
+ <Breakdown label="Devices" rows={data.breakdowns.devices} />
+ <Breakdown label="Browsers" rows={data.breakdowns.browsers} />
+ <Breakdown
+ label="Operating systems"
+ rows={data.breakdowns.operatingSystems}
+ />
+ </>
+ ) : null}
+ </Screen>
+ </>
+ );
+}
+
+const styles = StyleSheet.create({
+ heading: {
+ paddingTop: 10,
+ paddingBottom: 20,
+ gap: 4,
+ },
+ title: {
+ fontFamily: fonts.medium,
+ fontSize: 24,
+ lineHeight: 30,
+ color: colors.gray12,
+ },
+ subtitle: {
+ fontFamily: fonts.regular,
+ fontSize: 14,
+ lineHeight: 20,
+ color: colors.gray10,
+ },
+ rangeSelector: {
+ flexDirection: "row",
+ padding: 3,
+ borderRadius: radius.md,
+ backgroundColor: colors.gray3,
+ marginBottom: 20,
+ ...squircle,
+ },
+ rangeButton: {
+ flex: 1,
+ alignItems: "center",
+ paddingVertical: 8,
+ borderRadius: radius.sm,
+ ...squircle,
+ },
+ rangeButtonSelected: {
+ backgroundColor: colors.white,
+ },
+ rangeButtonPressed: {
+ opacity: 0.7,
+ },
+ rangeLabel: {
+ fontFamily: fonts.medium,
+ fontSize: 13,
+ color: colors.gray10,
+ },
+ rangeLabelSelected: {
+ color: colors.gray12,
+ },
+ state: {
+ minHeight: 300,
+ alignItems: "center",
+ justifyContent: "center",
+ gap: 12,
+ paddingHorizontal: 24,
+ },
+ stateTitle: {
+ fontFamily: fonts.medium,
+ fontSize: 18,
+ color: colors.gray12,
+ textAlign: "center",
+ },
+ stateText: {
+ fontFamily: fonts.regular,
+ fontSize: 14,
+ lineHeight: 20,
+ color: colors.gray10,
+ textAlign: "center",
+ },
+ metrics: {
+ flexDirection: "row",
+ flexWrap: "wrap",
+ gap: 10,
+ },
+ metricCard: {
+ width: "48%",
+ flexGrow: 1,
+ padding: 14,
+ borderRadius: radius.md,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: colors.gray4,
+ gap: 8,
+ ...squircle,
+ },
+ cardFallback: {
+ backgroundColor: colors.gray1,
+ },
+ metricLabelRow: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 6,
+ },
+ metricLabel: {
+ fontFamily: fonts.regular,
+ fontSize: 13,
+ color: colors.gray10,
+ },
+ metricValue: {
+ fontFamily: fonts.medium,
+ fontSize: 24,
+ color: colors.gray12,
+ },
+ chartSection: {
+ marginTop: 24,
+ gap: 8,
+ },
+ sectionTitle: {
+ fontFamily: fonts.medium,
+ fontSize: 14,
+ color: colors.gray11,
+ paddingHorizontal: 4,
+ },
+ chartCard: {
+ borderRadius: radius.md,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: colors.gray4,
+ padding: 14,
+ ...squircle,
+ },
+ emptyChart: {
+ height: 120,
+ alignItems: "center",
+ justifyContent: "center",
+ },
+ breakdownSection: {
+ marginTop: 24,
+ gap: 8,
+ },
+ breakdownCard: {
+ borderRadius: radius.md,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: colors.gray4,
+ overflow: "hidden",
+ ...squircle,
+ },
+ breakdownRow: {
+ minHeight: 56,
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 12,
+ paddingHorizontal: 14,
+ },
+ divider: {
+ borderTopWidth: StyleSheet.hairlineWidth,
+ borderTopColor: colors.gray4,
+ },
+ breakdownText: {
+ flex: 1,
+ minWidth: 0,
+ },
+ breakdownName: {
+ fontFamily: fonts.medium,
+ fontSize: 15,
+ color: colors.gray12,
+ },
+ breakdownSubtitle: {
+ fontFamily: fonts.regular,
+ fontSize: 12,
+ color: colors.gray9,
+ marginTop: 2,
+ },
+ breakdownValue: {
+ fontFamily: fonts.regular,
+ fontSize: 13,
+ color: colors.gray10,
+ },
+});
diff --git a/apps/mobile/app/delete-account.tsx b/apps/mobile/app/delete-account.tsx
new file mode 100644
index 000000000..2e6f73ee5
--- /dev/null
+++ b/apps/mobile/app/delete-account.tsx
@@ -0,0 +1,264 @@
+import { router, Stack } from "expo-router";
+import { useState } from "react";
+import {
+ ActionSheetIOS,
+ Alert,
+ Platform,
+ StyleSheet,
+ Text,
+ TextInput,
+ View,
+} from "react-native";
+import { MobileApiError } from "@/api/mobile";
+import { useAuth } from "@/auth/AuthContext";
+import { SignInPanel } from "@/auth/SignInPanel";
+import { ActionButton } from "@/components/ActionButton";
+import { GlassSurface } from "@/components/GlassSurface";
+import { Screen } from "@/components/Screen";
+import { colors, fonts, radius, squircle } from "@/theme";
+
+const deletionErrorMessage = (error: unknown) => {
+ if (error instanceof MobileApiError && error.status === 401) {
+ return "Your session expired. Sign in again before requesting deletion.";
+ }
+ return "Your deletion request could not be submitted. Check your connection and try again.";
+};
+
+export default function DeleteAccountScreen() {
+ const auth = useAuth();
+ const [confirmation, setConfirmation] = useState("");
+ const [submitting, setSubmitting] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const confirmed = confirmation.trim() === "DELETE";
+
+ const submit = async () => {
+ if (!confirmed || submitting) return;
+ setSubmitting(true);
+ setError(null);
+ try {
+ await auth.client.requestAccountDeletion();
+ await auth.signOut();
+ router.replace("/(tabs)/account");
+ Alert.alert(
+ "Deletion request received",
+ "We will permanently delete your account and associated data within 30 days and email you when it is complete.",
+ );
+ } catch (cause) {
+ setError(deletionErrorMessage(cause));
+ setSubmitting(false);
+ }
+ };
+
+ const confirmDeletion = () => {
+ if (!confirmed || submitting) return;
+
+ if (Platform.OS === "ios") {
+ ActionSheetIOS.showActionSheetWithOptions(
+ {
+ cancelButtonIndex: 1,
+ destructiveButtonIndex: 0,
+ message:
+ "This starts permanent deletion of your Cap account and associated data. This cannot be undone.",
+ options: ["Request permanent deletion", "Cancel"],
+ title: "Delete your Cap account?",
+ tintColor: colors.blue11,
+ userInterfaceStyle: "light",
+ },
+ (index) => {
+ if (index === 0) void submit();
+ },
+ );
+ return;
+ }
+
+ Alert.alert(
+ "Delete your Cap account?",
+ "This starts permanent deletion of your Cap account and associated data. This cannot be undone.",
+ [
+ { text: "Cancel", style: "cancel" },
+ {
+ text: "Request permanent deletion",
+ style: "destructive",
+ onPress: () => void submit(),
+ },
+ ],
+ );
+ };
+
+ if (auth.status === "signedOut") {
+ return (
+ <Screen scroll safeEdges={["left", "right", "bottom"]}>
+ <SignInPanel title="Sign in to manage your account" />
+ </Screen>
+ );
+ }
+
+ return (
+ <>
+ <Stack.Screen
+ options={{
+ headerShown: true,
+ title: "Delete Account",
+ headerBackTitle: "Back",
+ headerShadowVisible: false,
+ headerStyle: { backgroundColor: colors.appBackground },
+ }}
+ />
+ <Screen
+ automaticallyAdjustKeyboardInsets
+ scroll
+ safeEdges={["left", "right", "bottom"]}
+ >
+ <View style={styles.heading}>
+ <Text style={styles.title}>Permanently delete your account</Text>
+ <Text style={styles.subtitle}>
+ Your request begins immediately and cannot be undone after
+ processing.
+ </Text>
+ </View>
+ <GlassSurface
+ fallbackStyle={styles.cardFallback}
+ style={styles.card}
+ tintColor={colors.gray1}
+ >
+ <Text style={styles.cardTitle}>What will be deleted</Text>
+ <View style={styles.list}>
+ <Text style={styles.listItem}>
+ • Your Cap account, profile, and personal data
+ </Text>
+ <Text style={styles.listItem}>
+ • Caps, videos, comments, and other content associated with your
+ account
+ </Text>
+ <Text style={styles.listItem}>
+ • Organizations you solely own and your access to shared
+ organizations
+ </Text>
+ </View>
+ <Text style={styles.detail}>
+ You will be signed out immediately and cannot sign in while we
+ process deletion. Within 30 days, we cancel any direct Cap
+ subscription and email you when deletion is complete.
+ </Text>
+ </GlassSurface>
+ <View style={styles.field}>
+ <Text style={styles.label}>
+ Type <Text style={styles.confirmationWord}>DELETE</Text> to confirm
+ </Text>
+ <TextInput
+ accessibilityLabel="Deletion confirmation"
+ autoCapitalize="characters"
+ autoCorrect={false}
+ editable={!submitting}
+ onChangeText={setConfirmation}
+ placeholder="DELETE"
+ placeholderTextColor={colors.gray9}
+ returnKeyType="done"
+ style={styles.input}
+ value={confirmation}
+ />
+ </View>
+ {error ? (
+ <Text accessibilityLiveRegion="polite" style={styles.error}>
+ {error}
+ </Text>
+ ) : null}
+ <ActionButton
+ accessibilityHint="Starts permanent account deletion"
+ disabled={!confirmed}
+ label="Request account deletion"
+ loading={submitting}
+ onPress={confirmDeletion}
+ size="lg"
+ symbol="trash"
+ variant="danger"
+ />
+ </Screen>
+ </>
+ );
+}
+
+const styles = StyleSheet.create({
+ heading: {
+ gap: 6,
+ marginBottom: 20,
+ },
+ title: {
+ color: colors.gray12,
+ fontFamily: fonts.bold,
+ fontSize: 24,
+ lineHeight: 30,
+ },
+ subtitle: {
+ color: colors.gray11,
+ fontFamily: fonts.regular,
+ fontSize: 15,
+ lineHeight: 21,
+ },
+ card: {
+ borderColor: colors.red6,
+ borderRadius: radius.md,
+ borderWidth: StyleSheet.hairlineWidth,
+ gap: 14,
+ padding: 16,
+ ...squircle,
+ },
+ cardFallback: {
+ backgroundColor: colors.red2,
+ },
+ cardTitle: {
+ color: colors.red12,
+ fontFamily: fonts.bold,
+ fontSize: 17,
+ lineHeight: 22,
+ },
+ list: {
+ gap: 8,
+ },
+ listItem: {
+ color: colors.gray12,
+ fontFamily: fonts.regular,
+ fontSize: 15,
+ lineHeight: 21,
+ },
+ detail: {
+ color: colors.gray11,
+ fontFamily: fonts.regular,
+ fontSize: 14,
+ lineHeight: 20,
+ },
+ field: {
+ gap: 8,
+ marginTop: 22,
+ marginBottom: 16,
+ },
+ label: {
+ color: colors.gray12,
+ fontFamily: fonts.medium,
+ fontSize: 14,
+ lineHeight: 19,
+ },
+ confirmationWord: {
+ color: colors.red11,
+ fontFamily: fonts.bold,
+ },
+ input: {
+ backgroundColor: colors.white,
+ borderColor: colors.gray7,
+ borderRadius: radius.sm,
+ borderWidth: StyleSheet.hairlineWidth,
+ color: colors.gray12,
+ fontFamily: fonts.medium,
+ fontSize: 16,
+ minHeight: 48,
+ paddingHorizontal: 14,
+ ...squircle,
+ },
+ error: {
+ color: colors.red11,
+ fontFamily: fonts.regular,
+ fontSize: 14,
+ lineHeight: 20,
+ marginBottom: 12,
+ },
+});
diff --git a/apps/mobile/app/organization-settings.tsx b/apps/mobile/app/organization-settings.tsx
new file mode 100644
index 000000000..bb960ee2c
--- /dev/null
+++ b/apps/mobile/app/organization-settings.tsx
@@ -0,0 +1,619 @@
+import { Image } from "expo-image";
+import * as ImagePicker from "expo-image-picker";
+import { Stack } from "expo-router";
+import { SymbolView } from "expo-symbols";
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ ActionSheetIOS,
+ ActivityIndicator,
+ Alert,
+ Linking,
+ Platform,
+ Pressable,
+ StyleSheet,
+ Text,
+ TextInput,
+ View,
+} from "react-native";
+import type { MobileOrganizationSettings } from "@/api/mobile";
+import { MobileApiError } from "@/api/mobile";
+import { useAuth } from "@/auth/AuthContext";
+import { SignInPanel } from "@/auth/SignInPanel";
+import { ActionButton } from "@/components/ActionButton";
+import { CapLoadingIndicator } from "@/components/CapLoadingIndicator";
+import { GlassSurface } from "@/components/GlassSurface";
+import { Screen } from "@/components/Screen";
+import { colors, fonts, radius, squircle } from "@/theme";
+
+const maxIconBytes = 1024 * 1024;
+
+const settingsErrorMessage = (error: unknown) => {
+ if (error instanceof MobileApiError && error.status === 403) {
+ return "Only organization owners and admins can make this change.";
+ }
+ return "Organization settings could not be updated. Try again.";
+};
+
+const openPhotoSettings = () => {
+ if (Platform.OS === "ios") {
+ ActionSheetIOS.showActionSheetWithOptions(
+ {
+ cancelButtonIndex: 1,
+ message: "Allow Cap to choose an organization icon from Settings.",
+ options: ["Open Settings", "Cancel"],
+ title: "Photos access needed",
+ tintColor: colors.blue11,
+ userInterfaceStyle: "light",
+ },
+ (index) => {
+ if (index === 0) void Linking.openSettings();
+ },
+ );
+ return;
+ }
+ Alert.alert(
+ "Photos access needed",
+ "Allow Cap to choose an organization icon from Settings.",
+ [
+ { text: "Cancel", style: "cancel" },
+ { text: "Open Settings", onPress: () => void Linking.openSettings() },
+ ],
+ );
+};
+
+export default function OrganizationSettingsScreen() {
+ const auth = useAuth();
+ const [settings, setSettings] = useState<MobileOrganizationSettings | null>(
+ null,
+ );
+ const [name, setName] = useState("");
+ const [allowedEmailDomain, setAllowedEmailDomain] = useState("");
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [iconBusy, setIconBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const requestRef = useRef(0);
+
+ const load = useCallback(() => {
+ if (auth.status !== "signedIn") {
+ setLoading(false);
+ return;
+ }
+ const requestId = ++requestRef.current;
+ setLoading(true);
+ setError(null);
+ auth.client
+ .getOrganizationSettings()
+ .then((response) => {
+ if (requestRef.current !== requestId) return;
+ setSettings(response);
+ setName(response.name);
+ setAllowedEmailDomain(response.allowedEmailDomain ?? "");
+ })
+ .catch((cause: unknown) => {
+ if (requestRef.current === requestId) {
+ setError(settingsErrorMessage(cause));
+ }
+ })
+ .finally(() => {
+ if (requestRef.current === requestId) setLoading(false);
+ });
+ }, [auth.client, auth.status]);
+
+ useEffect(() => {
+ load();
+ return () => {
+ requestRef.current += 1;
+ };
+ }, [load]);
+
+ const dirty =
+ settings !== null &&
+ (name.trim() !== settings.name ||
+ allowedEmailDomain.trim() !== (settings.allowedEmailDomain ?? ""));
+ const busy = saving || iconBusy;
+
+ const save = async () => {
+ if (!settings?.canManage || saving || !name.trim()) return;
+ setSaving(true);
+ setError(null);
+ try {
+ const response = await auth.client.updateOrganizationSettings({
+ name: name.trim(),
+ allowedEmailDomain: allowedEmailDomain.trim() || null,
+ });
+ setSettings(response);
+ setName(response.name);
+ setAllowedEmailDomain(response.allowedEmailDomain ?? "");
+ void auth.refresh().catch(() => undefined);
+ } catch (cause) {
+ setError(settingsErrorMessage(cause));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const chooseIcon = async () => {
+ if (!settings?.canManage || busy) return;
+ let result: ImagePicker.ImagePickerResult;
+ try {
+ const permission =
+ await ImagePicker.requestMediaLibraryPermissionsAsync();
+ if (!permission.granted) {
+ openPhotoSettings();
+ return;
+ }
+ result = await ImagePicker.launchImageLibraryAsync({
+ allowsEditing: true,
+ aspect: [1, 1],
+ base64: true,
+ mediaTypes: ["images"],
+ quality: 0.8,
+ });
+ } catch {
+ setError("Photos could not be opened. Check access and try again.");
+ return;
+ }
+ if (result.canceled) return;
+ const asset = result.assets[0];
+ if (!asset?.base64) {
+ setError("The selected image could not be read. Choose another image.");
+ return;
+ }
+ const contentType = asset.mimeType?.toLowerCase() ?? "image/jpeg";
+ if (contentType !== "image/jpeg" && contentType !== "image/png") {
+ setError("Choose a PNG or JPEG image.");
+ return;
+ }
+ const expectedExtensions =
+ contentType === "image/png" ? ["png"] : ["jpg", "jpeg"];
+ const sourceFileName = asset.fileName?.split(/[\\/]/).at(-1);
+ const sourceExtension = sourceFileName?.split(".").at(-1)?.toLowerCase();
+ const fileName =
+ sourceFileName &&
+ sourceExtension &&
+ expectedExtensions.includes(sourceExtension)
+ ? sourceFileName
+ : `organization-${Date.now()}.${expectedExtensions[0]}`;
+ if (
+ (asset.fileSize && asset.fileSize > maxIconBytes) ||
+ asset.base64.length > Math.ceil((maxIconBytes * 4) / 3) + 4
+ ) {
+ setError("Choose a PNG or JPEG that is 1 MB or smaller.");
+ return;
+ }
+
+ setIconBusy(true);
+ setError(null);
+ try {
+ const response = await auth.client.updateOrganizationIcon({
+ data: asset.base64,
+ contentType,
+ fileName,
+ });
+ setSettings(response);
+ void auth.refresh().catch(() => undefined);
+ } catch (cause) {
+ setError(settingsErrorMessage(cause));
+ } finally {
+ setIconBusy(false);
+ }
+ };
+
+ const removeIcon = async () => {
+ if (!settings?.canManage || !settings.iconUrl || busy) return;
+ setIconBusy(true);
+ setError(null);
+ try {
+ const response = await auth.client.removeOrganizationIcon();
+ setSettings(response);
+ void auth.refresh().catch(() => undefined);
+ } catch (cause) {
+ setError(settingsErrorMessage(cause));
+ } finally {
+ setIconBusy(false);
+ }
+ };
+
+ const showIconActions = () => {
+ if (!settings?.canManage || busy) return;
+ const options = settings.iconUrl
+ ? ["Choose Photo", "Remove Icon", "Cancel"]
+ : ["Choose Photo", "Cancel"];
+ if (Platform.OS === "ios") {
+ ActionSheetIOS.showActionSheetWithOptions(
+ {
+ cancelButtonIndex: options.length - 1,
+ destructiveButtonIndex: settings.iconUrl ? 1 : undefined,
+ options,
+ title: "Organization icon",
+ tintColor: colors.blue11,
+ userInterfaceStyle: "light",
+ },
+ (index) => {
+ if (index === 0) void chooseIcon();
+ if (settings.iconUrl && index === 1) void removeIcon();
+ },
+ );
+ return;
+ }
+ Alert.alert("Organization icon", undefined, [
+ { text: "Choose Photo", onPress: () => void chooseIcon() },
+ ...(settings.iconUrl
+ ? [
+ {
+ text: "Remove Icon",
+ style: "destructive" as const,
+ onPress: () => void removeIcon(),
+ },
+ ]
+ : []),
+ { text: "Cancel", style: "cancel" },
+ ]);
+ };
+
+ if (auth.status === "signedOut") {
+ return (
+ <Screen scroll safeEdges={["left", "right", "bottom"]}>
+ <SignInPanel title="Sign in to manage your organization" />
+ </Screen>
+ );
+ }
+
+ return (
+ <>
+ <Stack.Screen
+ options={{
+ headerShown: true,
+ title: "Organization",
+ headerBackTitle: "Back",
+ headerShadowVisible: false,
+ headerStyle: { backgroundColor: colors.appBackground },
+ }}
+ />
+ <Screen
+ automaticallyAdjustKeyboardInsets
+ scroll
+ safeEdges={["left", "right", "bottom"]}
+ >
+ <View style={styles.heading}>
+ <Text style={styles.title}>Organization settings</Text>
+ <Text style={styles.subtitle}>
+ Manage the identity and link access rules for your active
+ organization.
+ </Text>
+ </View>
+ {loading ? (
+ <View style={styles.state}>
+ <CapLoadingIndicator />
+ <Text style={styles.stateText}>Loading settings…</Text>
+ </View>
+ ) : !settings ? (
+ <View style={styles.state}>
+ <SymbolView
+ name="exclamationmark.triangle"
+ size={30}
+ tintColor={colors.red9}
+ />
+ <Text style={styles.stateTitle}>Settings unavailable</Text>
+ <Text style={styles.stateText}>
+ {error ?? "The active organization could not be loaded."}
+ </Text>
+ <ActionButton
+ label="Try again"
+ onPress={load}
+ variant="secondary"
+ />
+ </View>
+ ) : (
+ <>
+ {!settings.canManage ? (
+ <View style={styles.notice}>
+ <SymbolView name="lock" size={18} tintColor={colors.gray10} />
+ <Text style={styles.noticeText}>
+ You’re a member. Owners and admins can edit these settings.
+ </Text>
+ </View>
+ ) : null}
+ <GlassSurface
+ fallbackStyle={styles.cardFallback}
+ style={styles.card}
+ tintColor={colors.gray1}
+ >
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel="Organization icon"
+ accessibilityHint={
+ settings.canManage ? "Opens icon actions" : undefined
+ }
+ accessibilityState={{
+ busy: iconBusy,
+ disabled: !settings.canManage || busy,
+ }}
+ disabled={!settings.canManage || busy}
+ onPress={showIconActions}
+ style={({ pressed }) => [
+ styles.iconRow,
+ pressed && styles.iconRowPressed,
+ ]}
+ >
+ <View style={styles.iconPreview}>
+ {iconBusy ? (
+ <ActivityIndicator color={colors.blue9} />
+ ) : settings.iconUrl ? (
+ <Image
+ contentFit="cover"
+ source={{ uri: settings.iconUrl }}
+ style={styles.iconImage}
+ />
+ ) : (
+ <Text style={styles.iconInitial}>
+ {settings.name.slice(0, 1).toUpperCase()}
+ </Text>
+ )}
+ </View>
+ <View style={styles.iconCopy}>
+ <Text style={styles.rowTitle}>Organization icon</Text>
+ <Text style={styles.rowSubtitle}>
+ PNG or JPEG, up to 1 MB
+ </Text>
+ </View>
+ {settings.canManage ? (
+ <SymbolView
+ name="chevron.right"
+ size={13}
+ tintColor={colors.gray9}
+ />
+ ) : null}
+ </Pressable>
+ <View style={styles.field}>
+ <Text style={styles.label}>Organization name</Text>
+ <TextInput
+ accessibilityLabel="Organization name"
+ autoCapitalize="words"
+ editable={settings.canManage && !busy}
+ maxLength={255}
+ onChangeText={setName}
+ placeholder="Organization name"
+ placeholderTextColor={colors.gray8}
+ style={styles.input}
+ value={name}
+ />
+ </View>
+ <View style={styles.field}>
+ <Text style={styles.label}>Email access restriction</Text>
+ <Text style={styles.help}>
+ Comma-separated domains or email addresses. Leave blank to
+ allow anyone with the link.
+ </Text>
+ <TextInput
+ accessibilityLabel="Email access restriction"
+ autoCapitalize="none"
+ autoCorrect={false}
+ editable={settings.canManage && !busy}
+ maxLength={255}
+ multiline
+ onChangeText={setAllowedEmailDomain}
+ placeholder="company.com, [email protected]"
+ placeholderTextColor={colors.gray8}
+ style={[styles.input, styles.multilineInput]}
+ value={allowedEmailDomain}
+ />
+ </View>
+ {settings.customDomain ? (
+ <View style={styles.domainRow}>
+ <View style={styles.domainCopy}>
+ <Text style={styles.label}>Custom domain</Text>
+ <Text style={styles.domainValue}>
+ {settings.customDomain}
+ </Text>
+ </View>
+ <Text
+ style={[
+ styles.domainStatus,
+ settings.domainVerified && styles.domainStatusVerified,
+ ]}
+ >
+ {settings.domainVerified ? "Verified" : "Pending"}
+ </Text>
+ </View>
+ ) : null}
+ </GlassSurface>
+ {error ? <Text style={styles.error}>{error}</Text> : null}
+ {settings.canManage ? (
+ <ActionButton
+ disabled={!dirty || !name.trim() || iconBusy}
+ label="Save changes"
+ loading={saving}
+ onPress={() => void save()}
+ style={styles.saveButton}
+ variant="blue"
+ />
+ ) : null}
+ </>
+ )}
+ </Screen>
+ </>
+ );
+}
+
+const styles = StyleSheet.create({
+ heading: {
+ paddingTop: 10,
+ paddingBottom: 20,
+ gap: 4,
+ },
+ title: {
+ fontFamily: fonts.medium,
+ fontSize: 24,
+ lineHeight: 30,
+ color: colors.gray12,
+ },
+ subtitle: {
+ fontFamily: fonts.regular,
+ fontSize: 14,
+ lineHeight: 20,
+ color: colors.gray10,
+ },
+ state: {
+ minHeight: 320,
+ alignItems: "center",
+ justifyContent: "center",
+ gap: 12,
+ paddingHorizontal: 24,
+ },
+ stateTitle: {
+ fontFamily: fonts.medium,
+ fontSize: 18,
+ color: colors.gray12,
+ },
+ stateText: {
+ fontFamily: fonts.regular,
+ fontSize: 14,
+ lineHeight: 20,
+ color: colors.gray10,
+ textAlign: "center",
+ },
+ notice: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 10,
+ padding: 14,
+ borderRadius: radius.md,
+ backgroundColor: colors.gray3,
+ marginBottom: 12,
+ ...squircle,
+ },
+ noticeText: {
+ flex: 1,
+ fontFamily: fonts.regular,
+ fontSize: 14,
+ lineHeight: 20,
+ color: colors.gray11,
+ },
+ card: {
+ borderRadius: radius.lg,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: colors.gray4,
+ padding: 16,
+ gap: 20,
+ ...squircle,
+ },
+ cardFallback: {
+ backgroundColor: colors.gray1,
+ },
+ iconRow: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 12,
+ margin: -4,
+ padding: 4,
+ borderRadius: radius.md,
+ ...squircle,
+ },
+ iconRowPressed: {
+ backgroundColor: colors.gray3,
+ },
+ iconPreview: {
+ width: 58,
+ height: 58,
+ borderRadius: radius.md,
+ alignItems: "center",
+ justifyContent: "center",
+ backgroundColor: colors.blue3,
+ overflow: "hidden",
+ ...squircle,
+ },
+ iconImage: {
+ width: "100%",
+ height: "100%",
+ },
+ iconInitial: {
+ fontFamily: fonts.medium,
+ fontSize: 22,
+ color: colors.blue11,
+ },
+ iconCopy: {
+ flex: 1,
+ },
+ rowTitle: {
+ fontFamily: fonts.medium,
+ fontSize: 16,
+ color: colors.gray12,
+ },
+ rowSubtitle: {
+ fontFamily: fonts.regular,
+ fontSize: 13,
+ color: colors.gray9,
+ marginTop: 2,
+ },
+ field: {
+ gap: 8,
+ },
+ label: {
+ fontFamily: fonts.medium,
+ fontSize: 14,
+ color: colors.gray12,
+ },
+ help: {
+ fontFamily: fonts.regular,
+ fontSize: 13,
+ lineHeight: 18,
+ color: colors.gray10,
+ },
+ input: {
+ minHeight: 46,
+ borderRadius: radius.md,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: colors.gray5,
+ backgroundColor: colors.white,
+ paddingHorizontal: 13,
+ fontFamily: fonts.regular,
+ fontSize: 16,
+ color: colors.gray12,
+ ...squircle,
+ },
+ multilineInput: {
+ minHeight: 92,
+ paddingTop: 12,
+ textAlignVertical: "top",
+ },
+ domainRow: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 12,
+ paddingTop: 4,
+ },
+ domainCopy: {
+ flex: 1,
+ },
+ domainValue: {
+ fontFamily: fonts.regular,
+ fontSize: 14,
+ color: colors.gray10,
+ marginTop: 3,
+ },
+ domainStatus: {
+ fontFamily: fonts.medium,
+ fontSize: 12,
+ color: colors.gray11,
+ backgroundColor: colors.gray3,
+ borderRadius: radius.full,
+ paddingHorizontal: 10,
+ paddingVertical: 5,
+ },
+ domainStatusVerified: {
+ color: colors.green9,
+ },
+ error: {
+ fontFamily: fonts.regular,
+ fontSize: 14,
+ lineHeight: 20,
+ color: colors.red10,
+ textAlign: "center",
+ marginTop: 12,
+ },
+ saveButton: {
+ marginTop: 16,
+ },
+});
diff --git a/apps/mobile/app/profile-settings.tsx b/apps/mobile/app/profile-settings.tsx
new file mode 100644
index 000000000..d6ece8dbc
--- /dev/null
+++ b/apps/mobile/app/profile-settings.tsx
@@ -0,0 +1,523 @@
+import { Image } from "expo-image";
+import * as ImagePicker from "expo-image-picker";
+import { Stack } from "expo-router";
+import { SymbolView } from "expo-symbols";
+import { useEffect, useState } from "react";
+import {
+ ActionSheetIOS,
+ ActivityIndicator,
+ Alert,
+ Linking,
+ Platform,
+ Pressable,
+ StyleSheet,
+ Text,
+ TextInput,
+ View,
+} from "react-native";
+import { MobileApiError, type MobileUser } from "@/api/mobile";
+import { useAuth } from "@/auth/AuthContext";
+import { SignInPanel } from "@/auth/SignInPanel";
+import { ActionButton } from "@/components/ActionButton";
+import { GlassSurface } from "@/components/GlassSurface";
+import { Screen } from "@/components/Screen";
+import { colors, fonts, radius, squircle } from "@/theme";
+
+const maxImageBytes = 1024 * 1024;
+
+const getImageContentType = (data: string) => {
+ if (data.startsWith("iVBORw0KGgo")) return "image/png" as const;
+ if (data.startsWith("/9j/")) return "image/jpeg" as const;
+ return null;
+};
+
+const profileErrorMessage = (error: unknown) => {
+ if (error instanceof MobileApiError && error.status === 400) {
+ return "Check your profile details and try again.";
+ }
+ return "Your profile could not be updated. Check your connection and try again.";
+};
+
+const openPhotoSettings = () => {
+ if (Platform.OS === "ios") {
+ ActionSheetIOS.showActionSheetWithOptions(
+ {
+ cancelButtonIndex: 1,
+ message: "Allow Cap to choose a profile image from Settings.",
+ options: ["Open Settings", "Cancel"],
+ title: "Photos access needed",
+ tintColor: colors.blue11,
+ userInterfaceStyle: "light",
+ },
+ (index) => {
+ if (index === 0) void Linking.openSettings();
+ },
+ );
+ return;
+ }
+
+ Alert.alert(
+ "Photos access needed",
+ "Allow Cap to choose a profile image from Settings.",
+ [
+ { text: "Cancel", style: "cancel" },
+ { text: "Open Settings", onPress: () => void Linking.openSettings() },
+ ],
+ );
+};
+
+const fullName = (profile: MobileUser) =>
+ [profile.name, profile.lastName].filter(Boolean).join(" ").trim();
+
+export default function ProfileSettingsScreen() {
+ const auth = useAuth();
+ const initialProfile = auth.bootstrap?.user ?? null;
+ const [profile, setProfile] = useState<MobileUser | null>(null);
+ const [firstName, setFirstName] = useState("");
+ const [lastName, setLastName] = useState("");
+ const [saving, setSaving] = useState(false);
+ const [imageBusy, setImageBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [success, setSuccess] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!initialProfile || profile) return;
+ setProfile(initialProfile);
+ setFirstName(initialProfile.name ?? "");
+ setLastName(initialProfile.lastName ?? "");
+ }, [initialProfile, profile]);
+
+ const dirty =
+ profile !== null &&
+ (firstName.trim() !== (profile.name ?? "") ||
+ lastName.trim() !== (profile.lastName ?? ""));
+ const busy = saving || imageBusy;
+
+ const applyProfile = async (
+ nextProfile: MobileUser,
+ syncNameFields = true,
+ ) => {
+ setProfile(nextProfile);
+ if (syncNameFields) {
+ setFirstName(nextProfile.name ?? "");
+ setLastName(nextProfile.lastName ?? "");
+ }
+ await auth.refresh().catch(() => undefined);
+ };
+
+ const save = async () => {
+ if (!profile || busy || !firstName.trim()) return;
+ setSaving(true);
+ setError(null);
+ setSuccess(null);
+ try {
+ const response = await auth.client.updateProfile({
+ name: firstName.trim(),
+ lastName: lastName.trim() || null,
+ });
+ await applyProfile(response);
+ setSuccess("Profile updated.");
+ } catch (cause) {
+ setError(profileErrorMessage(cause));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const chooseImage = async () => {
+ if (!profile || busy) return;
+ let result: ImagePicker.ImagePickerResult;
+ try {
+ const permission =
+ await ImagePicker.requestMediaLibraryPermissionsAsync();
+ if (!permission.granted) {
+ openPhotoSettings();
+ return;
+ }
+ result = await ImagePicker.launchImageLibraryAsync({
+ allowsEditing: true,
+ aspect: [1, 1],
+ base64: true,
+ mediaTypes: ["images"],
+ quality: 0.8,
+ });
+ } catch {
+ setError("Photos could not be opened. Check access and try again.");
+ return;
+ }
+
+ if (result.canceled) return;
+ const asset = result.assets[0];
+ if (!asset?.base64) {
+ setError("The selected image could not be read. Choose another image.");
+ return;
+ }
+ const contentType = getImageContentType(asset.base64);
+ if (!contentType) {
+ setError("Choose a PNG or JPEG image.");
+ return;
+ }
+ const expectedExtensions =
+ contentType === "image/png" ? ["png"] : ["jpg", "jpeg"];
+ const sourceFileName = asset.fileName?.split(/[\\/]/).at(-1);
+ const sourceExtension = sourceFileName?.split(".").at(-1)?.toLowerCase();
+ const fileName =
+ sourceFileName &&
+ sourceExtension &&
+ expectedExtensions.includes(sourceExtension)
+ ? sourceFileName
+ : `profile-${Date.now()}.${expectedExtensions[0]}`;
+ if (
+ (asset.fileSize && asset.fileSize > maxImageBytes) ||
+ asset.base64.length > Math.ceil((maxImageBytes * 4) / 3) + 4
+ ) {
+ setError("Choose a PNG or JPEG that is 1 MB or smaller.");
+ return;
+ }
+
+ setImageBusy(true);
+ setError(null);
+ setSuccess(null);
+ try {
+ const response = await auth.client.updateProfileImage({
+ data: asset.base64,
+ contentType,
+ fileName,
+ });
+ await applyProfile(response, false);
+ setSuccess("Profile image updated.");
+ } catch (cause) {
+ setError(profileErrorMessage(cause));
+ } finally {
+ setImageBusy(false);
+ }
+ };
+
+ const removeImage = async () => {
+ if (!profile?.imageUrl || busy) return;
+ setImageBusy(true);
+ setError(null);
+ setSuccess(null);
+ try {
+ const response = await auth.client.removeProfileImage();
+ await applyProfile(response, false);
+ setSuccess("Profile image removed.");
+ } catch (cause) {
+ setError(profileErrorMessage(cause));
+ } finally {
+ setImageBusy(false);
+ }
+ };
+
+ const showImageActions = () => {
+ if (!profile || busy) return;
+ const options = profile.imageUrl
+ ? ["Choose Photo", "Remove Photo", "Cancel"]
+ : ["Choose Photo", "Cancel"];
+ if (Platform.OS === "ios") {
+ ActionSheetIOS.showActionSheetWithOptions(
+ {
+ cancelButtonIndex: options.length - 1,
+ destructiveButtonIndex: profile.imageUrl ? 1 : undefined,
+ options,
+ title: "Profile image",
+ tintColor: colors.blue11,
+ userInterfaceStyle: "light",
+ },
+ (index) => {
+ if (index === 0) void chooseImage();
+ if (profile.imageUrl && index === 1) void removeImage();
+ },
+ );
+ return;
+ }
+
+ Alert.alert("Profile image", undefined, [
+ { text: "Choose Photo", onPress: () => void chooseImage() },
+ ...(profile.imageUrl
+ ? [
+ {
+ text: "Remove Photo",
+ style: "destructive" as const,
+ onPress: () => void removeImage(),
+ },
+ ]
+ : []),
+ { text: "Cancel", style: "cancel" },
+ ]);
+ };
+
+ if (auth.status === "signedOut") {
+ return (
+ <Screen scroll safeEdges={["left", "right", "bottom"]}>
+ <SignInPanel title="Sign in to edit your profile" />
+ </Screen>
+ );
+ }
+
+ return (
+ <>
+ <Stack.Screen
+ options={{
+ headerShown: true,
+ title: "Profile",
+ headerBackTitle: "Back",
+ headerShadowVisible: false,
+ headerStyle: { backgroundColor: colors.appBackground },
+ }}
+ />
+ <Screen
+ automaticallyAdjustKeyboardInsets
+ scroll
+ safeEdges={["left", "right", "bottom"]}
+ >
+ <View style={styles.heading}>
+ <Text style={styles.title}>Your profile</Text>
+ <Text style={styles.subtitle}>
+ Your name and image appear on shared Caps and comments.
+ </Text>
+ </View>
+ {!profile ? (
+ <View style={styles.state}>
+ <ActivityIndicator color={colors.blue9} />
+ <Text style={styles.stateText}>Loading profile…</Text>
+ </View>
+ ) : (
+ <>
+ <GlassSurface
+ fallbackStyle={styles.cardFallback}
+ style={styles.card}
+ tintColor={colors.gray1}
+ >
+ <Pressable
+ accessibilityHint="Opens profile image actions"
+ accessibilityLabel="Profile image"
+ accessibilityRole="button"
+ accessibilityState={{ busy: imageBusy, disabled: busy }}
+ accessibilityValue={{
+ text: profile.imageUrl
+ ? "Profile image set"
+ : "No profile image",
+ }}
+ disabled={busy}
+ onPress={showImageActions}
+ style={({ pressed }) => [
+ styles.imageRow,
+ pressed && !busy && styles.imageRowPressed,
+ ]}
+ >
+ <View style={styles.imagePreview}>
+ {imageBusy ? (
+ <ActivityIndicator color={colors.blue9} />
+ ) : profile.imageUrl ? (
+ <Image
+ cachePolicy="memory-disk"
+ contentFit="cover"
+ source={{ uri: profile.imageUrl }}
+ style={styles.image}
+ />
+ ) : (
+ <Text style={styles.initial}>
+ {(fullName(profile) || profile.email)
+ .slice(0, 1)
+ .toUpperCase()}
+ </Text>
+ )}
+ </View>
+ <View style={styles.imageCopy}>
+ <Text style={styles.rowTitle}>Profile image</Text>
+ <Text style={styles.rowSubtitle}>
+ PNG or JPEG, up to 1 MB
+ </Text>
+ </View>
+ <SymbolView
+ name="chevron.right"
+ size={13}
+ tintColor={colors.gray9}
+ />
+ </Pressable>
+ <View style={styles.field}>
+ <Text style={styles.label}>First name</Text>
+ <TextInput
+ accessibilityLabel="First name"
+ autoCapitalize="words"
+ editable={!busy}
+ maxLength={255}
+ onChangeText={(value) => {
+ setFirstName(value);
+ setSuccess(null);
+ }}
+ placeholder="First name"
+ placeholderTextColor={colors.gray8}
+ style={styles.input}
+ value={firstName}
+ />
+ </View>
+ <View style={styles.field}>
+ <Text style={styles.label}>Last name</Text>
+ <TextInput
+ accessibilityLabel="Last name"
+ autoCapitalize="words"
+ editable={!busy}
+ maxLength={255}
+ onChangeText={(value) => {
+ setLastName(value);
+ setSuccess(null);
+ }}
+ placeholder="Last name (optional)"
+ placeholderTextColor={colors.gray8}
+ style={styles.input}
+ value={lastName}
+ />
+ </View>
+ </GlassSurface>
+ {error ? (
+ <Text accessibilityRole="alert" style={styles.error}>
+ {error}
+ </Text>
+ ) : null}
+ {success ? (
+ <Text accessibilityLiveRegion="polite" style={styles.success}>
+ {success}
+ </Text>
+ ) : null}
+ <ActionButton
+ disabled={!dirty || !firstName.trim() || imageBusy}
+ label="Save changes"
+ loading={saving}
+ onPress={() => void save()}
+ style={styles.saveButton}
+ variant="blue"
+ />
+ </>
+ )}
+ </Screen>
+ </>
+ );
+}
+
+const styles = StyleSheet.create({
+ heading: {
+ paddingTop: 10,
+ paddingBottom: 20,
+ gap: 4,
+ },
+ title: {
+ fontFamily: fonts.medium,
+ fontSize: 24,
+ lineHeight: 30,
+ color: colors.gray12,
+ },
+ subtitle: {
+ fontFamily: fonts.regular,
+ fontSize: 14,
+ lineHeight: 20,
+ color: colors.gray10,
+ },
+ state: {
+ minHeight: 320,
+ alignItems: "center",
+ justifyContent: "center",
+ gap: 12,
+ },
+ stateText: {
+ fontFamily: fonts.regular,
+ fontSize: 14,
+ color: colors.gray10,
+ },
+ card: {
+ borderRadius: radius.lg,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: colors.gray4,
+ padding: 16,
+ gap: 20,
+ ...squircle,
+ },
+ cardFallback: {
+ backgroundColor: colors.gray1,
+ },
+ imageRow: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 12,
+ margin: -4,
+ padding: 4,
+ borderRadius: radius.md,
+ ...squircle,
+ },
+ imageRowPressed: {
+ backgroundColor: colors.gray3,
+ },
+ imagePreview: {
+ width: 72,
+ height: 72,
+ borderRadius: radius.full,
+ alignItems: "center",
+ justifyContent: "center",
+ backgroundColor: colors.blue3,
+ overflow: "hidden",
+ ...squircle,
+ },
+ image: {
+ width: "100%",
+ height: "100%",
+ },
+ initial: {
+ fontFamily: fonts.medium,
+ fontSize: 26,
+ color: colors.blue11,
+ },
+ imageCopy: {
+ flex: 1,
+ },
+ rowTitle: {
+ fontFamily: fonts.medium,
+ fontSize: 16,
+ color: colors.gray12,
+ },
+ rowSubtitle: {
+ fontFamily: fonts.regular,
+ fontSize: 13,
+ color: colors.gray9,
+ marginTop: 2,
+ },
+ field: {
+ gap: 8,
+ },
+ label: {
+ fontFamily: fonts.medium,
+ fontSize: 14,
+ color: colors.gray12,
+ },
+ input: {
+ minHeight: 46,
+ borderRadius: radius.md,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: colors.gray5,
+ backgroundColor: colors.white,
+ paddingHorizontal: 13,
+ fontFamily: fonts.regular,
+ fontSize: 16,
+ color: colors.gray12,
+ ...squircle,
+ },
+ error: {
+ fontFamily: fonts.regular,
+ fontSize: 14,
+ lineHeight: 20,
+ color: colors.red10,
+ textAlign: "center",
+ marginTop: 12,
+ },
+ success: {
+ fontFamily: fonts.regular,
+ fontSize: 14,
+ lineHeight: 20,
+ color: colors.green9,
+ textAlign: "center",
+ marginTop: 12,
+ },
+ saveButton: {
+ marginTop: 16,
+ },
+});
diff --git a/apps/mobile/src/screens/analytics.test.tsx b/apps/mobile/src/screens/analytics.test.tsx
new file mode 100644
index 000000000..8d2aa3d1c
--- /dev/null
+++ b/apps/mobile/src/screens/analytics.test.tsx
@@ -0,0 +1,219 @@
+import React, { type ReactElement, type ReactNode } from "react";
+import TestRenderer, {
+ act,
+ type ReactTestRenderer,
+ type ReactTestRendererJSON,
+} from "react-test-renderer";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import AnalyticsScreen, { downsampleAnalyticsChart } from "../../app/analytics";
+
+type HostProps = {
+ children?: ReactNode;
+ [key: string]: unknown;
+};
+
+type JsonNode = ReactTestRendererJSON | ReactTestRendererJSON[] | string | null;
+
+const auth = vi.hoisted(() => ({
+ value: {
+ status: "signedIn" as const,
+ client: {
+ getCapAnalytics: vi.fn(),
+ },
+ },
+}));
+
+(
+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const renderComponent = async (
+ node: ReactElement,
+): Promise<ReactTestRenderer> => {
+ let renderer: ReactTestRenderer | null = null;
+ await act(async () => {
+ renderer = TestRenderer.create(node);
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ return renderer as unknown as ReactTestRenderer;
+};
+
+const getTextNodes = (node: JsonNode): string[] => {
+ if (!node) return [];
+ if (typeof node === "string") return [node];
+ if (Array.isArray(node)) return node.flatMap(getTextNodes);
+ return node.children?.flatMap(getTextNodes) ?? [];
+};
+
+vi.mock("react-native", async () => {
+ const React = await import("react");
+ const createHost =
+ (name: string) =>
+ ({ children, ...props }: HostProps) =>
+ React.createElement(name, props, children);
+ return {
+ ActivityIndicator: createHost("ActivityIndicator"),
+ Pressable: createHost("Pressable"),
+ StyleSheet: {
+ create: <T extends Record<string, unknown>>(styles: T) => styles,
+ hairlineWidth: 1,
+ },
+ Text: createHost("Text"),
+ View: createHost("View"),
+ };
+});
+
+vi.mock("expo-router", async () => {
+ const React = await import("react");
+ return {
+ Stack: {
+ Screen: (props: HostProps) => React.createElement("StackScreen", props),
+ },
+ useLocalSearchParams: () => ({ capId: "video_123" }),
+ };
+});
+
+vi.mock("expo-symbols", async () => {
+ const React = await import("react");
+ return {
+ SymbolView: (props: HostProps) => React.createElement("SymbolView", props),
+ };
+});
+
+vi.mock("react-native-svg", async () => {
+ const React = await import("react");
+ return {
+ default: ({ children, ...props }: HostProps) =>
+ React.createElement("Svg", props, children),
+ Path: (props: HostProps) => React.createElement("Path", props),
+ };
+});
+
+vi.mock("@/api/mobile", () => ({
+ MobileApiError: class MobileApiError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ ) {
+ super(message);
+ }
+ },
+}));
+
+vi.mock("@/auth/AuthContext", () => ({
+ useAuth: () => auth.value,
+}));
+
+vi.mock("@/auth/SignInPanel", async () => {
+ const React = await import("react");
+ return { SignInPanel: () => React.createElement("SignInPanel") };
+});
+
+vi.mock("@/components/ActionButton", async () => {
+ const React = await import("react");
+ return {
+ ActionButton: ({ label, ...props }: HostProps & { label: string }) =>
+ React.createElement("ActionButton", {
+ ...props,
+ accessibilityLabel: label,
+ }),
+ };
+});
+
+vi.mock("@/components/GlassSurface", async () => {
+ const React = await import("react");
+ return {
+ GlassSurface: ({ children }: HostProps) =>
+ React.createElement("GlassSurface", null, children),
+ };
+});
+
+vi.mock("@/components/Screen", async () => {
+ const React = await import("react");
+ return {
+ Screen: ({ children }: HostProps) =>
+ React.createElement("Screen", null, children),
+ };
+});
+
+vi.mock("@/components/CapLoadingIndicator", async () => {
+ const React = await import("react");
+ return {
+ CapLoadingIndicator: (props: HostProps) =>
+ React.createElement("CapLoadingIndicator", props),
+ };
+});
+
+describe("AnalyticsScreen", () => {
+ beforeEach(() => {
+ auth.value.client.getCapAnalytics.mockReset();
+ auth.value.client.getCapAnalytics.mockResolvedValue({
+ available: true,
+ data: {
+ capName: "Launch review",
+ counts: { caps: 1, views: 12, comments: 2, reactions: 3 },
+ chart: [
+ {
+ bucket: "2026-07-21T12:00:00Z",
+ caps: 0,
+ views: 12,
+ comments: 2,
+ reactions: 3,
+ },
+ ],
+ breakdowns: {
+ countries: [{ name: "United Kingdom", views: 8, percentage: 66.7 }],
+ cities: [],
+ browsers: [],
+ operatingSystems: [],
+ devices: [],
+ topCaps: [],
+ },
+ },
+ });
+ });
+
+ it("loads native Cap analytics on demand", async () => {
+ const renderer = await renderComponent(
+ React.createElement(AnalyticsScreen),
+ );
+ const text = getTextNodes(renderer.toJSON());
+
+ expect(auth.value.client.getCapAnalytics).toHaveBeenCalledWith(
+ "video_123",
+ "7d",
+ );
+ expect(text).toContain("Launch review");
+ expect(text).toContain("Views over time");
+ expect(text).toContain("United Kingdom");
+ });
+
+ it("describes unavailable analytics without an external purchase call to action", async () => {
+ auth.value.client.getCapAnalytics.mockResolvedValueOnce({
+ available: false,
+ data: null,
+ });
+ const renderer = await renderComponent(
+ React.createElement(AnalyticsScreen),
+ );
+ const text = getTextNodes(renderer.toJSON()).join(" ");
+
+ expect(text).toContain("Your current plan does not include analytics.");
+ expect(text).not.toContain("Upgrade on the web");
+ });
+
+ it("bounds chart work by aggregating older buckets", () => {
+ const points = Array.from({ length: 120 }, (_, index) => ({
+ bucket: String(index),
+ caps: 0,
+ views: 1,
+ comments: 0,
+ reactions: 0,
+ }));
+ const sampled = downsampleAnalyticsChart(points, 48);
+
+ expect(sampled.length).toBeLessThanOrEqual(48);
+ expect(sampled.reduce((total, point) => total + point.views, 0)).toBe(120);
+ });
+});
diff --git a/apps/mobile/src/screens/delete-account.test.tsx b/apps/mobile/src/screens/delete-account.test.tsx
new file mode 100644
index 000000000..af148bca9
--- /dev/null
+++ b/apps/mobile/src/screens/delete-account.test.tsx
@@ -0,0 +1,274 @@
+import React, { type ReactElement, type ReactNode } from "react";
+import TestRenderer, {
+ act,
+ type ReactTestRenderer,
+ type ReactTestRendererJSON,
+} from "react-test-renderer";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import DeleteAccountScreen from "../../app/delete-account";
+
+type HostProps = {
+ children?: ReactNode;
+ [key: string]: unknown;
+};
+
+type JsonNode = ReactTestRendererJSON | ReactTestRendererJSON[] | string | null;
+
+const auth = vi.hoisted(() => ({
+ value: {
+ status: "signedIn" as const,
+ client: {
+ requestAccountDeletion: vi.fn(() =>
+ Promise.resolve({ success: true as const }),
+ ),
+ },
+ signOut: vi.fn(() => Promise.resolve()),
+ },
+}));
+
+const actionSheet = vi.hoisted(() => ({
+ showActionSheetWithOptions: vi.fn(),
+}));
+
+const router = vi.hoisted(() => ({
+ replace: vi.fn(),
+}));
+
+(
+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const renderComponent = async (
+ node: ReactElement,
+): Promise<ReactTestRenderer> => {
+ let renderer: ReactTestRenderer | null = null;
+ await act(async () => {
+ renderer = TestRenderer.create(node);
+ });
+ return renderer as unknown as ReactTestRenderer;
+};
+
+const getTextNodes = (node: JsonNode): string[] => {
+ if (!node) return [];
+ if (typeof node === "string") return [node];
+ if (Array.isArray(node)) return node.flatMap(getTextNodes);
+ return node.children?.flatMap(getTextNodes) ?? [];
+};
+
+const flushMicrotasks = async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+};
+
+vi.mock("react-native", async () => {
+ const React = await import("react");
+ const createHost =
+ (name: string) =>
+ ({ children, ...props }: HostProps) =>
+ React.createElement(name, props, children);
+
+ return {
+ ActionSheetIOS: actionSheet,
+ ActivityIndicator: createHost("ActivityIndicator"),
+ Alert: { alert: vi.fn() },
+ Platform: { OS: "ios" },
+ Pressable: createHost("Pressable"),
+ StyleSheet: {
+ create: <T extends Record<string, unknown>>(styles: T) => styles,
+ hairlineWidth: 1,
+ },
+ Text: createHost("Text"),
+ TextInput: createHost("TextInput"),
+ View: createHost("View"),
+ };
+});
+
+vi.mock("expo-router", async () => {
+ const React = await import("react");
+ return {
+ router,
+ Stack: {
+ Screen: (props: Record<string, unknown>) =>
+ React.createElement("StackScreen", props),
+ },
+ };
+});
+
+vi.mock("expo-symbols", async () => {
+ const React = await import("react");
+ return {
+ SymbolView: (props: Record<string, unknown>) =>
+ React.createElement("SymbolView", props),
+ };
+});
+
+vi.mock("@/api/mobile", () => ({
+ MobileApiError: class MobileApiError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ readonly payload: unknown,
+ ) {
+ super(message);
+ }
+ },
+}));
+
+vi.mock("@/auth/AuthContext", () => ({
+ useAuth: () => auth.value,
+}));
+
+vi.mock("@/auth/SignInPanel", async () => {
+ const React = await import("react");
+ return {
+ SignInPanel: () => React.createElement("SignInPanel"),
+ };
+});
+
+vi.mock("@/components/GlassSurface", async () => {
+ const React = await import("react");
+ return {
+ GlassSurface: ({ children }: { children?: ReactNode }) =>
+ React.createElement("GlassSurface", null, children),
+ };
+});
+
+vi.mock("@/components/Screen", async () => {
+ const React = await import("react");
+ return {
+ Screen: ({ children }: { children?: ReactNode }) =>
+ React.createElement("Screen", null, children),
+ };
+});
+
+describe("DeleteAccountScreen", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ auth.value.client.requestAccountDeletion.mockResolvedValue({
+ success: true,
+ });
+ auth.value.signOut.mockResolvedValue(undefined);
+ });
+
+ it("discloses permanent deletion and requires the confirmation phrase", async () => {
+ const renderer = await renderComponent(
+ React.createElement(DeleteAccountScreen),
+ );
+ const text = getTextNodes(renderer.toJSON()).join(" ");
+ const [confirmation] = renderer.root.findAllByProps({
+ accessibilityLabel: "Deletion confirmation",
+ });
+ const [request] = renderer.root.findAllByProps({
+ accessibilityLabel: "Request account deletion",
+ });
+ if (!confirmation || !request)
+ throw new Error("Deletion controls were not rendered");
+
+ expect(text).toContain("Permanently delete your account");
+ expect(text).toContain("Within 30 days");
+ expect(request.props.accessibilityState).toEqual({
+ busy: false,
+ disabled: true,
+ });
+
+ await act(async () => {
+ confirmation.props.onChangeText("DELETE");
+ });
+ const [confirmedRequest] = renderer.root.findAllByProps({
+ accessibilityLabel: "Request account deletion",
+ });
+ expect(confirmedRequest?.props.accessibilityState).toEqual({
+ busy: false,
+ disabled: false,
+ });
+ });
+
+ it("submits after destructive confirmation and signs out", async () => {
+ const renderer = await renderComponent(
+ React.createElement(DeleteAccountScreen),
+ );
+ const [confirmation] = renderer.root.findAllByProps({
+ accessibilityLabel: "Deletion confirmation",
+ });
+ if (!confirmation)
+ throw new Error("Deletion confirmation was not rendered");
+
+ await act(async () => {
+ confirmation.props.onChangeText("DELETE");
+ });
+ const [request] = renderer.root.findAllByProps({
+ accessibilityLabel: "Request account deletion",
+ });
+ if (!request) throw new Error("Deletion action was not rendered");
+ await act(async () => {
+ request.props.onPress();
+ });
+
+ expect(actionSheet.showActionSheetWithOptions).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cancelButtonIndex: 1,
+ destructiveButtonIndex: 0,
+ options: ["Request permanent deletion", "Cancel"],
+ }),
+ expect.any(Function),
+ );
+ const callback = actionSheet.showActionSheetWithOptions.mock
+ .calls[0]?.[1] as ((index: number) => void) | undefined;
+ if (!callback)
+ throw new Error("Deletion confirmation callback was not set");
+
+ await act(async () => {
+ callback(0);
+ await flushMicrotasks();
+ });
+
+ expect(auth.value.client.requestAccountDeletion).toHaveBeenCalledTimes(1);
+ expect(auth.value.signOut).toHaveBeenCalledTimes(1);
+ expect(router.replace).toHaveBeenCalledWith("/(tabs)/account");
+ const { Alert } = await import("react-native");
+ expect(Alert.alert).toHaveBeenCalledWith(
+ "Deletion request received",
+ expect.stringContaining("within 30 days"),
+ );
+ });
+
+ it("keeps the user signed in when the request fails", async () => {
+ auth.value.client.requestAccountDeletion.mockRejectedValueOnce(
+ new Error("offline"),
+ );
+ const renderer = await renderComponent(
+ React.createElement(DeleteAccountScreen),
+ );
+ const [confirmation] = renderer.root.findAllByProps({
+ accessibilityLabel: "Deletion confirmation",
+ });
+ if (!confirmation)
+ throw new Error("Deletion confirmation was not rendered");
+ await act(async () => {
+ confirmation.props.onChangeText("DELETE");
+ });
+ const [request] = renderer.root.findAllByProps({
+ accessibilityLabel: "Request account deletion",
+ });
+ if (!request) throw new Error("Deletion action was not rendered");
+ await act(async () => {
+ request.props.onPress();
+ });
+ const callback = actionSheet.showActionSheetWithOptions.mock
+ .calls[0]?.[1] as ((index: number) => void) | undefined;
+ if (!callback)
+ throw new Error("Deletion confirmation callback was not set");
+
+ await act(async () => {
+ callback(0);
+ await flushMicrotasks();
+ });
+
+ expect(auth.value.signOut).not.toHaveBeenCalled();
+ expect(getTextNodes(renderer.toJSON()).join(" ")).toContain(
+ "could not be submitted",
+ );
+ });
+});
diff --git a/apps/mobile/src/screens/organization-settings.test.tsx b/apps/mobile/src/screens/organization-settings.test.tsx
new file mode 100644
index 000000000..c761263f0
--- /dev/null
+++ b/apps/mobile/src/screens/organization-settings.test.tsx
@@ -0,0 +1,222 @@
+import React, { type ReactElement, type ReactNode } from "react";
+import TestRenderer, {
+ act,
+ type ReactTestRenderer,
+ type ReactTestRendererJSON,
+} from "react-test-renderer";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import OrganizationSettingsScreen from "../../app/organization-settings";
+
+type HostProps = {
+ children?: ReactNode;
+ [key: string]: unknown;
+};
+
+type JsonNode = ReactTestRendererJSON | ReactTestRendererJSON[] | string | null;
+
+const settings = {
+ id: "org_123",
+ name: "Cap",
+ role: "owner" as const,
+ canManage: true,
+ iconUrl: null,
+ allowedEmailDomain: null,
+ customDomain: "video.cap.so",
+ domainVerified: true,
+};
+
+const auth = vi.hoisted(() => ({
+ value: {
+ status: "signedIn" as const,
+ client: {
+ getOrganizationSettings: vi.fn(),
+ removeOrganizationIcon: vi.fn(),
+ updateOrganizationIcon: vi.fn(),
+ updateOrganizationSettings: vi.fn(),
+ },
+ refresh: vi.fn(),
+ },
+}));
+
+(
+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const renderComponent = async (
+ node: ReactElement,
+): Promise<ReactTestRenderer> => {
+ let renderer: ReactTestRenderer | null = null;
+ await act(async () => {
+ renderer = TestRenderer.create(node);
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ return renderer as unknown as ReactTestRenderer;
+};
+
+const getTextNodes = (node: JsonNode): string[] => {
+ if (!node) return [];
+ if (typeof node === "string") return [node];
+ if (Array.isArray(node)) return node.flatMap(getTextNodes);
+ return node.children?.flatMap(getTextNodes) ?? [];
+};
+
+vi.mock("react-native", async () => {
+ const React = await import("react");
+ const createHost =
+ (name: string) =>
+ ({ children, ...props }: HostProps) =>
+ React.createElement(name, props, children);
+ return {
+ ActionSheetIOS: { showActionSheetWithOptions: vi.fn() },
+ ActivityIndicator: createHost("ActivityIndicator"),
+ Alert: { alert: vi.fn() },
+ Linking: { openSettings: vi.fn() },
+ Platform: { OS: "ios" },
+ Pressable: createHost("Pressable"),
+ StyleSheet: {
+ create: <T extends Record<string, unknown>>(styles: T) => styles,
+ hairlineWidth: 1,
+ },
+ Text: createHost("Text"),
+ TextInput: createHost("TextInput"),
+ View: createHost("View"),
+ };
+});
+
+vi.mock("expo-image", async () => {
+ const React = await import("react");
+ return { Image: (props: HostProps) => React.createElement("Image", props) };
+});
+
+vi.mock("expo-image-picker", () => ({
+ launchImageLibraryAsync: vi.fn(),
+ requestMediaLibraryPermissionsAsync: vi.fn(),
+}));
+
+vi.mock("expo-router", async () => {
+ const React = await import("react");
+ return {
+ Stack: {
+ Screen: (props: HostProps) => React.createElement("StackScreen", props),
+ },
+ };
+});
+
+vi.mock("expo-symbols", async () => {
+ const React = await import("react");
+ return {
+ SymbolView: (props: HostProps) => React.createElement("SymbolView", props),
+ };
+});
+
+vi.mock("@/api/mobile", () => ({
+ MobileApiError: class MobileApiError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ ) {
+ super(message);
+ }
+ },
+}));
+
+vi.mock("@/auth/AuthContext", () => ({
+ useAuth: () => auth.value,
+}));
+
+vi.mock("@/auth/SignInPanel", async () => {
+ const React = await import("react");
+ return { SignInPanel: () => React.createElement("SignInPanel") };
+});
+
+vi.mock("@/components/ActionButton", async () => {
+ const React = await import("react");
+ return {
+ ActionButton: ({ label, ...props }: HostProps & { label: string }) =>
+ React.createElement("ActionButton", {
+ ...props,
+ accessibilityLabel: label,
+ }),
+ };
+});
+
+vi.mock("@/components/GlassSurface", async () => {
+ const React = await import("react");
+ return {
+ GlassSurface: ({ children }: HostProps) =>
+ React.createElement("GlassSurface", null, children),
+ };
+});
+
+vi.mock("@/components/Screen", async () => {
+ const React = await import("react");
+ return {
+ Screen: ({ children }: HostProps) =>
+ React.createElement("Screen", null, children),
+ };
+});
+
+vi.mock("@/components/CapLoadingIndicator", async () => {
+ const React = await import("react");
+ return {
+ CapLoadingIndicator: (props: HostProps) =>
+ React.createElement("CapLoadingIndicator", props),
+ };
+});
+
+describe("OrganizationSettingsScreen", () => {
+ beforeEach(() => {
+ auth.value.client.getOrganizationSettings.mockReset();
+ auth.value.client.getOrganizationSettings.mockResolvedValue(settings);
+ auth.value.client.updateOrganizationSettings.mockReset();
+ auth.value.client.updateOrganizationSettings.mockResolvedValue({
+ ...settings,
+ name: "Cap Studio",
+ });
+ auth.value.refresh.mockReset();
+ auth.value.refresh.mockResolvedValue(undefined);
+ });
+
+ it("loads editable native organization details", async () => {
+ const renderer = await renderComponent(
+ React.createElement(OrganizationSettingsScreen),
+ );
+ const text = getTextNodes(renderer.toJSON());
+
+ expect(auth.value.client.getOrganizationSettings).toHaveBeenCalledTimes(1);
+ expect(text).toContain("Organization settings");
+ expect(text).toContain("video.cap.so");
+ expect(text).toContain("Verified");
+ });
+
+ it("saves common details and refreshes the account bootstrap", async () => {
+ const renderer = await renderComponent(
+ React.createElement(OrganizationSettingsScreen),
+ );
+ const [nameInput] = renderer.root.findAllByProps({
+ accessibilityLabel: "Organization name",
+ });
+ if (!nameInput) throw new Error("Organization name input was not rendered");
+
+ await act(async () => {
+ nameInput.props.onChangeText("Cap Studio");
+ });
+ const [saveButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Save changes",
+ });
+ if (!saveButton) throw new Error("Save button was not rendered");
+
+ await act(async () => {
+ saveButton.props.onPress();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(auth.value.client.updateOrganizationSettings).toHaveBeenCalledWith({
+ name: "Cap Studio",
+ allowedEmailDomain: null,
+ });
+ expect(auth.value.refresh).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/mobile/src/screens/profile-settings.test.tsx b/apps/mobile/src/screens/profile-settings.test.tsx
new file mode 100644
index 000000000..d56fe880d
--- /dev/null
+++ b/apps/mobile/src/screens/profile-settings.test.tsx
@@ -0,0 +1,431 @@
+import React, { type ReactElement, type ReactNode } from "react";
+import TestRenderer, {
+ act,
+ type ReactTestRenderer,
+ type ReactTestRendererJSON,
+} from "react-test-renderer";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import ProfileSettingsScreen from "../../app/profile-settings";
+
+type HostProps = {
+ children?: ReactNode;
+ [key: string]: unknown;
+};
+
+type JsonNode = ReactTestRendererJSON | ReactTestRendererJSON[] | string | null;
+
+const profile = {
+ id: "user_123",
+ name: "Richie",
+ lastName: "McIlroy",
+ email: "[email protected]",
+ imageUrl: null as string | null,
+ activeOrganizationId: "org_123",
+};
+
+const auth = vi.hoisted(() => ({
+ value: {
+ status: "signedIn" as const,
+ bootstrap: {
+ user: {
+ id: "user_123",
+ name: "Richie",
+ lastName: "McIlroy",
+ email: "[email protected]",
+ imageUrl: null as string | null,
+ activeOrganizationId: "org_123",
+ },
+ },
+ client: {
+ updateProfile: vi.fn(),
+ updateProfileImage: vi.fn(),
+ removeProfileImage: vi.fn(),
+ },
+ refresh: vi.fn(() => Promise.resolve()),
+ },
+}));
+
+const actionSheet = vi.hoisted(() => ({
+ showActionSheetWithOptions: vi.fn(),
+}));
+
+const imagePicker = vi.hoisted(() => ({
+ requestMediaLibraryPermissionsAsync: vi.fn(),
+ launchImageLibraryAsync: vi.fn(),
+}));
+
+(
+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const renderComponent = async (
+ node: ReactElement,
+): Promise<ReactTestRenderer> => {
+ let renderer: ReactTestRenderer | null = null;
+ await act(async () => {
+ renderer = TestRenderer.create(node);
+ });
+ return renderer as unknown as ReactTestRenderer;
+};
+
+const getTextNodes = (node: JsonNode): string[] => {
+ if (!node) return [];
+ if (typeof node === "string") return [node];
+ if (Array.isArray(node)) return node.flatMap(getTextNodes);
+ return node.children?.flatMap(getTextNodes) ?? [];
+};
+
+const flushMicrotasks = async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+};
+
+const selectActionSheetOption = async (index: number) => {
+ const callback = actionSheet.showActionSheetWithOptions.mock.calls.at(
+ -1,
+ )?.[1] as ((selectedIndex: number) => void) | undefined;
+ if (!callback) throw new Error("Action sheet selection callback was not set");
+ await act(async () => {
+ callback(index);
+ await flushMicrotasks();
+ });
+};
+
+vi.mock("react-native", async () => {
+ const React = await import("react");
+ const createHost =
+ (name: string) =>
+ ({ children, ...props }: HostProps) =>
+ React.createElement(name, props, children);
+
+ return {
+ ActionSheetIOS: actionSheet,
+ ActivityIndicator: createHost("ActivityIndicator"),
+ Alert: { alert: vi.fn() },
+ Linking: { openSettings: vi.fn(() => Promise.resolve()) },
+ Platform: { OS: "ios" },
+ Pressable: createHost("Pressable"),
+ StyleSheet: {
+ create: <T extends Record<string, unknown>>(styles: T) => styles,
+ hairlineWidth: 1,
+ },
+ Text: createHost("Text"),
+ TextInput: createHost("TextInput"),
+ View: createHost("View"),
+ };
+});
+
+vi.mock("expo-image", async () => {
+ const React = await import("react");
+ return {
+ Image: (props: Record<string, unknown>) =>
+ React.createElement("Image", props),
+ };
+});
+
+vi.mock("expo-image-picker", () => imagePicker);
+
+vi.mock("expo-router", async () => {
+ const React = await import("react");
+ return {
+ Stack: {
+ Screen: (props: Record<string, unknown>) =>
+ React.createElement("StackScreen", props),
+ },
+ };
+});
+
+vi.mock("expo-symbols", async () => {
+ const React = await import("react");
+ return {
+ SymbolView: (props: Record<string, unknown>) =>
+ React.createElement("SymbolView", props),
+ };
+});
+
+vi.mock("@/api/mobile", () => ({
+ MobileApiError: class MobileApiError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ readonly payload: unknown,
+ ) {
+ super(message);
+ }
+ },
+}));
+
+vi.mock("@/auth/AuthContext", () => ({
+ useAuth: () => auth.value,
+}));
+
+vi.mock("@/auth/SignInPanel", async () => {
+ const React = await import("react");
+ return {
+ SignInPanel: () => React.createElement("SignInPanel"),
+ };
+});
+
+vi.mock("@/components/GlassSurface", async () => {
+ const React = await import("react");
+ return {
+ GlassSurface: ({ children }: { children?: ReactNode }) =>
+ React.createElement("GlassSurface", null, children),
+ };
+});
+
+vi.mock("@/components/Screen", async () => {
+ const React = await import("react");
+ return {
+ Screen: ({ children }: { children?: ReactNode }) =>
+ React.createElement("Screen", null, children),
+ };
+});
+
+describe("ProfileSettingsScreen", () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ actionSheet.showActionSheetWithOptions.mockReset();
+ imagePicker.requestMediaLibraryPermissionsAsync.mockReset();
+ imagePicker.requestMediaLibraryPermissionsAsync.mockResolvedValue({
+ granted: true,
+ });
+ imagePicker.launchImageLibraryAsync.mockReset();
+ imagePicker.launchImageLibraryAsync.mockResolvedValue({ canceled: true });
+ auth.value.bootstrap.user = { ...profile };
+ auth.value.client.updateProfile.mockReset();
+ auth.value.client.updateProfile.mockResolvedValue({ ...profile });
+ auth.value.client.updateProfileImage.mockReset();
+ auth.value.client.updateProfileImage.mockResolvedValue({
+ ...profile,
+ imageUrl: "https://cap.so/profile.png",
+ });
+ auth.value.client.removeProfileImage.mockReset();
+ auth.value.client.removeProfileImage.mockResolvedValue({ ...profile });
+ auth.value.refresh.mockReset();
+ auth.value.refresh.mockResolvedValue(undefined);
+ });
+
+ it("updates first and last name and refreshes Account data", async () => {
+ const renderer = await renderComponent(
+ React.createElement(ProfileSettingsScreen),
+ );
+ const [firstName] = renderer.root.findAllByProps({
+ accessibilityLabel: "First name",
+ });
+ const [lastName] = renderer.root.findAllByProps({
+ accessibilityLabel: "Last name",
+ });
+ if (!firstName || !lastName)
+ throw new Error("Name fields were not rendered");
+
+ expect(firstName.props.value).toBe("Richie");
+ expect(lastName.props.value).toBe("McIlroy");
+ await act(async () => {
+ firstName.props.onChangeText(" Richard ");
+ lastName.props.onChangeText(" McIlroy ");
+ });
+ const [save] = renderer.root.findAllByProps({
+ accessibilityLabel: "Save changes",
+ });
+ if (!save) throw new Error("Save changes button was not rendered");
+
+ await act(async () => {
+ save.props.onPress();
+ await flushMicrotasks();
+ });
+
+ expect(auth.value.client.updateProfile).toHaveBeenCalledWith({
+ name: "Richard",
+ lastName: "McIlroy",
+ });
+ expect(auth.value.refresh).toHaveBeenCalledTimes(1);
+ expect(getTextNodes(renderer.toJSON())).toContain("Profile updated.");
+ });
+
+ it("chooses and uploads a native profile image", async () => {
+ vi.spyOn(Date, "now").mockReturnValue(123456);
+ imagePicker.launchImageLibraryAsync.mockResolvedValueOnce({
+ canceled: false,
+ assets: [
+ {
+ base64: "/9j/",
+ fileName: "avatar.png",
+ fileSize: 5,
+ mimeType: "image/png",
+ },
+ ],
+ });
+ const renderer = await renderComponent(
+ React.createElement(ProfileSettingsScreen),
+ );
+ const [image] = renderer.root.findAllByProps({
+ accessibilityLabel: "Profile image",
+ });
+ const [firstName] = renderer.root.findAllByProps({
+ accessibilityLabel: "First name",
+ });
+ if (!image || !firstName) {
+ throw new Error("Profile image controls were not rendered");
+ }
+
+ await act(async () => {
+ firstName.props.onChangeText("Richard");
+ image.props.onPress();
+ });
+ await selectActionSheetOption(0);
+
+ expect(imagePicker.requestMediaLibraryPermissionsAsync).toHaveBeenCalled();
+ expect(imagePicker.launchImageLibraryAsync).toHaveBeenCalledWith({
+ allowsEditing: true,
+ aspect: [1, 1],
+ base64: true,
+ mediaTypes: ["images"],
+ quality: 0.8,
+ });
+ expect(auth.value.client.updateProfileImage).toHaveBeenCalledWith({
+ data: "/9j/",
+ contentType: "image/jpeg",
+ fileName: "profile-123456.jpg",
+ });
+ expect(auth.value.refresh).toHaveBeenCalledTimes(1);
+ expect(
+ renderer.root.findByProps({ accessibilityLabel: "First name" }).props
+ .value,
+ ).toBe("Richard");
+ expect(getTextNodes(renderer.toJSON())).toContain("Profile image updated.");
+ });
+
+ it("removes the current profile image", async () => {
+ auth.value.bootstrap.user = {
+ ...profile,
+ imageUrl: "https://cap.so/existing.png",
+ };
+ const renderer = await renderComponent(
+ React.createElement(ProfileSettingsScreen),
+ );
+ const [image] = renderer.root.findAllByProps({
+ accessibilityLabel: "Profile image",
+ });
+ if (!image) throw new Error("Profile image button was not rendered");
+
+ await act(async () => {
+ image.props.onPress();
+ });
+ expect(actionSheet.showActionSheetWithOptions).toHaveBeenCalledWith(
+ expect.objectContaining({
+ destructiveButtonIndex: 1,
+ options: ["Choose Photo", "Remove Photo", "Cancel"],
+ }),
+ expect.any(Function),
+ );
+ await selectActionSheetOption(1);
+
+ expect(auth.value.client.removeProfileImage).toHaveBeenCalledTimes(1);
+ expect(auth.value.refresh).toHaveBeenCalledTimes(1);
+ expect(getTextNodes(renderer.toJSON())).toContain("Profile image removed.");
+ });
+
+ it("rejects profile images larger than 1 MB before upload", async () => {
+ imagePicker.launchImageLibraryAsync.mockResolvedValueOnce({
+ canceled: false,
+ assets: [
+ {
+ base64: "/9j/",
+ fileName: "avatar.jpg",
+ fileSize: 1024 * 1024 + 1,
+ mimeType: "image/jpeg",
+ },
+ ],
+ });
+ const renderer = await renderComponent(
+ React.createElement(ProfileSettingsScreen),
+ );
+ const [image] = renderer.root.findAllByProps({
+ accessibilityLabel: "Profile image",
+ });
+ if (!image) throw new Error("Profile image button was not rendered");
+
+ await act(async () => {
+ image.props.onPress();
+ });
+ await selectActionSheetOption(0);
+
+ expect(auth.value.client.updateProfileImage).not.toHaveBeenCalled();
+ expect(getTextNodes(renderer.toJSON())).toContain(
+ "Choose a PNG or JPEG that is 1 MB or smaller.",
+ );
+ });
+
+ it("offers Settings when photo access is denied", async () => {
+ imagePicker.requestMediaLibraryPermissionsAsync.mockResolvedValueOnce({
+ granted: false,
+ });
+ const renderer = await renderComponent(
+ React.createElement(ProfileSettingsScreen),
+ );
+ const [image] = renderer.root.findAllByProps({
+ accessibilityLabel: "Profile image",
+ });
+ if (!image) throw new Error("Profile image button was not rendered");
+
+ await act(async () => {
+ image.props.onPress();
+ });
+ await selectActionSheetOption(0);
+
+ expect(imagePicker.launchImageLibraryAsync).not.toHaveBeenCalled();
+ expect(actionSheet.showActionSheetWithOptions).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ message: "Allow Cap to choose a profile image from Settings.",
+ options: ["Open Settings", "Cancel"],
+ title: "Photos access needed",
+ }),
+ expect.any(Function),
+ );
+ });
+
+ it("recovers from a failed name update", async () => {
+ auth.value.client.updateProfile.mockRejectedValueOnce(new Error("offline"));
+ const renderer = await renderComponent(
+ React.createElement(ProfileSettingsScreen),
+ );
+ const [firstName] = renderer.root.findAllByProps({
+ accessibilityLabel: "First name",
+ });
+ if (!firstName) throw new Error("First name field was not rendered");
+ await act(async () => {
+ firstName.props.onChangeText("Richard");
+ });
+ const [save] = renderer.root.findAllByProps({
+ accessibilityLabel: "Save changes",
+ });
+ if (!save) throw new Error("Save changes button was not rendered");
+
+ await act(async () => {
+ save.props.onPress();
+ await flushMicrotasks();
+ });
+ expect(getTextNodes(renderer.toJSON())).toContain(
+ "Your profile could not be updated. Check your connection and try again.",
+ );
+
+ auth.value.client.updateProfile.mockResolvedValueOnce({
+ ...profile,
+ name: "Richard",
+ });
+ const [retry] = renderer.root.findAllByProps({
+ accessibilityLabel: "Save changes",
+ });
+ if (!retry) throw new Error("Save changes button was not rendered");
+ await act(async () => {
+ retry.props.onPress();
+ await flushMicrotasks();
+ });
+
+ expect(auth.value.client.updateProfile).toHaveBeenCalledTimes(2);
+ expect(getTextNodes(renderer.toJSON())).toContain("Profile updated.");
+ });
+});