Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(mobile): add dashboard tab screen

Richie McIlroy315ec317801c
diff --git a/apps/mobile/app/(tabs)/index.tsx b/apps/mobile/app/(tabs)/index.tsx
new file mode 100644
index 000000000..817f7e3c7
--- /dev/null
+++ b/apps/mobile/app/(tabs)/index.tsx
@@ -0,0 +1,947 @@
+import { FlashList } from "@shopify/flash-list";
+import * as Clipboard from "expo-clipboard";
+import { router } from "expo-router";
+import { SymbolView } from "expo-symbols";
+import * as WebBrowser from "expo-web-browser";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import {
+ ActionSheetIOS,
+ Alert,
+ Linking,
+ Platform,
+ Pressable,
+ Share,
+ StyleSheet,
+ Text,
+ View,
+} from "react-native";
+import type {
+ MobileCapSummary,
+ MobileCapsListResponse,
+ MobileFolder,
+} from "@/api/mobile";
+import { MobileApiError } from "@/api/mobile";
+import { apiBaseUrl, useAuth } from "@/auth/AuthContext";
+import { SignInPanel } from "@/auth/SignInPanel";
+import { CapSettingsSheet } from "@/caps/CapSettingsSheet";
+import { showCapPasswordActions } from "@/caps/passwordActions";
+import {
+ PhotosPermissionDeniedError,
+ saveCapVideoToPhotos,
+} from "@/caps/saveCapVideo";
+import { showCapTitleActions } from "@/caps/titleActions";
+import { ActionButton } from "@/components/ActionButton";
+import { CapCard } from "@/components/CapCard";
+import { CapLogoBadge } from "@/components/CapLogoBadge";
+import { CapRefreshControl } from "@/components/CapRefreshControl";
+import { OrgSwitcher } from "@/components/OrgSwitcher";
+import { Screen } from "@/components/Screen";
+import { colors, fonts, radius, squircle } from "@/theme";
+
+type ListItem =
+ | { type: "section"; id: "folders" | "videos"; title: string }
+ | { type: "folder"; folder: MobileFolder }
+ | { type: "cap"; cap: MobileCapSummary };
+
+const folderColorOptions: Array<{
+ label: string;
+ color: MobileFolder["color"];
+}> = [
+ { label: "Normal", color: "normal" },
+ { label: "Blue", color: "blue" },
+ { label: "Red", color: "red" },
+ { label: "Yellow", color: "yellow" },
+];
+
+const folderTintByColor = {
+ normal: colors.gray12,
+ blue: colors.blue9,
+ red: colors.red9,
+ yellow: colors.yellow9,
+} as const;
+
+const getCapsErrorMessage = (error: unknown) => {
+ if (error instanceof MobileApiError) {
+ if (error.status === 401) return "Your session expired. Sign in again.";
+ return "Cap could not load your library. Try again.";
+ }
+ return error instanceof Error
+ ? error.message
+ : "Cap could not load your library. Try again.";
+};
+
+const showPhotosSettingsAlert = () => {
+ if (Platform.OS === "ios") {
+ ActionSheetIOS.showActionSheetWithOptions(
+ {
+ cancelButtonIndex: 1,
+ message: "Allow Cap to save videos to Photos 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 save videos to Photos from Settings.",
+ [
+ { text: "Cancel", style: "cancel" },
+ {
+ text: "Open Settings",
+ onPress: () => {
+ void Linking.openSettings();
+ },
+ },
+ ],
+ );
+};
+
+export default function CapsScreen() {
+ const auth = useAuth();
+ const [folder, setFolder] = useState<MobileFolder | null>(null);
+ const [result, setResult] = useState<MobileCapsListResponse | null>(null);
+ const [refreshing, setRefreshing] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [savingId, setSavingId] = useState<string | null>(null);
+ const [updatingSharingId, setUpdatingSharingId] = useState<string | null>(
+ null,
+ );
+ const [settingsCap, setSettingsCap] = useState<MobileCapSummary | null>(null);
+ const [creatingFolder, setCreatingFolder] = useState(false);
+ const [creatingFolderName, setCreatingFolderName] = useState<string | null>(
+ null,
+ );
+
+ const load = useCallback(async () => {
+ if (auth.status !== "signedIn") return;
+ setLoading(true);
+ try {
+ const response = await auth.client.listCaps({
+ folderId: folder?.id ?? null,
+ page: 1,
+ limit: 30,
+ });
+ setResult(response);
+ setLoadError(null);
+ } catch (error) {
+ setLoadError(getCapsErrorMessage(error));
+ } finally {
+ setLoading(false);
+ }
+ }, [auth, folder?.id]);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ const refresh = useCallback(async () => {
+ setRefreshing(true);
+ try {
+ await Promise.all([auth.refresh(), load()]);
+ } catch (error) {
+ setLoadError(getCapsErrorMessage(error));
+ } finally {
+ setRefreshing(false);
+ }
+ }, [auth, load]);
+
+ const confirmDeleteCap = useCallback(
+ (cap: MobileCapSummary) => {
+ if (auth.status !== "signedIn") return;
+ const deleteCap = () => {
+ void (async () => {
+ setSettingsCap(null);
+ await auth.client.deleteCap(cap.id);
+ await Promise.all([auth.refresh(), load()]);
+ })();
+ };
+
+ if (Platform.OS === "ios") {
+ ActionSheetIOS.showActionSheetWithOptions(
+ {
+ cancelButtonIndex: 1,
+ destructiveButtonIndex: 0,
+ message: `${cap.title} will be removed from your library.`,
+ options: ["Delete Cap", "Cancel"],
+ title: "Delete Cap",
+ tintColor: colors.blue11,
+ userInterfaceStyle: "light",
+ },
+ (index) => {
+ if (index === 0) deleteCap();
+ },
+ );
+ return;
+ }
+
+ Alert.alert(
+ "Delete Cap",
+ `${cap.title} will be removed from your library.`,
+ [
+ { text: "Cancel", style: "cancel" },
+ {
+ text: "Delete",
+ style: "destructive",
+ onPress: deleteCap,
+ },
+ ],
+ );
+ },
+ [auth, load],
+ );
+
+ const copyCapLink = useCallback((cap: MobileCapSummary) => {
+ void Clipboard.setStringAsync(cap.shareUrl);
+ }, []);
+
+ const shareCapLink = useCallback((cap: MobileCapSummary) => {
+ void Share.share({ url: cap.shareUrl, message: cap.shareUrl });
+ }, []);
+
+ const updateCapVisibility = useCallback(
+ async (cap: MobileCapSummary, isPublic: boolean) => {
+ if (auth.status !== "signedIn" || updatingSharingId !== null) return;
+ setUpdatingSharingId(cap.id);
+ try {
+ const updated = await auth.client.updateCapSharing(cap.id, {
+ public: isPublic,
+ });
+ setSettingsCap((current) =>
+ current?.id === updated.id ? updated : current,
+ );
+ await Promise.all([auth.refresh(), load()]);
+ } catch (error) {
+ Alert.alert(
+ "Sharing update failed",
+ error instanceof Error
+ ? error.message
+ : "Unable to update sharing for this Cap.",
+ );
+ } finally {
+ setUpdatingSharingId(null);
+ }
+ },
+ [auth, load, updatingSharingId],
+ );
+
+ const saveCapVideo = useCallback(
+ async (cap: MobileCapSummary) => {
+ if (auth.status !== "signedIn" || savingId !== null) return;
+ setSavingId(cap.id);
+ try {
+ await saveCapVideoToPhotos(auth.client, cap.id);
+ } catch (error) {
+ if (error instanceof PhotosPermissionDeniedError) {
+ showPhotosSettingsAlert();
+ return;
+ }
+ Alert.alert(
+ "Save failed",
+ error instanceof Error ? error.message : "Unable to save this video.",
+ );
+ } finally {
+ setSavingId(null);
+ }
+ },
+ [auth, savingId],
+ );
+
+ const showPasswordActions = useCallback(
+ (cap: MobileCapSummary) => {
+ if (auth.status !== "signedIn") return;
+ showCapPasswordActions({
+ cap,
+ client: auth.client,
+ onUpdated: async (updated) => {
+ setSettingsCap((current) =>
+ current?.id === updated.id ? updated : current,
+ );
+ await Promise.all([auth.refresh(), load()]);
+ },
+ });
+ },
+ [auth, load],
+ );
+
+ const showTitleActions = useCallback(
+ (cap: MobileCapSummary) => {
+ if (auth.status !== "signedIn") return;
+ showCapTitleActions({
+ cap,
+ client: auth.client,
+ onUpdated: async (updated) => {
+ setSettingsCap((current) =>
+ current?.id === updated.id ? updated : current,
+ );
+ await Promise.all([auth.refresh(), load()]);
+ },
+ });
+ },
+ [auth, load],
+ );
+
+ const showCapSettings = useCallback((cap: MobileCapSummary) => {
+ setSettingsCap(cap);
+ }, []);
+
+ const viewAnalytics = useCallback((cap: MobileCapSummary) => {
+ const url = new URL("/dashboard/analytics", apiBaseUrl);
+ url.searchParams.set("capId", cap.id);
+ void WebBrowser.openBrowserAsync(url.toString());
+ }, []);
+
+ const createFolder = useCallback(
+ async (name: string, color: MobileFolder["color"]) => {
+ if (auth.status !== "signedIn" || creatingFolder) return;
+ const trimmedName = name.trim();
+ if (!trimmedName) {
+ Alert.alert("Folder name required", "Enter a folder name to continue.");
+ return;
+ }
+
+ setCreatingFolder(true);
+ setCreatingFolderName(trimmedName);
+ try {
+ await auth.client.createFolder({ name: trimmedName, color });
+ setFolder(null);
+ await Promise.all([auth.refresh(), load()]);
+ } catch (error) {
+ Alert.alert(
+ "Folder creation failed",
+ error instanceof Error
+ ? error.message
+ : "Unable to create this folder.",
+ );
+ } finally {
+ setCreatingFolder(false);
+ setCreatingFolderName(null);
+ }
+ },
+ [auth, creatingFolder, load],
+ );
+
+ const showFolderColorSheet = useCallback(
+ (name: string) => {
+ if (Platform.OS !== "ios") {
+ void createFolder(name, "normal");
+ return;
+ }
+
+ const cancelButtonIndex = folderColorOptions.length;
+ ActionSheetIOS.showActionSheetWithOptions(
+ {
+ cancelButtonIndex,
+ message: name,
+ options: [
+ ...folderColorOptions.map((option) => option.label),
+ "Cancel",
+ ],
+ title: "Folder color",
+ tintColor: colors.blue11,
+ userInterfaceStyle: "light",
+ },
+ (index) => {
+ const option = folderColorOptions[index];
+ if (option) void createFolder(name, option.color);
+ },
+ );
+ },
+ [createFolder],
+ );
+
+ const showNewFolderPrompt = useCallback(() => {
+ if (auth.status !== "signedIn" || creatingFolder) return;
+
+ if (Platform.OS === "ios") {
+ Alert.prompt(
+ "New Folder",
+ "Name this folder.",
+ [
+ { text: "Cancel", style: "cancel" },
+ {
+ text: "Next",
+ onPress: (value?: string) => {
+ const name = value?.trim() ?? "";
+ if (!name) {
+ Alert.alert(
+ "Folder name required",
+ "Enter a folder name to continue.",
+ );
+ return;
+ }
+ showFolderColorSheet(name);
+ },
+ },
+ ],
+ "plain-text",
+ );
+ return;
+ }
+
+ Alert.alert("New Folder", "Create a folder named Untitled?", [
+ { text: "Cancel", style: "cancel" },
+ {
+ text: "Create",
+ onPress: () => {
+ void createFolder("Untitled", "normal");
+ },
+ },
+ ]);
+ }, [auth.status, createFolder, creatingFolder, showFolderColorSheet]);
+
+ const showSharingActions = useCallback(
+ (cap: MobileCapSummary) => {
+ if (updatingSharingId !== null) return;
+ const visibilityAction = cap.public ? "Make private" : "Make public";
+
+ if (Platform.OS === "ios") {
+ ActionSheetIOS.showActionSheetWithOptions(
+ {
+ cancelButtonIndex: 3,
+ message: cap.shareUrl,
+ options: [visibilityAction, "Copy link", "Share link", "Cancel"],
+ title: cap.public ? "Shared" : "Not shared",
+ tintColor: colors.blue11,
+ userInterfaceStyle: "light",
+ },
+ (index) => {
+ if (index === 0) void updateCapVisibility(cap, !cap.public);
+ if (index === 1) copyCapLink(cap);
+ if (index === 2) shareCapLink(cap);
+ },
+ );
+ return;
+ }
+
+ Alert.alert(cap.public ? "Shared" : "Not shared", cap.shareUrl, [
+ {
+ text: visibilityAction,
+ onPress: () => void updateCapVisibility(cap, !cap.public),
+ },
+ { text: "Copy link", onPress: () => copyCapLink(cap) },
+ { text: "Share link", onPress: () => shareCapLink(cap) },
+ { text: "Cancel", style: "cancel" },
+ ]);
+ },
+ [copyCapLink, shareCapLink, updateCapVisibility, updatingSharingId],
+ );
+
+ const items = useMemo<ListItem[]>(() => {
+ if (!result) return [];
+ const nextItems: ListItem[] = [];
+ if (result.folders.length > 0) {
+ nextItems.push({ type: "section", id: "folders", title: "Folders" });
+ nextItems.push(
+ ...result.folders.map((item) => ({
+ type: "folder" as const,
+ folder: item,
+ })),
+ );
+ }
+ if (result.caps.length > 0) {
+ nextItems.push({ type: "section", id: "videos", title: "Videos" });
+ nextItems.push(
+ ...result.caps.map((item) => ({ type: "cap" as const, cap: item })),
+ );
+ }
+ return nextItems;
+ }, [result]);
+
+ const userName = auth.bootstrap?.user.name?.split(" ")[0];
+ const folderCreationHint = creatingFolder
+ ? "Folder creation is in progress"
+ : "Creates a folder for organizing Caps";
+ const folderCreationStatus = creatingFolder
+ ? `Creating folder ${creatingFolderName ?? ""}`.trim()
+ : null;
+ const folderCreationAccessibilityLabel = "New Folder";
+ const folderCreationAccessibilityValue = folderCreationStatus
+ ? { text: folderCreationStatus }
+ : undefined;
+ const dashboardActionHint = creatingFolder
+ ? "Folder creation is in progress"
+ : null;
+ const savingCap =
+ savingId !== null
+ ? settingsCap?.id === savingId
+ ? settingsCap
+ : (result?.caps.find((cap) => cap.id === savingId) ?? null)
+ : null;
+ const updatingSharingCap =
+ updatingSharingId !== null
+ ? settingsCap?.id === updatingSharingId
+ ? settingsCap
+ : (result?.caps.find((cap) => cap.id === updatingSharingId) ?? null)
+ : null;
+ const isLibraryActionInProgress =
+ savingId !== null || updatingSharingId !== null;
+ const saveDisabledHint =
+ savingId !== null
+ ? "Save is in progress"
+ : "Current Cap action is in progress";
+ const visibilityDisabledHint =
+ updatingSharingId !== null
+ ? "Sharing update is in progress"
+ : "Current Cap action is in progress";
+ const saveDisabledAccessibilityValue = savingCap
+ ? `Saving video for ${savingCap.title}`
+ : undefined;
+ const visibilityDisabledAccessibilityValue = updatingSharingCap
+ ? `Updating sharing for ${updatingSharingCap.title}`
+ : undefined;
+
+ if (auth.status === "loading") {
+ return <Screen title="My Caps" loading />;
+ }
+
+ if (auth.status === "signedOut") {
+ return (
+ <Screen scroll>
+ <SignInPanel />
+ </Screen>
+ );
+ }
+
+ return (
+ <Screen title="My Caps" loading={loading && !result}>
+ {auth.bootstrap ? (
+ <View style={styles.topBar}>
+ <OrgSwitcher
+ bootstrap={auth.bootstrap}
+ onChange={async (organizationId) => {
+ setFolder(null);
+ await auth.setActiveOrganization(organizationId);
+ await load();
+ }}
+ />
+ </View>
+ ) : null}
+ <View style={styles.actions}>
+ <ActionButton
+ label="New Folder"
+ accessibilityLabel={folderCreationAccessibilityLabel}
+ accessibilityHint={folderCreationHint}
+ accessibilityValue={folderCreationAccessibilityValue}
+ onPress={showNewFolderPrompt}
+ loading={creatingFolder}
+ size="sm"
+ style={styles.actionButton}
+ symbol="folder.badge.plus"
+ variant="dark"
+ />
+ <ActionButton
+ label="Import Video"
+ accessibilityHint={dashboardActionHint ?? "Opens import options"}
+ accessibilityValue={folderCreationAccessibilityValue}
+ onPress={() => router.push("/upload")}
+ disabled={creatingFolder}
+ size="sm"
+ style={styles.actionButton}
+ symbol="square.and.arrow.up"
+ variant="dark"
+ />
+ </View>
+ {folder ? (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel="Back to My Caps"
+ onPress={() => setFolder(null)}
+ style={styles.folderCrumb}
+ >
+ <Text style={styles.folderCrumbText}>My Caps</Text>
+ <SymbolView
+ name="chevron.right"
+ size={14}
+ tintColor={colors.gray9}
+ weight="medium"
+ />
+ <View style={styles.folderCrumbIcon}>
+ <SymbolView
+ name="folder.fill"
+ size={20}
+ tintColor={folderTintByColor[folder.color]}
+ weight="medium"
+ />
+ </View>
+ <Text numberOfLines={1} style={styles.folderCurrent}>
+ {folder.name}
+ </Text>
+ </Pressable>
+ ) : null}
+ {loadError ? (
+ <View
+ accessibilityLabel={`Library error: ${loadError}`}
+ accessibilityLiveRegion="polite"
+ accessibilityRole="alert"
+ style={styles.errorCard}
+ >
+ <View style={styles.errorIcon}>
+ <SymbolView
+ name="exclamationmark.triangle.fill"
+ size={18}
+ tintColor={colors.red9}
+ weight="medium"
+ />
+ </View>
+ <View style={styles.errorCopy}>
+ <Text style={styles.errorTitle}>Unable to load Caps</Text>
+ <Text style={styles.errorText}>{loadError}</Text>
+ </View>
+ <ActionButton
+ label="Try again"
+ accessibilityHint="Reloads your Cap library"
+ onPress={load}
+ size="sm"
+ style={styles.errorButton}
+ symbol="arrow.clockwise"
+ />
+ </View>
+ ) : null}
+ {loadError && !result ? null : (
+ <FlashList
+ data={items}
+ keyExtractor={(item) =>
+ item.type === "section"
+ ? `section-${item.id}`
+ : item.type === "folder"
+ ? `folder-${item.folder.id}`
+ : `cap-${item.cap.id}`
+ }
+ refreshControl={
+ <CapRefreshControl refreshing={refreshing} onRefresh={refresh} />
+ }
+ showsVerticalScrollIndicator={false}
+ contentContainerStyle={styles.listContent}
+ getItemType={(item) => item.type}
+ ListEmptyComponent={
+ <View style={styles.emptyState}>
+ <View style={styles.emptyArt}>
+ <View style={[styles.emptyArtCard, styles.emptyArtCardBack]} />
+ <View style={styles.emptyArtCard} />
+ <View style={styles.emptyLogo}>
+ <CapLogoBadge size={52} />
+ </View>
+ </View>
+ <Text style={styles.emptyTitle}>
+ Hey{userName ? ` ${userName}` : ""}! Import your first Cap
+ </Text>
+ <Text style={styles.emptyText}>
+ Bring videos into Cap and share them instantly.
+ </Text>
+ <View style={styles.emptyActions}>
+ <ActionButton
+ label="Import Video"
+ accessibilityHint={
+ dashboardActionHint ?? "Opens import options"
+ }
+ accessibilityValue={folderCreationAccessibilityValue}
+ onPress={() => router.push("/upload")}
+ disabled={creatingFolder}
+ style={styles.emptyButton}
+ symbol="square.and.arrow.up"
+ variant="dark"
+ />
+ </View>
+ </View>
+ }
+ renderItem={({ item }) =>
+ item.type === "section" ? (
+ <View style={styles.sectionHeader}>
+ <Text style={styles.sectionTitle}>{item.title}</Text>
+ </View>
+ ) : item.type === "folder" ? (
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={`Open folder ${item.folder.name}`}
+ onPress={() => setFolder(item.folder)}
+ style={({ pressed }) => [
+ styles.folderRow,
+ pressed ? styles.folderRowPressed : null,
+ ]}
+ >
+ <View style={styles.folderIcon}>
+ <SymbolView
+ name="folder.fill"
+ size={32}
+ tintColor={folderTintByColor[item.folder.color]}
+ weight="medium"
+ />
+ </View>
+ <View style={styles.folderText}>
+ <Text numberOfLines={1} style={styles.folderName}>
+ {item.folder.name}
+ </Text>
+ <Text style={styles.folderMeta}>
+ {item.folder.videoCount}{" "}
+ {item.folder.videoCount === 1 ? "video" : "videos"}
+ </Text>
+ </View>
+ <SymbolView
+ name="chevron.right"
+ size={14}
+ tintColor={colors.gray9}
+ weight="medium"
+ />
+ </Pressable>
+ ) : (
+ <CapCard
+ cap={item.cap}
+ onAnalyticsPress={() => viewAnalytics(item.cap)}
+ onCopyPress={() => copyCapLink(item.cap)}
+ onPress={() => router.push(`/caps/${item.cap.id}`)}
+ onSharePress={() => shareCapLink(item.cap)}
+ onVisibilityPress={() => showSharingActions(item.cap)}
+ onMenuPress={() => showCapSettings(item.cap)}
+ visibilityBusy={updatingSharingId === item.cap.id}
+ visibilityDisabled={updatingSharingId !== null}
+ visibilityDisabledHint={
+ updatingSharingId === item.cap.id
+ ? "Sharing update is in progress"
+ : "Another sharing update is in progress"
+ }
+ visibilityAccessibilityValue={
+ updatingSharingId === item.cap.id
+ ? `Updating sharing for ${item.cap.title}`
+ : undefined
+ }
+ />
+ )
+ }
+ />
+ )}
+ <CapSettingsSheet
+ cap={settingsCap}
+ visible={settingsCap !== null}
+ onClose={() => setSettingsCap(null)}
+ onCopyLink={copyCapLink}
+ onDelete={confirmDeleteCap}
+ onPassword={showPasswordActions}
+ onRename={showTitleActions}
+ onSaveVideo={(cap) => {
+ void saveCapVideo(cap);
+ }}
+ onShareLink={shareCapLink}
+ onViewAnalytics={viewAnalytics}
+ onVisibilityChange={(cap, isPublic) => {
+ void updateCapVisibility(cap, isPublic);
+ }}
+ saveDisabled={isLibraryActionInProgress}
+ saveDisabledHint={saveDisabledHint}
+ saveDisabledValue={savingId !== null ? undefined : "Unavailable"}
+ saveDisabledAccessibilityValue={saveDisabledAccessibilityValue}
+ visibilityDisabled={isLibraryActionInProgress}
+ visibilityDisabledHint={visibilityDisabledHint}
+ visibilityDisabledAccessibilityValue={
+ visibilityDisabledAccessibilityValue
+ }
+ />
+ </Screen>
+ );
+}
+
+const styles = StyleSheet.create({
+ topBar: {
+ marginBottom: 12,
+ },
+ actions: {
+ flexDirection: "row",
+ flexWrap: "wrap",
+ gap: 8,
+ marginBottom: 40,
+ },
+ actionButton: {
+ flexGrow: 1,
+ flexBasis: 104,
+ paddingHorizontal: 12,
+ },
+ listContent: {
+ paddingBottom: 22,
+ },
+ folderCrumb: {
+ minHeight: 40,
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 7,
+ marginBottom: 14,
+ },
+ folderCrumbText: {
+ fontFamily: fonts.medium,
+ color: colors.gray9,
+ fontSize: 20,
+ lineHeight: 26,
+ },
+ folderCrumbIcon: {
+ width: 24,
+ height: 24,
+ alignItems: "center",
+ justifyContent: "center",
+ },
+ folderCurrent: {
+ flex: 1,
+ fontFamily: fonts.medium,
+ color: colors.gray12,
+ fontSize: 20,
+ lineHeight: 26,
+ },
+ folderRow: {
+ minHeight: 82,
+ flexDirection: "row",
+ alignItems: "center",
+ borderRadius: radius.sm,
+ borderWidth: StyleSheet.hairlineWidth,
+ paddingHorizontal: 16,
+ paddingVertical: 16,
+ gap: 12,
+ marginBottom: 12,
+ backgroundColor: colors.gray3,
+ borderColor: colors.gray5,
+ ...squircle,
+ },
+ folderRowPressed: {
+ backgroundColor: colors.gray4,
+ borderColor: colors.gray6,
+ },
+ sectionHeader: {
+ paddingTop: 8,
+ paddingBottom: 24,
+ },
+ sectionTitle: {
+ fontFamily: fonts.medium,
+ fontSize: 24,
+ lineHeight: 30,
+ color: colors.gray12,
+ },
+ folderIcon: {
+ width: 50,
+ height: 50,
+ alignItems: "center",
+ justifyContent: "center",
+ },
+ folderText: {
+ flex: 1,
+ minWidth: 0,
+ },
+ folderName: {
+ fontFamily: fonts.regular,
+ fontSize: 15,
+ lineHeight: 22,
+ color: colors.gray12,
+ },
+ folderMeta: {
+ fontFamily: fonts.regular,
+ fontSize: 13,
+ lineHeight: 18,
+ color: colors.gray10,
+ },
+ errorCard: {
+ flexDirection: "row",
+ alignItems: "center",
+ gap: 12,
+ backgroundColor: colors.gray1,
+ borderRadius: radius.md,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: colors.gray3,
+ padding: 14,
+ marginBottom: 14,
+ ...squircle,
+ },
+ errorIcon: {
+ width: 36,
+ height: 36,
+ borderRadius: radius.full,
+ alignItems: "center",
+ justifyContent: "center",
+ backgroundColor: colors.gray3,
+ ...squircle,
+ },
+ errorCopy: {
+ flex: 1,
+ minWidth: 0,
+ },
+ errorTitle: {
+ fontFamily: fonts.medium,
+ fontSize: 15,
+ lineHeight: 20,
+ color: colors.gray12,
+ },
+ errorText: {
+ fontFamily: fonts.regular,
+ fontSize: 13,
+ lineHeight: 18,
+ color: colors.gray10,
+ marginTop: 2,
+ },
+ errorButton: {
+ paddingHorizontal: 14,
+ },
+ emptyState: {
+ alignItems: "center",
+ paddingTop: 42,
+ gap: 12,
+ paddingHorizontal: 8,
+ },
+ emptyArt: {
+ width: 180,
+ height: 112,
+ alignItems: "center",
+ justifyContent: "center",
+ marginBottom: 10,
+ },
+ emptyArtCard: {
+ position: "absolute",
+ width: 152,
+ height: 86,
+ borderRadius: radius.md,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: colors.gray3,
+ backgroundColor: colors.gray1,
+ transform: [{ rotate: "-4deg" }],
+ ...squircle,
+ },
+ emptyArtCardBack: {
+ backgroundColor: colors.gray3,
+ borderColor: colors.gray4,
+ transform: [{ translateX: 12 }, { translateY: 7 }, { rotate: "5deg" }],
+ },
+ emptyLogo: {
+ width: 72,
+ height: 72,
+ borderRadius: radius.lg,
+ alignItems: "center",
+ justifyContent: "center",
+ backgroundColor: colors.white,
+ borderWidth: StyleSheet.hairlineWidth,
+ borderColor: colors.gray3,
+ ...squircle,
+ },
+ emptyTitle: {
+ fontFamily: fonts.medium,
+ fontSize: 20,
+ color: colors.gray12,
+ textAlign: "center",
+ },
+ emptyText: {
+ fontFamily: fonts.regular,
+ fontSize: 15,
+ lineHeight: 22,
+ color: colors.gray10,
+ textAlign: "center",
+ },
+ emptyActions: {
+ width: "100%",
+ flexDirection: "row",
+ gap: 10,
+ marginTop: 4,
+ },
+ emptyButton: {
+ flex: 1,
+ },
+});
diff --git a/apps/mobile/src/screens/dashboard-upload-visibility.test.tsx b/apps/mobile/src/screens/dashboard-upload-visibility.test.tsx
new file mode 100644
index 000000000..b0880df9d
--- /dev/null
+++ b/apps/mobile/src/screens/dashboard-upload-visibility.test.tsx
@@ -0,0 +1,2377 @@
+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 CapsScreen from "../../app/(tabs)";
+import UploadScreen from "../../app/(tabs)/upload";
+
+type AuthStub = {
+ status: "signedIn";
+ bootstrap: {
+ activeOrganizationId: string;
+ user: {
+ email: string;
+ name: string | null;
+ };
+ };
+ client: {
+ createFolder: (input: { color?: string; name: string }) => Promise<{
+ color: string;
+ id: string;
+ name: string;
+ parentId: null;
+ videoCount: number;
+ }>;
+ getCap: (id: string) => Promise<{
+ cap: {
+ upload: null;
+ };
+ }>;
+ listCaps: () => Promise<{
+ caps: unknown[];
+ folders: unknown[];
+ pagination: {
+ hasNextPage: boolean;
+ page: number;
+ totalPages: number;
+ };
+ rootFolders: unknown[];
+ }>;
+ updateCapSharing: (
+ id: string,
+ input: { public: boolean },
+ ) => Promise<unknown>;
+ };
+ refresh: () => Promise<void>;
+};
+
+type HostProps = {
+ children?: ReactNode;
+ [key: string]: unknown;
+};
+
+type JsonNode = ReactTestRendererJSON | ReactTestRendererJSON[] | string | null;
+
+const createAuth = (): AuthStub => ({
+ status: "signedIn",
+ bootstrap: {
+ activeOrganizationId: "org_123",
+ user: {
+ email: "[email protected]",
+ name: "Richie",
+ },
+ },
+ client: {
+ createFolder: vi.fn((input: { color?: string; name: string }) =>
+ Promise.resolve({
+ id: "folder_123",
+ name: input.name,
+ color: input.color ?? "normal",
+ parentId: null,
+ videoCount: 0,
+ }),
+ ),
+ getCap: () =>
+ Promise.resolve({
+ cap: {
+ upload: null,
+ },
+ }),
+ listCaps: () =>
+ Promise.resolve({
+ caps: [],
+ folders: [],
+ pagination: {
+ hasNextPage: false,
+ page: 1,
+ totalPages: 1,
+ },
+ rootFolders: [],
+ }),
+ updateCapSharing: vi.fn((id: string, input: { public: boolean }) =>
+ Promise.resolve({
+ id,
+ public: input.public,
+ }),
+ ),
+ },
+ refresh: () => Promise.resolve(),
+});
+
+const createDeferred = <T,>() => {
+ let resolve!: (value: T | PromiseLike<T>) => void;
+ const promise = new Promise<T>((nextResolve) => {
+ resolve = nextResolve;
+ });
+ return { promise, resolve };
+};
+
+const authState = vi.hoisted((): { value: AuthStub | null } => ({
+ value: null,
+}));
+
+const uploadQueueState = vi.hoisted(
+ (): {
+ value: {
+ items: Array<{
+ capId: string | null;
+ contentType: string;
+ createdAt: string;
+ error: string | null;
+ fileName: string;
+ folderId: string | null;
+ id: string;
+ localUri: string;
+ organizationId: string | null;
+ progress: number;
+ processingMessage?: string | null;
+ rawFileKey: string | null;
+ size: number;
+ durationSeconds?: number;
+ status: "complete" | "failed" | "processing" | "queued" | "uploading";
+ updatedAt: string;
+ }>;
+ };
+ } => ({
+ value: {
+ items: [],
+ },
+ }),
+);
+
+const uploadQueueActionsState = vi.hoisted((): { value: unknown[] } => ({
+ value: [],
+}));
+
+(
+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const renderTree = async (node: ReactElement): Promise<JsonNode> => {
+ let renderer: ReactTestRenderer | null = null;
+ await act(async () => {
+ renderer = TestRenderer.create(node);
+ });
+ return (renderer as ReactTestRenderer | null)?.toJSON() ?? null;
+};
+
+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 hasProp = (node: JsonNode, prop: string, value: unknown): boolean => {
+ if (!node || typeof node === "string") return false;
+ if (Array.isArray(node))
+ return node.some((item) => hasProp(item, prop, value));
+ if (node.props[prop] === value) return true;
+ return node.children?.some((child) => hasProp(child, prop, value)) ?? false;
+};
+
+const propMatches = (actual: unknown, expected: unknown): boolean => {
+ if (
+ expected &&
+ typeof expected === "object" &&
+ !Array.isArray(expected) &&
+ actual &&
+ typeof actual === "object" &&
+ !Array.isArray(actual)
+ ) {
+ return Object.entries(expected).every(
+ ([key, value]) => (actual as Record<string, unknown>)[key] === value,
+ );
+ }
+
+ return actual === expected;
+};
+
+const hasProps = (
+ node: JsonNode,
+ expected: Record<string, unknown>,
+): boolean => {
+ if (!node || typeof node === "string") return false;
+ if (Array.isArray(node)) return node.some((item) => hasProps(item, expected));
+ if (
+ Object.entries(expected).every(([key, value]) =>
+ propMatches(node.props[key], value),
+ )
+ ) {
+ return true;
+ }
+ return node.children?.some((child) => hasProps(child, expected)) ?? false;
+};
+
+const hasStyle = (
+ node: JsonNode,
+ expected: Record<string, unknown>,
+): boolean => {
+ if (!node || typeof node === "string") return false;
+ if (Array.isArray(node)) return node.some((item) => hasStyle(item, expected));
+ const style =
+ typeof node.props.style === "function"
+ ? node.props.style({ pressed: false })
+ : node.props.style;
+ const resolved = Array.isArray(style)
+ ? Object.assign({}, ...style.filter(Boolean))
+ : style;
+ if (
+ resolved &&
+ Object.entries(expected).every(([key, value]) => resolved[key] === value)
+ ) {
+ return true;
+ }
+ return node.children?.some((child) => hasStyle(child, expected)) ?? false;
+};
+
+const resolveStyle = (
+ style: unknown,
+ pressed = false,
+): Record<string, unknown> => {
+ const resolved = typeof style === "function" ? style({ pressed }) : style;
+ const styles = Array.isArray(resolved) ? resolved : [resolved];
+ return Object.assign({}, ...styles.filter(Boolean));
+};
+
+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(),
+ prompt: vi.fn(),
+ },
+ AppState: {
+ addEventListener: vi.fn(() => ({
+ remove: vi.fn(),
+ })),
+ },
+ Linking: {
+ openSettings: vi.fn(),
+ },
+ Modal: createHost("Modal"),
+ Platform: {
+ OS: "ios",
+ select: <T,>(values: { default?: T; ios?: T }) =>
+ values.ios ?? values.default,
+ },
+ Pressable: createHost("Pressable"),
+ RefreshControl: createHost("RefreshControl"),
+ Share: {
+ share: vi.fn(),
+ },
+ StyleSheet: {
+ absoluteFillObject: {
+ bottom: 0,
+ left: 0,
+ position: "absolute",
+ right: 0,
+ top: 0,
+ },
+ create: <T extends Record<string, unknown>>(styles: T) => styles,
+ hairlineWidth: 1,
+ },
+ Switch: createHost("Switch"),
+ Text: createHost("Text"),
+ TextInput: createHost("TextInput"),
+ View: createHost("View"),
+ };
+});
+
+vi.mock("@shopify/flash-list", async () => {
+ const React = await import("react");
+ return {
+ FlashList: ({
+ data,
+ ListEmptyComponent,
+ renderItem,
+ }: {
+ data?: unknown[];
+ ListEmptyComponent?: ReactNode;
+ renderItem?: (info: { index: number; item: unknown }) => ReactNode;
+ }) =>
+ React.createElement(
+ "FlashList",
+ null,
+ data && data.length > 0
+ ? data.map((item, index) =>
+ React.createElement(
+ React.Fragment,
+ { key: index },
+ renderItem?.({ item, index }),
+ ),
+ )
+ : ListEmptyComponent,
+ ),
+ };
+});
+
+vi.mock("expo-clipboard", () => ({
+ setStringAsync: vi.fn(),
+}));
+
+vi.mock("expo-router", () => ({
+ router: {
+ push: vi.fn(),
+ },
+}));
+
+vi.mock("expo-web-browser", () => ({
+ openBrowserAsync: vi.fn(),
+}));
+
+vi.mock("@/auth/AuthContext", () => ({
+ apiBaseUrl: "https://cap.so",
+ useAuth: () => authState.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: ({
+ children,
+ label,
+ onPress,
+ ...props
+ }: {
+ children?: ReactNode;
+ label: string;
+ onPress?: () => void;
+ [key: string]: unknown;
+ }) =>
+ React.createElement(
+ "ActionButton",
+ { accessibilityLabel: label, onPress, ...props },
+ children ?? label,
+ ),
+ };
+});
+
+vi.mock("@/components/Screen", async () => {
+ const React = await import("react");
+
+ return {
+ Screen: ({
+ children,
+ loading,
+ subtitle,
+ title,
+ }: {
+ children?: ReactNode;
+ loading?: boolean;
+ subtitle?: string | null;
+ title?: string;
+ }) =>
+ React.createElement(
+ "Screen",
+ null,
+ title ? React.createElement("Text", null, title) : null,
+ subtitle ? React.createElement("Text", null, subtitle) : null,
+ loading ? React.createElement("Text", null, "Loading") : children,
+ ),
+ };
+});
+
+vi.mock("@/components/GlassSurface", async () => {
+ const React = await import("react");
+ return {
+ GlassSurface: ({ children }: { children?: ReactNode }) =>
+ React.createElement("GlassSurface", null, children),
+ };
+});
+
+vi.mock("@/components/CapCard", async () => {
+ const React = await import("react");
+ return {
+ CapCard: (props: HostProps) => React.createElement("CapCard", props),
+ };
+});
+
+vi.mock("@/components/OrgSwitcher", async () => {
+ const React = await import("react");
+ return {
+ OrgSwitcher: () => React.createElement("OrgSwitcher"),
+ };
+});
+
+vi.mock("expo-symbols", () => ({
+ SymbolView: () => null,
+}));
+
+vi.mock("react-native-svg", async () => {
+ const React = await import("react");
+ const createHost =
+ (name: string) =>
+ ({ children, ...props }: HostProps) =>
+ React.createElement(name, props, children);
+
+ return {
+ default: createHost("Svg"),
+ Path: createHost("Path"),
+ Rect: createHost("Rect"),
+ };
+});
+
+vi.mock("@/theme", () => ({
+ colors: {
+ appBackground: "#f9f9f9",
+ black: "#000000",
+ blackAlpha40: "rgba(18, 22, 31, 0.4)",
+ blue11: "#0d74ce",
+ blue3: "#edf6ff",
+ blue6: "#acd8fc",
+ blue9: "#0090ff",
+ buttonBlue: "#2563eb",
+ buttonBlueBorder: "#1e40af",
+ glass: "rgba(252, 252, 252, 0.72)",
+ gray1: "#fcfcfc",
+ gray10: "#838383",
+ gray12: "#202020",
+ gray2: "#f9f9f9",
+ gray3: "#f0f0f0",
+ gray4: "#e8e8e8",
+ gray5: "#e0e0e0",
+ gray6: "#d9d9d9",
+ gray9: "#8d8d8d",
+ red1: "#fffcfc",
+ red3: "#feebec",
+ red6: "#fdbdbe",
+ red9: "#e5484d",
+ white: "#ffffff",
+ yellow3: "#fffab8",
+ yellow5: "#ffe770",
+ yellow9: "#f5d90a",
+ },
+ fonts: {
+ bold: "NeueMontreal-Bold",
+ medium: "NeueMontreal-Medium",
+ regular: "NeueMontreal-Regular",
+ },
+ radius: {
+ full: 999,
+ lg: 16,
+ md: 12,
+ sm: 8,
+ xl: 20,
+ xs: 6,
+ },
+ shadows: {
+ card: {},
+ popover: {},
+ },
+ squircle: {
+ borderCurve: "continuous",
+ },
+}));
+
+vi.mock("expo-document-picker", () => ({
+ getDocumentAsync: vi.fn(),
+}));
+
+vi.mock("expo-file-system/legacy", () => ({
+ documentDirectory: "file:///tmp/",
+ downloadAsync: vi.fn(),
+}));
+
+vi.mock("expo-image-picker", () => ({
+ launchImageLibraryAsync: vi.fn(),
+ requestMediaLibraryPermissionsAsync: vi.fn(),
+}));
+
+vi.mock("expo-media-library", () => ({
+ requestPermissionsAsync: vi.fn(),
+ saveToLibraryAsync: vi.fn(),
+}));
+
+vi.mock("@/uploads/runMobileUpload", () => ({
+ runMobileUpload: vi.fn(),
+}));
+
+vi.mock("@/uploads/uploadQueue", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/uploads/uploadQueue")>();
+
+ return {
+ ...actual,
+ emptyUploadQueue: uploadQueueState.value,
+ uploadProgressPercent: (progress: number) => Math.round(progress * 100),
+ uploadQueueReducer: (state: { items: unknown[] }, action: unknown) => {
+ uploadQueueActionsState.value.push(action);
+ return state;
+ },
+ uploadQueueStatusText: (item: {
+ processingMessage?: string | null;
+ progress: number;
+ status: string;
+ }) => {
+ if (item.status === "complete") return "Ready to view";
+ if (item.status === "failed") return "Upload failed";
+ if (item.status === "processing") {
+ return item.processingMessage ?? "Finishing up";
+ }
+ if (item.status === "uploading") {
+ return `Uploading ${Math.round(item.progress * 100)}%`;
+ }
+ return "Queued";
+ },
+ };
+});
+
+describe("upload and dashboard visibility", () => {
+ beforeEach(() => {
+ authState.value = createAuth();
+ uploadQueueState.value.items = [];
+ uploadQueueActionsState.value = [];
+ });
+
+ it("shows native upload entry points", async () => {
+ const tree = await renderTree(React.createElement(UploadScreen));
+
+ expect(getTextNodes(tree)).toContain("Import");
+ expect(getTextNodes(tree)).toContain("Upload File");
+ expect(getTextNodes(tree)).toContain("Browse Files");
+ expect(getTextNodes(tree)).toContain("Photos");
+ expect(getTextNodes(tree)).toContain("Import from Loom");
+ expect(getTextNodes(tree)).toContain("MP4, MOV, AVI, MKV, WebM, or M4V");
+ expect(hasStyle(tree, { height: 128, backgroundColor: "#f0f0f0" })).toBe(
+ true,
+ );
+ expect(
+ hasProps(tree, {
+ accessibilityHint: "Opens upload source options",
+ accessibilityLabel: "Choose upload source",
+ accessibilityState: { busy: false, disabled: false },
+ accessibilityValue: {
+ text: "MP4, MOV, AVI, MKV, WebM, or M4V",
+ },
+ }),
+ ).toBe(true);
+ expect(
+ hasProps(tree, {
+ accessibilityHint: "Opens Loom import in a browser sheet",
+ accessibilityLabel: "Open Loom import",
+ }),
+ ).toBe(true);
+ expect(
+ hasProps(tree, {
+ accessibilityHint: "Opens the native file picker",
+ accessibilityLabel: "Browse Files",
+ }),
+ ).toBe(true);
+ expect(
+ hasProps(tree, {
+ accessibilityHint: "Opens your photo library",
+ accessibilityLabel: "Photos",
+ }),
+ ).toBe(true);
+ });
+
+ it("opens the native iOS upload source sheet", async () => {
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const [uploadSource] = renderer.root.findAllByProps({
+ accessibilityLabel: "Choose upload source",
+ });
+ if (!uploadSource) throw new Error("Upload source button was not rendered");
+
+ const { ActionSheetIOS } = await import("react-native");
+ const showActionSheetWithOptions = vi.mocked(
+ ActionSheetIOS.showActionSheetWithOptions,
+ );
+ showActionSheetWithOptions.mockClear();
+
+ await act(async () => {
+ uploadSource.props.onPress();
+ });
+
+ expect(showActionSheetWithOptions).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cancelButtonIndex: 3,
+ options: ["Browse Files", "Photos", "Import from Loom", "Cancel"],
+ tintColor: "#0d74ce",
+ title: "Upload File",
+ userInterfaceStyle: "light",
+ }),
+ expect.any(Function),
+ );
+
+ const [, callback] = showActionSheetWithOptions.mock.calls[0] ?? [];
+ if (!callback) throw new Error("Upload source callback was not set");
+ const WebBrowser = await import("expo-web-browser");
+ const openBrowserAsync = vi.mocked(WebBrowser.openBrowserAsync);
+ openBrowserAsync.mockClear();
+
+ await act(async () => {
+ callback(2);
+ });
+
+ expect(openBrowserAsync).toHaveBeenCalledWith(
+ "https://cap.so/dashboard/import/loom",
+ );
+ });
+
+ it("opens Loom import in the native browser sheet", async () => {
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const [loomAction] = renderer.root.findAllByProps({
+ accessibilityLabel: "Import from Loom",
+ });
+ const [loomImport] = renderer.root.findAllByProps({
+ accessibilityLabel: "Open Loom import",
+ });
+ if (!loomAction) throw new Error("Loom upload action was not rendered");
+ if (!loomImport) throw new Error("Loom import card was not rendered");
+
+ const WebBrowser = await import("expo-web-browser");
+ const openBrowserAsync = vi.mocked(WebBrowser.openBrowserAsync);
+ openBrowserAsync.mockClear();
+
+ expect(loomAction.props.accessibilityHint).toBe(
+ "Opens Loom import in a browser sheet",
+ );
+
+ await act(async () => {
+ loomAction.props.onPress();
+ });
+
+ expect(openBrowserAsync).toHaveBeenCalledWith(
+ "https://cap.so/dashboard/import/loom",
+ );
+ openBrowserAsync.mockClear();
+
+ await act(async () => {
+ loomImport.props.onPress();
+ });
+
+ expect(openBrowserAsync).toHaveBeenCalledWith(
+ "https://cap.so/dashboard/import/loom",
+ );
+ });
+
+ it("shows Loom import failures on the Loom card", async () => {
+ const WebBrowser = await import("expo-web-browser");
+ const openBrowserAsync = vi.mocked(WebBrowser.openBrowserAsync);
+ openBrowserAsync.mockClear();
+ openBrowserAsync.mockRejectedValueOnce(new Error("Loom unavailable"));
+
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const [loomImport] = renderer.root.findAllByProps({
+ accessibilityLabel: "Open Loom import",
+ });
+ if (!loomImport) throw new Error("Loom import card was not rendered");
+
+ await act(async () => {
+ loomImport.props.onPress();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(getTextNodes(renderer.toJSON())).toContain(
+ "Loom import unavailable",
+ );
+ expect(getTextNodes(renderer.toJSON())).toContain("Loom unavailable");
+ const [failedLoomImport] = renderer.root.findAllByProps({
+ accessibilityLabel: "Loom import unavailable",
+ });
+ if (!failedLoomImport) throw new Error("Loom error card was not rendered");
+ expect(failedLoomImport.props.accessibilityHint).toBe(
+ "Retries Loom import",
+ );
+ expect(failedLoomImport.props.accessibilityValue).toEqual({
+ text: "Loom unavailable",
+ });
+ expect(failedLoomImport.props.accessibilityState).toEqual({
+ busy: false,
+ disabled: false,
+ });
+ const [retryLoomAction] = renderer.root.findAllByProps({
+ accessibilityLabel: "Retry Loom",
+ });
+ if (!retryLoomAction) throw new Error("Retry Loom action was not rendered");
+ expect(retryLoomAction.props.accessibilityHint).toBe("Loom unavailable");
+ expect(retryLoomAction.props.accessibilityValue).toEqual({
+ text: "Loom unavailable",
+ });
+ expect(retryLoomAction.props.disabled).toBe(false);
+ const [uploadSource] = renderer.root.findAllByProps({
+ accessibilityLabel: "Choose upload source",
+ });
+ if (!uploadSource) throw new Error("Upload source card was not rendered");
+ expect(uploadSource.props.accessibilityValue).toEqual({
+ text: "MP4, MOV, AVI, MKV, WebM, or M4V",
+ });
+ expect(hasStyle(renderer.toJSON(), { color: "#e5484d" })).toBe(true);
+ expect(
+ hasProps(renderer.toJSON(), {
+ accessibilityLiveRegion: "polite",
+ accessibilityRole: "alert",
+ }),
+ ).toBe(true);
+ });
+
+ it("locks stale Loom import actions while the browser sheet is opening", async () => {
+ const WebBrowser = await import("expo-web-browser");
+ const openBrowserAsync = vi.mocked(WebBrowser.openBrowserAsync);
+ let resolveBrowser:
+ | ((
+ value: Awaited<ReturnType<typeof WebBrowser.openBrowserAsync>>,
+ ) => void)
+ | null = null;
+ openBrowserAsync.mockClear();
+ openBrowserAsync.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveBrowser = resolve;
+ }),
+ );
+
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const [loomAction] = renderer.root.findAllByProps({
+ accessibilityLabel: "Import from Loom",
+ });
+ const [loomImport] = renderer.root.findAllByProps({
+ accessibilityLabel: "Open Loom import",
+ });
+ if (!loomAction) throw new Error("Loom upload action was not rendered");
+ if (!loomImport) throw new Error("Loom import card was not rendered");
+
+ await act(async () => {
+ void loomAction.props.onPress();
+ await Promise.resolve();
+ });
+
+ const [uploadSource] = renderer.root.findAllByProps({
+ accessibilityLabel: "Choose upload source",
+ });
+ const [loadingLoomImport] = renderer.root.findAllByProps({
+ accessibilityLabel: "Opening Loom",
+ });
+ const [browseButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Browse Files",
+ });
+ const [loadingLoomAction] = renderer.root.findAllByProps({
+ accessibilityLabel: "Import from Loom",
+ });
+ if (!uploadSource) throw new Error("Upload source button was not rendered");
+ if (!browseButton) throw new Error("Browse Files button was not rendered");
+ if (!loadingLoomAction)
+ throw new Error("Loom upload action was not rendered");
+ if (!loadingLoomImport)
+ throw new Error("Loom import card was not rendered");
+
+ const loadingText = getTextNodes(renderer.toJSON());
+ expect(loadingText.filter((item) => item === "Opening Loom")).toHaveLength(
+ 1,
+ );
+ expect(getTextNodes(renderer.toJSON())).not.toContain("Opening Loom...");
+ expect(
+ loadingText.filter(
+ (item) => item === "Continue in the browser sheet to import from Loom.",
+ ),
+ ).toHaveLength(1);
+ expect(uploadSource.props.accessibilityHint).toBe("Loom import is opening");
+ expect(uploadSource.props.accessibilityValue).toEqual({
+ text: "Opening Loom import",
+ });
+ expect(uploadSource.props.accessibilityState).toEqual({
+ busy: true,
+ disabled: true,
+ });
+ expect(browseButton.props.disabled).toBe(true);
+ expect(browseButton.props.accessibilityHint).toBe("Loom import is opening");
+ expect(browseButton.props.accessibilityValue).toEqual({
+ text: "Opening Loom import",
+ });
+ expect(loadingLoomAction.props.accessibilityHint).toBe(
+ "Loom import is opening",
+ );
+ expect(loadingLoomAction.props.accessibilityValue).toEqual({
+ text: "Opening Loom import",
+ });
+ expect(loadingLoomAction.props.loading).toBe(true);
+ expect(loadingLoomAction.props.disabled).toBe(false);
+ expect(loadingLoomImport.props.accessibilityHint).toBe(
+ "Loom import is opening",
+ );
+ expect(loadingLoomImport.props.accessibilityValue).toEqual({
+ text: "Opening Loom import",
+ });
+ expect(loadingLoomImport.props.disabled).toBe(true);
+ expect(openBrowserAsync).toHaveBeenCalledTimes(1);
+
+ openBrowserAsync.mockClear();
+
+ await act(async () => {
+ loomAction.props.onPress();
+ loomImport.props.onPress();
+ uploadSource.props.onPress();
+ await Promise.resolve();
+ });
+
+ expect(openBrowserAsync).not.toHaveBeenCalled();
+
+ await act(async () => {
+ resolveBrowser?.({
+ type: "dismiss",
+ } as Awaited<ReturnType<typeof WebBrowser.openBrowserAsync>>);
+ await Promise.resolve();
+ });
+ });
+
+ it("locks upload sources while the file picker is opening", async () => {
+ const DocumentPicker = await import("expo-document-picker");
+ let resolvePicker:
+ | ((
+ value: Awaited<ReturnType<typeof DocumentPicker.getDocumentAsync>>,
+ ) => void)
+ | null = null;
+ vi.mocked(DocumentPicker.getDocumentAsync).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolvePicker = resolve;
+ }),
+ );
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const [browseButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Browse Files",
+ });
+ if (!browseButton) throw new Error("Browse Files button was not rendered");
+
+ await act(async () => {
+ void browseButton.props.onPress();
+ await Promise.resolve();
+ });
+
+ const [uploadSource] = renderer.root.findAllByProps({
+ accessibilityLabel: "Opening Files",
+ });
+ const [loadingBrowseButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Browse Files",
+ });
+ const [photosButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Photos",
+ });
+ const [loomAction] = renderer.root.findAllByProps({
+ accessibilityLabel: "Import from Loom",
+ });
+ const [loomImport] = renderer.root.findAllByProps({
+ accessibilityLabel: "Open Loom import",
+ });
+ if (
+ !uploadSource ||
+ !loadingBrowseButton ||
+ !photosButton ||
+ !loomAction ||
+ !loomImport
+ ) {
+ throw new Error("Upload source controls were not rendered");
+ }
+
+ expect(getTextNodes(renderer.toJSON())).toContain("Opening Files");
+ expect(getTextNodes(renderer.toJSON())).not.toContain("Opening Files...");
+ expect(getTextNodes(renderer.toJSON())).toContain(
+ "Choose a video from Files.",
+ );
+ expect(uploadSource.props.accessibilityHint).toBe(
+ "Upload source picker is opening",
+ );
+ expect(uploadSource.props.accessibilityValue).toEqual({
+ text: "Opening native file picker",
+ });
+ expect(uploadSource.props.accessibilityState).toEqual({
+ busy: true,
+ disabled: true,
+ });
+ expect(uploadSource.props.disabled).toBe(true);
+ expect(resolveStyle(uploadSource.props.style)).toMatchObject({
+ opacity: 0.58,
+ });
+ expect(loadingBrowseButton.props.loading).toBe(true);
+ expect(loadingBrowseButton.props.accessibilityHint).toBe(
+ "Upload source picker is opening",
+ );
+ expect(loadingBrowseButton.props.accessibilityValue).toEqual({
+ text: "Opening native file picker",
+ });
+ expect(photosButton.props.accessibilityHint).toBe(
+ "Another upload source is opening",
+ );
+ expect(photosButton.props.accessibilityValue).toEqual({
+ text: "Opening native file picker",
+ });
+ expect(photosButton.props.disabled).toBe(true);
+ expect(loomAction.props.accessibilityHint).toBe(
+ "Another upload source is opening",
+ );
+ expect(loomAction.props.accessibilityValue).toEqual({
+ text: "Opening native file picker",
+ });
+ expect(loomAction.props.disabled).toBe(true);
+ expect(loomImport.props.accessibilityHint).toBe(
+ "Upload source picker is opening",
+ );
+ expect(loomImport.props.accessibilityValue).toEqual({
+ text: "Opening native file picker",
+ });
+ expect(loomImport.props.disabled).toBe(true);
+
+ const { ActionSheetIOS } = await import("react-native");
+ const showActionSheetWithOptions = vi.mocked(
+ ActionSheetIOS.showActionSheetWithOptions,
+ );
+ const ImagePicker = await import("expo-image-picker");
+ const requestMediaLibraryPermissionsAsync = vi.mocked(
+ ImagePicker.requestMediaLibraryPermissionsAsync,
+ );
+ const WebBrowser = await import("expo-web-browser");
+ const openBrowserAsync = vi.mocked(WebBrowser.openBrowserAsync);
+ showActionSheetWithOptions.mockClear();
+ requestMediaLibraryPermissionsAsync.mockClear();
+ openBrowserAsync.mockClear();
+
+ await act(async () => {
+ uploadSource.props.onPress();
+ photosButton.props.onPress();
+ loomAction.props.onPress();
+ loomImport.props.onPress();
+ });
+
+ expect(showActionSheetWithOptions).not.toHaveBeenCalled();
+ expect(requestMediaLibraryPermissionsAsync).not.toHaveBeenCalled();
+ expect(openBrowserAsync).not.toHaveBeenCalled();
+ expect(DocumentPicker.getDocumentAsync).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ resolvePicker?.({
+ assets: null,
+ canceled: true,
+ } as Awaited<ReturnType<typeof DocumentPicker.getDocumentAsync>>);
+ await Promise.resolve();
+ });
+ });
+
+ it("shows the active Photos source as loading while the photo picker is opening", async () => {
+ const ImagePicker = await import("expo-image-picker");
+ const requestMediaLibraryPermissionsAsync = vi.mocked(
+ ImagePicker.requestMediaLibraryPermissionsAsync,
+ );
+ let resolvePermission:
+ | ((
+ value: Awaited<
+ ReturnType<typeof ImagePicker.requestMediaLibraryPermissionsAsync>
+ >,
+ ) => void)
+ | null = null;
+ requestMediaLibraryPermissionsAsync.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolvePermission = resolve;
+ }),
+ );
+ const { ActionSheetIOS } = await import("react-native");
+ const showActionSheetWithOptions = vi.mocked(
+ ActionSheetIOS.showActionSheetWithOptions,
+ );
+ showActionSheetWithOptions.mockClear();
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const [photosButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Photos",
+ });
+ if (!photosButton) throw new Error("Photos button was not rendered");
+
+ await act(async () => {
+ void photosButton.props.onPress();
+ await Promise.resolve();
+ });
+
+ const [uploadSource] = renderer.root.findAllByProps({
+ accessibilityLabel: "Opening Photos",
+ });
+ const [browseButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Browse Files",
+ });
+ const [loadingPhotosButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Photos",
+ });
+ const [loomAction] = renderer.root.findAllByProps({
+ accessibilityLabel: "Import from Loom",
+ });
+ const [loomImport] = renderer.root.findAllByProps({
+ accessibilityLabel: "Open Loom import",
+ });
+ if (
+ !uploadSource ||
+ !browseButton ||
+ !loadingPhotosButton ||
+ !loomAction ||
+ !loomImport
+ ) {
+ throw new Error("Upload source controls were not rendered");
+ }
+
+ expect(getTextNodes(renderer.toJSON())).toContain("Opening Photos");
+ expect(getTextNodes(renderer.toJSON())).not.toContain("Opening Photos...");
+ expect(getTextNodes(renderer.toJSON())).toContain(
+ "Choose a video from Photos.",
+ );
+ expect(uploadSource.props.accessibilityHint).toBe(
+ "Upload source picker is opening",
+ );
+ expect(uploadSource.props.accessibilityValue).toEqual({
+ text: "Opening native photo picker",
+ });
+ expect(uploadSource.props.accessibilityState).toEqual({
+ busy: true,
+ disabled: true,
+ });
+ expect(uploadSource.props.disabled).toBe(true);
+ expect(resolveStyle(uploadSource.props.style)).toMatchObject({
+ opacity: 0.58,
+ });
+ expect(browseButton.props.accessibilityHint).toBe(
+ "Another upload source is opening",
+ );
+ expect(browseButton.props.accessibilityValue).toEqual({
+ text: "Opening native photo picker",
+ });
+ expect(browseButton.props.disabled).toBe(true);
+ expect(loadingPhotosButton.props.accessibilityHint).toBe(
+ "Upload source picker is opening",
+ );
+ expect(loadingPhotosButton.props.accessibilityValue).toEqual({
+ text: "Opening native photo picker",
+ });
+ expect(loadingPhotosButton.props.loading).toBe(true);
+ expect(loadingPhotosButton.props.disabled).toBe(false);
+ expect(loomAction.props.accessibilityHint).toBe(
+ "Another upload source is opening",
+ );
+ expect(loomAction.props.accessibilityValue).toEqual({
+ text: "Opening native photo picker",
+ });
+ expect(loomAction.props.disabled).toBe(true);
+ expect(loomImport.props.accessibilityHint).toBe(
+ "Upload source picker is opening",
+ );
+ expect(loomImport.props.accessibilityValue).toEqual({
+ text: "Opening native photo picker",
+ });
+ expect(loomImport.props.disabled).toBe(true);
+
+ await act(async () => {
+ resolvePermission?.({
+ granted: false,
+ } as Awaited<
+ ReturnType<typeof ImagePicker.requestMediaLibraryPermissionsAsync>
+ >);
+ await Promise.resolve();
+ });
+
+ expect(showActionSheetWithOptions).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cancelButtonIndex: 1,
+ message: "Allow Cap to read videos from Photos before uploading.",
+ options: ["Open Settings", "Cancel"],
+ title: "Photos access needed",
+ }),
+ expect.any(Function),
+ );
+ expect(getTextNodes(renderer.toJSON())).toContain(
+ "Upload source unavailable",
+ );
+ expect(getTextNodes(renderer.toJSON())).toContain(
+ "Allow Cap to read videos from Photos before uploading.",
+ );
+ const [failedUploadSource] = renderer.root.findAllByProps({
+ accessibilityLabel: "Upload source unavailable",
+ });
+ const [retryPhotosButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Retry Photos",
+ });
+ if (!failedUploadSource)
+ throw new Error("Upload source error state was not rendered");
+ if (!retryPhotosButton)
+ throw new Error("Retry Photos button was not rendered");
+ expect(failedUploadSource.props.accessibilityValue).toEqual({
+ text: "Allow Cap to read videos from Photos before uploading.",
+ });
+ expect(retryPhotosButton.props.accessibilityHint).toBe(
+ "Allow Cap to read videos from Photos before uploading.",
+ );
+ expect(retryPhotosButton.props.accessibilityValue).toEqual({
+ text: "Allow Cap to read videos from Photos before uploading.",
+ });
+ expect(retryPhotosButton.props.disabled).toBe(false);
+ });
+
+ it("deduplicates stale upload source actions while the file picker is opening", async () => {
+ const DocumentPicker = await import("expo-document-picker");
+ const getDocumentAsync = vi.mocked(DocumentPicker.getDocumentAsync);
+ let resolvePicker:
+ | ((
+ value: Awaited<ReturnType<typeof DocumentPicker.getDocumentAsync>>,
+ ) => void)
+ | null = null;
+ getDocumentAsync.mockClear();
+ getDocumentAsync.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolvePicker = resolve;
+ }),
+ );
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const [uploadSource] = renderer.root.findAllByProps({
+ accessibilityLabel: "Choose upload source",
+ });
+ const [browseButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Browse Files",
+ });
+ const [photosButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Photos",
+ });
+ const [loomAction] = renderer.root.findAllByProps({
+ accessibilityLabel: "Import from Loom",
+ });
+ const [loomImport] = renderer.root.findAllByProps({
+ accessibilityLabel: "Open Loom import",
+ });
+ if (
+ !uploadSource ||
+ !browseButton ||
+ !photosButton ||
+ !loomAction ||
+ !loomImport
+ ) {
+ throw new Error("Upload source controls were not rendered");
+ }
+
+ await act(async () => {
+ void browseButton.props.onPress();
+ await Promise.resolve();
+ });
+
+ const { ActionSheetIOS } = await import("react-native");
+ const showActionSheetWithOptions = vi.mocked(
+ ActionSheetIOS.showActionSheetWithOptions,
+ );
+ const ImagePicker = await import("expo-image-picker");
+ const requestMediaLibraryPermissionsAsync = vi.mocked(
+ ImagePicker.requestMediaLibraryPermissionsAsync,
+ );
+ const WebBrowser = await import("expo-web-browser");
+ const openBrowserAsync = vi.mocked(WebBrowser.openBrowserAsync);
+ showActionSheetWithOptions.mockClear();
+ requestMediaLibraryPermissionsAsync.mockClear();
+ openBrowserAsync.mockClear();
+
+ await act(async () => {
+ uploadSource.props.onPress();
+ browseButton.props.onPress();
+ photosButton.props.onPress();
+ loomAction.props.onPress();
+ loomImport.props.onPress();
+ await Promise.resolve();
+ });
+
+ expect(getDocumentAsync).toHaveBeenCalledTimes(1);
+ expect(showActionSheetWithOptions).not.toHaveBeenCalled();
+ expect(requestMediaLibraryPermissionsAsync).not.toHaveBeenCalled();
+ expect(openBrowserAsync).not.toHaveBeenCalled();
+
+ await act(async () => {
+ resolvePicker?.({
+ assets: null,
+ canceled: true,
+ } as Awaited<ReturnType<typeof DocumentPicker.getDocumentAsync>>);
+ await Promise.resolve();
+ });
+ });
+
+ it("locks Loom import while a device upload is active", async () => {
+ const DocumentPicker = await import("expo-document-picker");
+ const { runMobileUpload } = await import("@/uploads/runMobileUpload");
+ const uploadStartedAt = 1_763_440_800_000;
+ const dateNow = vi.spyOn(Date, "now").mockReturnValue(uploadStartedAt);
+ let resolveUpload:
+ | ((value: Awaited<ReturnType<typeof runMobileUpload>>) => void)
+ | null = null;
+ uploadQueueState.value.items = [
+ {
+ capId: null,
+ contentType: "video/mp4",
+ createdAt: "2026-05-18T10:00:00.000Z",
+ error: null,
+ fileName: "launch-review.mp4",
+ folderId: null,
+ id: `${uploadStartedAt}-launch-review.mp4`,
+ localUri: "file:///tmp/launch-review.mp4",
+ organizationId: "org_123",
+ progress: 0,
+ processingMessage: null,
+ rawFileKey: null,
+ size: 12_400_000,
+ status: "queued",
+ updatedAt: "2026-05-18T10:00:00.000Z",
+ },
+ ];
+ vi.mocked(DocumentPicker.getDocumentAsync).mockResolvedValueOnce({
+ assets: [
+ {
+ mimeType: "video/mp4",
+ name: "launch-review.mp4",
+ size: 12_400_000,
+ uri: "file:///tmp/launch-review.mp4",
+ },
+ ],
+ canceled: false,
+ } as Awaited<ReturnType<typeof DocumentPicker.getDocumentAsync>>);
+ vi.mocked(runMobileUpload).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveUpload = resolve;
+ }),
+ );
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const [browseButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Browse Files",
+ });
+ if (!browseButton) throw new Error("Browse Files button was not rendered");
+
+ await act(async () => {
+ void browseButton.props.onPress();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ const [uploadSource] = renderer.root.findAllByProps({
+ accessibilityLabel: "Choose upload source",
+ });
+ const [loomImport] = renderer.root.findAllByProps({
+ accessibilityLabel: "Open Loom import",
+ });
+ const [activeBrowseButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Browse Files",
+ });
+ const [photosButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Photos",
+ });
+ const [loomAction] = renderer.root.findAllByProps({
+ accessibilityLabel: "Import from Loom",
+ });
+ if (!uploadSource) throw new Error("Upload source button was not rendered");
+ if (!loomImport) throw new Error("Loom import card was not rendered");
+ if (!activeBrowseButton)
+ throw new Error("Browse Files button was not rendered");
+ if (!photosButton) throw new Error("Photos button was not rendered");
+ if (!loomAction) throw new Error("Loom upload action was not rendered");
+ const WebBrowser = await import("expo-web-browser");
+ const openBrowserAsync = vi.mocked(WebBrowser.openBrowserAsync);
+ openBrowserAsync.mockClear();
+
+ expect(getTextNodes(renderer.toJSON())).toContain("Upload File");
+ expect(getTextNodes(renderer.toJSON())).not.toContain("Preparing upload");
+ expect(getTextNodes(renderer.toJSON()).join("")).toContain(
+ "Preparing upload · 12 MB",
+ );
+ expect(getTextNodes(renderer.toJSON())).toContain("Import from Loom");
+ expect(getTextNodes(renderer.toJSON())).toContain(
+ "Finish preparing this upload before importing from Loom.",
+ );
+ expect(uploadSource.props.accessibilityHint).toBe("Preparing upload");
+ expect(uploadSource.props.accessibilityValue).toEqual({
+ text: "Preparing upload launch-review.mp4",
+ });
+ expect(uploadSource.props.disabled).toBe(true);
+ expect(resolveStyle(uploadSource.props.style)).toMatchObject({
+ opacity: 0.58,
+ });
+ expect(activeBrowseButton.props.loading).toBe(false);
+ expect(activeBrowseButton.props.accessibilityHint).toBe("Preparing upload");
+ expect(activeBrowseButton.props.accessibilityValue).toEqual({
+ text: "Preparing upload launch-review.mp4",
+ });
+ expect(activeBrowseButton.props.disabled).toBe(true);
+ expect(photosButton.props.loading).toBe(false);
+ expect(photosButton.props.accessibilityHint).toBe("Preparing upload");
+ expect(photosButton.props.accessibilityValue).toEqual({
+ text: "Preparing upload launch-review.mp4",
+ });
+ expect(photosButton.props.disabled).toBe(true);
+ expect(loomAction.props.loading).toBe(false);
+ expect(loomAction.props.accessibilityHint).toBe("Preparing upload");
+ expect(loomAction.props.accessibilityValue).toEqual({
+ text: "Preparing upload launch-review.mp4",
+ });
+ expect(loomAction.props.disabled).toBe(true);
+ expect(loomImport.props.accessibilityHint).toBe("Preparing upload");
+ expect(loomImport.props.accessibilityValue).toEqual({
+ text: "Preparing upload launch-review.mp4",
+ });
+ expect(loomImport.props.accessibilityState).toEqual({
+ busy: true,
+ disabled: true,
+ });
+ expect(loomImport.props.disabled).toBe(true);
+
+ await act(async () => {
+ loomImport.props.onPress();
+ });
+
+ expect(openBrowserAsync).not.toHaveBeenCalled();
+
+ await act(async () => {
+ resolveUpload?.({
+ id: "video_123",
+ } as Awaited<ReturnType<typeof runMobileUpload>>);
+ await Promise.resolve();
+ });
+ dateNow.mockRestore();
+ });
+
+ it("locks inactive upload queue rows while a device upload is active", async () => {
+ uploadQueueState.value.items = [
+ {
+ capId: null,
+ contentType: "video/mp4",
+ createdAt: "2026-05-18T10:00:00.000Z",
+ error: "Network unavailable",
+ fileName: "failed-upload.mp4",
+ folderId: null,
+ id: "failed-upload",
+ localUri: "file:///tmp/failed-upload.mp4",
+ organizationId: "org_123",
+ progress: 0.42,
+ rawFileKey: null,
+ size: 124_000,
+ durationSeconds: 125,
+ status: "failed",
+ updatedAt: "2026-05-18T10:00:00.000Z",
+ },
+ ];
+ const DocumentPicker = await import("expo-document-picker");
+ const { runMobileUpload } = await import("@/uploads/runMobileUpload");
+ let resolveUpload:
+ | ((value: Awaited<ReturnType<typeof runMobileUpload>>) => void)
+ | null = null;
+ vi.mocked(DocumentPicker.getDocumentAsync).mockResolvedValueOnce({
+ assets: [
+ {
+ mimeType: "video/mp4",
+ name: "launch-review.mp4",
+ size: 12_400_000,
+ uri: "file:///tmp/launch-review.mp4",
+ },
+ ],
+ canceled: false,
+ } as Awaited<ReturnType<typeof DocumentPicker.getDocumentAsync>>);
+ vi.mocked(runMobileUpload).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveUpload = resolve;
+ }),
+ );
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const [browseButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Browse Files",
+ });
+ if (!browseButton) throw new Error("Browse Files button was not rendered");
+
+ await act(async () => {
+ void browseButton.props.onPress();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ const [queueRow] = renderer.root.findAllByProps({
+ accessibilityLabel: "Upload failed-upload.mp4",
+ });
+ const [retryButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Retry upload failed-upload.mp4",
+ });
+ const queueMenus = renderer.root.findAllByProps({
+ accessibilityLabel: "More actions for failed-upload.mp4",
+ });
+ const [queueMenu] = queueMenus;
+ if (!queueRow) throw new Error("Upload queue row was not rendered");
+ if (!retryButton) throw new Error("Retry button was not rendered");
+ if (!queueMenu) throw new Error("Upload queue menu was not rendered");
+
+ expect(queueRow.props.accessibilityHint).toBe(
+ "Another upload is in progress",
+ );
+ expect(queueRow.props.accessibilityState).toEqual({
+ busy: false,
+ disabled: true,
+ });
+ expect(queueRow.props.accessibilityValue).toEqual({
+ text: "Preparing upload launch-review.mp4",
+ });
+ expect(queueRow.props.disabled).toBe(true);
+ expect(retryButton.props.disabled).toBe(true);
+ expect(retryButton.props.accessibilityHint).toBe(
+ "Another upload is in progress",
+ );
+ expect(retryButton.props.accessibilityValue).toEqual({
+ text: "Preparing upload launch-review.mp4",
+ });
+ expect(queueMenu.props.accessibilityHint).toBe(
+ "Another upload is in progress",
+ );
+ expect(queueMenu.props.accessibilityState).toEqual({
+ busy: false,
+ disabled: true,
+ });
+ expect(queueMenu.props.accessibilityValue).toEqual({
+ text: "Preparing upload launch-review.mp4",
+ });
+ expect(queueMenu.props.disabled).toBe(true);
+
+ const { ActionSheetIOS } = await import("react-native");
+ const showActionSheetWithOptions = vi.mocked(
+ ActionSheetIOS.showActionSheetWithOptions,
+ );
+ showActionSheetWithOptions.mockClear();
+
+ await act(async () => {
+ queueRow.props.onPress();
+ retryButton.props.onPress({ stopPropagation: vi.fn() });
+ queueMenu.props.onPress({ stopPropagation: vi.fn() });
+ });
+
+ expect(showActionSheetWithOptions).not.toHaveBeenCalled();
+ expect(uploadQueueActionsState.value).not.toContainEqual(
+ expect.objectContaining({
+ id: "failed-upload",
+ type: "retry",
+ }),
+ );
+
+ await act(async () => {
+ resolveUpload?.({
+ id: "video_123",
+ } as Awaited<ReturnType<typeof runMobileUpload>>);
+ await Promise.resolve();
+ });
+ });
+
+ it("locks stale upload queue view actions while a device upload is active", async () => {
+ uploadQueueState.value.items = [
+ {
+ capId: "video_complete",
+ contentType: "video/mp4",
+ createdAt: "2026-05-18T10:00:00.000Z",
+ error: null,
+ fileName: "processed-upload.mp4",
+ folderId: null,
+ id: "processed-upload",
+ localUri: "file:///tmp/processed-upload.mp4",
+ organizationId: "org_123",
+ progress: 1,
+ rawFileKey: "raw-file-key",
+ size: 124_000,
+ durationSeconds: 125,
+ status: "complete",
+ updatedAt: "2026-05-18T10:00:00.000Z",
+ },
+ ];
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const [queueRow] = renderer.root.findAllByProps({
+ accessibilityLabel: "Upload processed-upload.mp4",
+ });
+ const [queueMenu] = renderer.root.findAllByProps({
+ accessibilityLabel: "More actions for processed-upload.mp4",
+ });
+ const [viewButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "View upload processed-upload.mp4",
+ });
+ if (!queueRow) throw new Error("Upload queue row was not rendered");
+ if (!queueMenu) throw new Error("Upload queue menu was not rendered");
+ if (!viewButton) throw new Error("View button was not rendered");
+ expect(queueRow.props.accessibilityHint).toBe(
+ "Ready to view. Opens upload actions",
+ );
+ expect(queueMenu.props.accessibilityHint).toBe(
+ "Opens view and remove actions",
+ );
+ expect(queueRow.props.accessibilityValue).toEqual({
+ text: "Ready to view · 124 KB · 2 mins",
+ });
+
+ const { ActionSheetIOS } = await import("react-native");
+ const showActionSheetWithOptions = vi.mocked(
+ ActionSheetIOS.showActionSheetWithOptions,
+ );
+ showActionSheetWithOptions.mockClear();
+
+ await act(async () => {
+ queueRow.props.onPress();
+ });
+
+ const [, callback] = showActionSheetWithOptions.mock.calls[0] ?? [];
+ if (!callback) throw new Error("Upload queue action callback was not set");
+
+ const DocumentPicker = await import("expo-document-picker");
+ const { runMobileUpload } = await import("@/uploads/runMobileUpload");
+ let resolveUpload:
+ | ((value: Awaited<ReturnType<typeof runMobileUpload>>) => void)
+ | null = null;
+ vi.mocked(DocumentPicker.getDocumentAsync).mockResolvedValueOnce({
+ assets: [
+ {
+ mimeType: "video/mp4",
+ name: "launch-review.mp4",
+ size: 12_400_000,
+ uri: "file:///tmp/launch-review.mp4",
+ },
+ ],
+ canceled: false,
+ } as Awaited<ReturnType<typeof DocumentPicker.getDocumentAsync>>);
+ vi.mocked(runMobileUpload).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveUpload = resolve;
+ }),
+ );
+ const [browseButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Browse Files",
+ });
+ if (!browseButton) throw new Error("Browse Files button was not rendered");
+
+ await act(async () => {
+ void browseButton.props.onPress();
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ const { router } = await import("expo-router");
+ const push = vi.mocked(router.push);
+ push.mockClear();
+ const [lockedViewButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "View upload processed-upload.mp4",
+ });
+ const [lockedQueueMenu] = renderer.root.findAllByProps({
+ accessibilityLabel: "More actions for processed-upload.mp4",
+ });
+ if (!lockedViewButton) throw new Error("View button was not rendered");
+ if (!lockedQueueMenu) throw new Error("Upload queue menu was not rendered");
+ expect(lockedViewButton.props.accessibilityHint).toBe(
+ "Another upload is in progress",
+ );
+ expect(lockedViewButton.props.accessibilityValue).toEqual({
+ text: "Preparing upload launch-review.mp4",
+ });
+ expect(lockedViewButton.props.disabled).toBe(true);
+ expect(lockedQueueMenu.props.accessibilityHint).toBe(
+ "Another upload is in progress",
+ );
+ expect(lockedQueueMenu.props.accessibilityState).toEqual({
+ busy: false,
+ disabled: true,
+ });
+ expect(lockedQueueMenu.props.accessibilityValue).toEqual({
+ text: "Preparing upload launch-review.mp4",
+ });
+ expect(lockedQueueMenu.props.disabled).toBe(true);
+
+ showActionSheetWithOptions.mockClear();
+ await act(async () => {
+ viewButton.props.onPress({ stopPropagation: vi.fn() });
+ lockedQueueMenu.props.onPress({ stopPropagation: vi.fn() });
+ callback(0);
+ });
+
+ expect(push).not.toHaveBeenCalled();
+ expect(showActionSheetWithOptions).not.toHaveBeenCalled();
+
+ await act(async () => {
+ resolveUpload?.({
+ id: "video_123",
+ } as Awaited<ReturnType<typeof runMobileUpload>>);
+ await Promise.resolve();
+ });
+ });
+
+ it("announces processing upload queue rows with their current status", async () => {
+ uploadQueueState.value.items = [
+ {
+ capId: "video_processing",
+ contentType: "video/mp4",
+ createdAt: "2026-05-18T10:00:00.000Z",
+ error: null,
+ fileName: "processing-upload.mp4",
+ folderId: null,
+ id: "processing-upload",
+ localUri: "file:///tmp/processing-upload.mp4",
+ organizationId: "org_123",
+ progress: 0.42,
+ processingMessage: "Processing frames",
+ rawFileKey: "raw-file-key",
+ size: 124_000,
+ durationSeconds: 125,
+ status: "processing",
+ updatedAt: "2026-05-18T10:00:00.000Z",
+ },
+ ];
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const tree = renderer.toJSON();
+ const [queueRow] = renderer.root.findAllByProps({
+ accessibilityLabel: "Upload processing-upload.mp4",
+ });
+ const [queueMenu] = renderer.root.findAllByProps({
+ accessibilityLabel: "More actions for processing-upload.mp4",
+ });
+ const [viewButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "View upload processing-upload.mp4",
+ });
+ if (!queueRow) throw new Error("Processing upload row was not rendered");
+ if (!queueMenu) throw new Error("Upload queue menu was not rendered");
+ if (!viewButton) throw new Error("View button was not rendered");
+
+ expect(getTextNodes(tree).join("")).toContain(
+ "Processing frames · 124 KB · 2 mins",
+ );
+ expect(queueRow.props.accessibilityHint).toBe(
+ "Processing frames. Opens upload actions",
+ );
+ expect(queueMenu.props.accessibilityHint).toBe(
+ "Opens view and remove actions",
+ );
+ expect(queueRow.props.accessibilityValue).toEqual({
+ text: "Processing frames · 124 KB · 2 mins",
+ });
+ expect(
+ hasProps(tree, {
+ accessibilityLabel: "Upload progress for processing-upload.mp4",
+ accessibilityRole: "progressbar",
+ accessibilityValue: {
+ max: 100,
+ min: 0,
+ now: 42,
+ text: "42%",
+ },
+ }),
+ ).toBe(true);
+ expect(viewButton.props.accessibilityHint).toBe("Opens the uploaded Cap");
+ });
+
+ it("shows queued upload rows without premature progress", async () => {
+ uploadQueueState.value.items = [
+ {
+ capId: null,
+ contentType: "video/mp4",
+ createdAt: "2026-05-18T10:00:00.000Z",
+ error: null,
+ fileName: "queued-upload.mp4",
+ folderId: null,
+ id: "queued-upload",
+ localUri: "file:///tmp/queued-upload.mp4",
+ organizationId: "org_123",
+ progress: 0,
+ processingMessage: null,
+ rawFileKey: null,
+ size: 124_000,
+ durationSeconds: 125,
+ status: "queued",
+ updatedAt: "2026-05-18T10:00:00.000Z",
+ },
+ ];
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const tree = renderer.toJSON();
+ const [queueRow] = renderer.root.findAllByProps({
+ accessibilityLabel: "Upload queued-upload.mp4",
+ });
+ const [queueMenu] = renderer.root.findAllByProps({
+ accessibilityLabel: "More actions for queued-upload.mp4",
+ });
+ if (!queueRow) throw new Error("Queued upload row was not rendered");
+ if (!queueMenu) throw new Error("Upload queue menu was not rendered");
+
+ expect(getTextNodes(tree).join("")).toContain("Queued · 124 KB · 2 mins");
+ expect(queueRow.props.accessibilityHint).toBe(
+ "Queued. Opens upload actions",
+ );
+ expect(queueRow.props.accessibilityValue).toEqual({
+ text: "Queued · 124 KB · 2 mins",
+ });
+ expect(queueMenu.props.accessibilityHint).toBe("Opens remove action");
+ expect(
+ hasProps(tree, {
+ accessibilityLabel: "Upload progress for queued-upload.mp4",
+ accessibilityRole: "progressbar",
+ }),
+ ).toBe(false);
+
+ const { ActionSheetIOS } = await import("react-native");
+ const showActionSheetWithOptions = vi.mocked(
+ ActionSheetIOS.showActionSheetWithOptions,
+ );
+ showActionSheetWithOptions.mockClear();
+
+ await act(async () => {
+ queueMenu.props.onPress({ stopPropagation: vi.fn() });
+ });
+
+ expect(showActionSheetWithOptions).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cancelButtonIndex: 1,
+ destructiveButtonIndex: 0,
+ message: "Queued · 124 KB · 2 mins",
+ options: ["Remove from Queue", "Cancel"],
+ title: "queued-upload.mp4",
+ userInterfaceStyle: "light",
+ }),
+ expect.any(Function),
+ );
+ });
+
+ it("keeps uploaded files processing when the library refresh fails", async () => {
+ const auth = createAuth();
+ auth.refresh = vi.fn(() => Promise.reject(new Error("Refresh failed")));
+ authState.value = auth;
+ const DocumentPicker = await import("expo-document-picker");
+ const { runMobileUpload } = await import("@/uploads/runMobileUpload");
+ vi.mocked(DocumentPicker.getDocumentAsync).mockResolvedValueOnce({
+ assets: [
+ {
+ mimeType: "video/mp4",
+ name: "launch-review.mp4",
+ size: 12_400_000,
+ uri: "file:///tmp/launch-review.mp4",
+ },
+ ],
+ canceled: false,
+ } as Awaited<ReturnType<typeof DocumentPicker.getDocumentAsync>>);
+ vi.mocked(runMobileUpload).mockResolvedValueOnce({
+ id: "video_123",
+ } as Awaited<ReturnType<typeof runMobileUpload>>);
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const [browseButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Browse Files",
+ });
+ if (!browseButton) throw new Error("Browse Files button was not rendered");
+
+ await act(async () => {
+ await browseButton.props.onPress();
+ await Promise.resolve();
+ });
+
+ expect(uploadQueueActionsState.value).toContainEqual(
+ expect.objectContaining({
+ progress: 0,
+ type: "processing",
+ }),
+ );
+ expect(
+ uploadQueueActionsState.value.some(
+ (action) =>
+ typeof action === "object" &&
+ action !== null &&
+ "type" in action &&
+ action.type === "fail",
+ ),
+ ).toBe(false);
+ });
+
+ it("completes uploaded files when the final processing refresh fails", async () => {
+ vi.useFakeTimers();
+ try {
+ const auth = createAuth();
+ auth.refresh = vi.fn(() => Promise.reject(new Error("Refresh failed")));
+ auth.client.getCap = vi.fn(() =>
+ Promise.resolve({
+ cap: {
+ upload: null,
+ },
+ }),
+ );
+ authState.value = auth;
+ const DocumentPicker = await import("expo-document-picker");
+ const { runMobileUpload } = await import("@/uploads/runMobileUpload");
+ vi.mocked(DocumentPicker.getDocumentAsync).mockResolvedValueOnce({
+ assets: [
+ {
+ mimeType: "video/mp4",
+ name: "launch-review.mp4",
+ size: 12_400_000,
+ uri: "file:///tmp/launch-review.mp4",
+ },
+ ],
+ canceled: false,
+ } as Awaited<ReturnType<typeof DocumentPicker.getDocumentAsync>>);
+ vi.mocked(runMobileUpload).mockResolvedValueOnce({
+ id: "video_123",
+ } as Awaited<ReturnType<typeof runMobileUpload>>);
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const [browseButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Browse Files",
+ });
+ if (!browseButton)
+ throw new Error("Browse Files button was not rendered");
+
+ await act(async () => {
+ await browseButton.props.onPress();
+ await Promise.resolve();
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1500);
+ });
+
+ expect(auth.client.getCap).toHaveBeenCalledWith("video_123");
+ expect(auth.refresh).toHaveBeenCalledTimes(2);
+ expect(uploadQueueActionsState.value).toContainEqual(
+ expect.objectContaining({
+ type: "complete",
+ }),
+ );
+ expect(
+ uploadQueueActionsState.value.some(
+ (action) =>
+ typeof action === "object" &&
+ action !== null &&
+ "type" in action &&
+ action.type === "fail",
+ ),
+ ).toBe(false);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("opens the native iOS upload queue sheet", async () => {
+ uploadQueueState.value.items = [
+ {
+ capId: null,
+ contentType: "video/mp4",
+ createdAt: "2026-05-18T10:00:00.000Z",
+ error: "Network unavailable",
+ fileName: "failed-upload.mp4",
+ folderId: null,
+ id: "failed-upload",
+ localUri: "file:///tmp/failed-upload.mp4",
+ organizationId: "org_123",
+ progress: 0.42,
+ rawFileKey: null,
+ size: 124_000,
+ durationSeconds: 125,
+ status: "failed",
+ updatedAt: "2026-05-18T10:00:00.000Z",
+ },
+ ];
+ const renderer = await renderComponent(React.createElement(UploadScreen));
+ const tree = renderer.toJSON();
+ const [queueMenu] = renderer.root.findAllByProps({
+ accessibilityLabel: "More actions for failed-upload.mp4",
+ });
+ if (!queueMenu) throw new Error("Upload queue menu was not rendered");
+ const [queueRow] = renderer.root.findAllByProps({
+ accessibilityLabel: "Upload failed-upload.mp4",
+ });
+ if (!queueRow) throw new Error("Upload queue row was not rendered");
+ expect(getTextNodes(tree).join("")).toContain(
+ "Upload failed · Network unavailable · 124 KB · 2 mins",
+ );
+ expect(queueMenu.props.hitSlop).toBe(6);
+ expect(queueMenu.props.accessibilityHint).toBe(
+ "Opens retry and remove actions",
+ );
+ expect(
+ hasProps(tree, {
+ accessibilityHint: "Upload failed. Opens upload actions",
+ accessibilityLabel: "Upload failed-upload.mp4",
+ accessibilityState: { busy: false, disabled: false },
+ }),
+ ).toBe(true);
+ expect(queueRow.props.accessibilityValue).toEqual({
+ text: "Upload failed · Network unavailable · 124 KB · 2 mins",
+ });
+ expect(
+ hasProps(tree, {
+ accessibilityLabel: "Upload progress for failed-upload.mp4",
+ accessibilityRole: "progressbar",
+ }),
+ ).toBe(false);
+ expect(hasProp(tree, "accessibilityRole", "alert")).toBe(true);
+
+ const { ActionSheetIOS } = await import("react-native");
+ const showActionSheetWithOptions = vi.mocked(
+ ActionSheetIOS.showActionSheetWithOptions,
+ );
+ showActionSheetWithOptions.mockClear();
+
+ const menuStopPropagation = vi.fn();
+ await act(async () => {
+ queueMenu.props.onPress({ stopPropagation: menuStopPropagation });
+ });
+
+ expect(menuStopPropagation).toHaveBeenCalled();
+ expect(showActionSheetWithOptions).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cancelButtonIndex: 2,
+ destructiveButtonIndex: 1,
+ message: "Upload failed · Network unavailable · 124 KB · 2 mins",
+ options: ["Retry", "Remove from Queue", "Cancel"],
+ title: "failed-upload.mp4",
+ userInterfaceStyle: "light",
+ }),
+ expect.any(Function),
+ );
+ showActionSheetWithOptions.mockClear();
+
+ await act(async () => {
+ queueRow.props.onPress();
+ });
+
+ expect(showActionSheetWithOptions).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cancelButtonIndex: 2,
+ destructiveButtonIndex: 1,
+ message: "Upload failed · Network unavailable · 124 KB · 2 mins",
+ options: ["Retry", "Remove from Queue", "Cancel"],
+ title: "failed-upload.mp4",
+ userInterfaceStyle: "light",
+ }),
+ expect.any(Function),
+ );
+ });
+
+ it("announces picker errors as native alerts", async () => {
+ const DocumentPicker = await import("expo-document-picker");
+ vi.mocked(DocumentPicker.getDocumentAsync).mockRejectedValueOnce(
+ new Error("Files unavailable"),
+ );
+ const uploadRenderer = await renderComponent(
+ React.createElement(UploadScreen),
+ );
+ const [browseButton] = uploadRenderer.root.findAllByProps({
+ accessibilityLabel: "Browse Files",
+ });
+ if (!browseButton) throw new Error("Browse Files button was not rendered");
+
+ await act(async () => {
+ await browseButton.props.onPress();
+ });
+
+ expect(getTextNodes(uploadRenderer.toJSON())).toContain(
+ "Upload source unavailable",
+ );
+ expect(getTextNodes(uploadRenderer.toJSON())).toContain(
+ "Files unavailable",
+ );
+ const [uploadSource] = uploadRenderer.root.findAllByProps({
+ accessibilityLabel: "Upload source unavailable",
+ });
+ if (!uploadSource) throw new Error("Upload source button was not rendered");
+ expect(uploadSource.props.accessibilityHint).toBe(
+ "Retries upload source options",
+ );
+ expect(uploadSource.props.accessibilityValue).toEqual({
+ text: "Files unavailable",
+ });
+ const [retryFilesButton] = uploadRenderer.root.findAllByProps({
+ accessibilityLabel: "Retry Files",
+ });
+ if (!retryFilesButton)
+ throw new Error("Retry Files button was not rendered");
+ expect(retryFilesButton.props.accessibilityHint).toBe("Files unavailable");
+ expect(retryFilesButton.props.disabled).toBe(false);
+ const [loomImport] = uploadRenderer.root.findAllByProps({
+ accessibilityLabel: "Open Loom import",
+ });
+ if (!loomImport) throw new Error("Loom import card was not rendered");
+ expect(loomImport.props.accessibilityValue).toBeUndefined();
+ expect(hasStyle(uploadRenderer.toJSON(), { color: "#e5484d" })).toBe(true);
+ expect(
+ hasProps(uploadRenderer.toJSON(), {
+ accessibilityLiveRegion: "polite",
+ accessibilityRole: "alert",
+ }),
+ ).toBe(true);
+ });
+
+ it("shows dashboard import actions", async () => {
+ const tree = await renderTree(React.createElement(CapsScreen));
+ const text = getTextNodes(tree);
+
+ expect(text).toContain("My Caps");
+ expect(text.filter((item) => item === "New Folder").length).toBeGreaterThan(
+ 0,
+ );
+ expect(text).not.toContain("Record");
+ expect(
+ text.filter((item) => item === "Import Video").length,
+ ).toBeGreaterThan(0);
+ expect(hasStyle(tree, { marginBottom: 40 })).toBe(true);
+ expect(text.join("")).toContain("Hey Richie! Import your first Cap");
+ expect(hasProp(tree, "accessibilityLabel", "Cap logo")).toBe(true);
+ expect(
+ hasProps(tree, {
+ accessibilityHint: "Opens import options",
+ accessibilityLabel: "Import Video",
+ }),
+ ).toBe(true);
+ });
+
+ it("announces dashboard load errors with a retry action", async () => {
+ const auth = createAuth();
+ auth.client.listCaps = vi.fn(() =>
+ Promise.reject(new Error("Network unavailable")),
+ );
+ authState.value = auth;
+ const renderer = await renderComponent(React.createElement(CapsScreen));
+
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ const tree = renderer.toJSON();
+ const text = getTextNodes(tree);
+
+ expect(text).toContain("Unable to load Caps");
+ expect(text).toContain("Network unavailable");
+ expect(
+ hasProps(tree, {
+ accessibilityLabel: "Library error: Network unavailable",
+ accessibilityLiveRegion: "polite",
+ accessibilityRole: "alert",
+ }),
+ ).toBe(true);
+
+ const [retryButton] = renderer.root.findAllByProps({
+ accessibilityLabel: "Try again",
+ });
+ if (!retryButton)
+ throw new Error("Dashboard retry action was not rendered");
+ expect(retryButton.props.accessibilityHint).toBe(
+ "Reloads your Cap library",
+ );
+
+ await act(async () => {
+ await retryButton.props.onPress();
+ await Promise.resolve();
+ });
+
+ expect(auth.client.listCaps).toHaveBeenCalledTimes(2);
+ });
+
+ it("renders dashboard folders with native folder rows", async () => {
+ const auth = createAuth();
+ auth.client.listCaps = () =>
+ Promise.resolve({
+ caps: [],
+ folders: [
+ {
+ color: "blue",
+ id: "folder_123",
+ name: "Product",
+ parentId: null,
+ videoCount: 2,
+ },
+ ],
+ pagination: {
+ hasNextPage: false,
+ page: 1,
+ totalPages: 1,
+ },
+ rootFolders: [],
+ });
+ authState.value = auth;
+
+ const renderer = await renderComponent(React.createElement(CapsScreen));
+ await act(async () => {
+ await Promise.resolve();
+ });
+ const tree = renderer.toJSON();
+ const text = getTextNodes(tree);
+
+ expect(text).toContain("Folders");
+ expect(text).toContain("Product");
+ expect(text.join("")).toContain("2 videos");
+ expect(hasStyle(tree, { paddingBottom: 24 })).toBe(true);
+ expect(hasProp(tree, "accessibilityLabel", "Open folder Product")).toBe(
+ true,
+ );
+
+ const [folderRow] = renderer.root.findAllByProps({
+ accessibilityLabel: "Open folder Product",
+ });
+ if (!folderRow) throw new Error("Folder row was not rendered");
+
+ expect(resolveStyle(folderRow.props.style)).toMatchObject({
+ backgroundColor: "#f0f0f0",
+ borderColor: "#e0e0e0",
+ });
+ expect(resolveStyle(folderRow.props.style, true)).toMatchObject({
+ backgroundColor: "#e8e8e8",
+ borderColor: "#d9d9d9",
+ });
+
+ await act(async () => {
+ folderRow.props.onPress();
+ });
+
+ expect(
+ hasProp(renderer.toJSON(), "accessibilityLabel", "Back to My Caps"),
+ ).toBe(true);
+ });
+
+ it("marks the dashboard card sharing action busy while visibility is updating", async () => {
+ const auth = createAuth();
+ const cap = {
+ commentCount: 2,
+ createdAt: "2026-05-18T10:00:00.000Z",
+ durationSeconds: 125,
+ folderId: null,
+ id: "video_123",
+ ownerName: "Richie",
+ protected: false,
+ public: true,
+ reactionCount: 3,
+ shareUrl: "https://cap.so/s/video_123",
+ thumbnailUrl: null,
+ title: "Launch review",
+ updatedAt: "2026-05-18T10:30:00.000Z",
+ upload: null,
+ viewCount: 7,
+ };
+ const sharingDeferred = createDeferred<unknown>();
+ auth.client.listCaps = vi.fn(() =>
+ Promise.resolve({
+ caps: [cap],
+ folders: [],
+ pagination: {
+ hasNextPage: false,
+ page: 1,
+ totalPages: 1,
+ },
+ rootFolders: [],
+ }),
+ );
+ auth.client.updateCapSharing = vi.fn(() => sharingDeferred.promise);
+ authState.value = auth;
+
+ const renderer = await renderComponent(React.createElement(CapsScreen));
+ await act(async () => {
+ await Promise.resolve();
+ });
+ const [capCard] = renderer.root.findAllByProps({ cap });
+ if (!capCard) throw new Error("Cap card was not rendered");
+
+ const { ActionSheetIOS } = await import("react-native");
+ const showActionSheetWithOptions = vi.mocked(
+ ActionSheetIOS.showActionSheetWithOptions,
+ );
+ showActionSheetWithOptions.mockClear();
+
+ await act(async () => {
+ capCard.props.onVisibilityPress();
+ });
+
+ const [, sharingCallback] = showActionSheetWithOptions.mock.calls[0] ?? [];
+ if (!sharingCallback) throw new Error("Sharing callback was not set");
+
+ await act(async () => {
+ sharingCallback(0);
+ await Promise.resolve();
+ });
+
+ const [busyCard] = renderer.root.findAllByProps({ cap });
+ if (!busyCard) throw new Error("Busy Cap card was not rendered");
+
+ expect(auth.client.updateCapSharing).toHaveBeenCalledWith("video_123", {
+ public: false,
+ });
+ expect(busyCard.props.visibilityBusy).toBe(true);
+ expect(busyCard.props.visibilityDisabled).toBe(true);
+ expect(busyCard.props.visibilityDisabledHint).toBe(
+ "Sharing update is in progress",
+ );
+ expect(busyCard.props.visibilityValue).toBeUndefined();
+ expect(busyCard.props.visibilityAccessibilityValue).toBe(
+ "Updating sharing for Launch review",
+ );
+
+ await act(async () => {
+ sharingDeferred.resolve({ ...cap, public: false });
+ await sharingDeferred.promise;
+ await Promise.resolve();
+ });
+ });
+
+ it("opens the native iOS folder creation prompt and color sheet", async () => {
+ const auth = createAuth();
+ authState.value = auth;
+ const renderer = await renderComponent(React.createElement(CapsScreen));
+ const [newFolder] = renderer.root.findAllByProps({
+ accessibilityLabel: "New Folder",
+ });
+ if (!newFolder) throw new Error("New Folder action was not rendered");
+
+ const { ActionSheetIOS, Alert } = await import("react-native");
+ const prompt = vi.mocked(Alert.prompt);
+ const showActionSheetWithOptions = vi.mocked(
+ ActionSheetIOS.showActionSheetWithOptions,
+ );
+ prompt.mockClear();
+ showActionSheetWithOptions.mockClear();
+
+ await act(async () => {
+ newFolder.props.onPress();
+ });
+
+ expect(prompt).toHaveBeenCalledWith(
+ "New Folder",
+ "Name this folder.",
+ expect.any(Array),
+ "plain-text",
+ );
+
+ const buttons = prompt.mock.calls[0]?.[2] as
+ | Array<{ onPress?: (value?: string) => void }>
+ | undefined;
+ if (!Array.isArray(buttons)) {
+ throw new Error("Folder prompt buttons were not provided");
+ }
+ const nextButton = buttons[1];
+ const nextAction = nextButton?.onPress;
+ if (typeof nextAction !== "function") {
+ throw new Error("Folder prompt next action was not provided");
+ }
+
+ await act(async () => {
+ nextAction("Product");
+ });
+
+ expect(showActionSheetWithOptions).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cancelButtonIndex: 4,
+ message: "Product",
+ options: ["Normal", "Blue", "Red", "Yellow", "Cancel"],
+ title: "Folder color",
+ userInterfaceStyle: "light",
+ }),
+ expect.any(Function),
+ );
+
+ const [, colorCallback] = showActionSheetWithOptions.mock.calls[0] ?? [];
+ if (!colorCallback) throw new Error("Folder color callback was not set");
+
+ await act(async () => {
+ colorCallback(1);
+ await Promise.resolve();
+ });
+
+ expect(auth.client.createFolder).toHaveBeenCalledWith({
+ name: "Product",
+ color: "blue",
+ });
+ });
+
+ it("locks dashboard navigation while a folder is being created", async () => {
+ const auth = createAuth();
+ const folderDeferred =
+ createDeferred<Awaited<ReturnType<AuthStub["client"]["createFolder"]>>>();
+ auth.client.createFolder = vi.fn(() => folderDeferred.promise);
+ authState.value = auth;
+ const renderer = await renderComponent(React.createElement(CapsScreen));
+ const [newFolder] = renderer.root.findAllByProps({
+ accessibilityLabel: "New Folder",
+ });
+ if (!newFolder) throw new Error("New Folder action was not rendered");
+
+ const { ActionSheetIOS, Alert } = await import("react-native");
+ const prompt = vi.mocked(Alert.prompt);
+ const showActionSheetWithOptions = vi.mocked(
+ ActionSheetIOS.showActionSheetWithOptions,
+ );
+ prompt.mockClear();
+ showActionSheetWithOptions.mockClear();
+
+ await act(async () => {
+ newFolder.props.onPress();
+ });
+
+ const buttons = prompt.mock.calls[0]?.[2] as
+ | Array<{ onPress?: (value?: string) => void }>
+ | undefined;
+ const nextAction = buttons?.[1]?.onPress;
+ if (typeof nextAction !== "function") {
+ throw new Error("Folder prompt next action was not provided");
+ }
+
+ await act(async () => {
+ nextAction("Product");
+ });
+
+ const [, colorCallback] = showActionSheetWithOptions.mock.calls[0] ?? [];
+ if (!colorCallback) throw new Error("Folder color callback was not set");
+
+ await act(async () => {
+ colorCallback(1);
+ await Promise.resolve();
+ });
+
+ const [creatingFolder] = renderer.root.findAllByProps({
+ accessibilityLabel: "New Folder",
+ });
+ if (!creatingFolder) {
+ throw new Error("Creating folder action was not rendered");
+ }
+ expect(getTextNodes(renderer.toJSON())).not.toContain("Creating...");
+ expect(creatingFolder.props.loading).toBe(true);
+ expect(creatingFolder.props.accessibilityHint).toBe(
+ "Folder creation is in progress",
+ );
+ expect(creatingFolder.props.accessibilityValue).toEqual({
+ text: "Creating folder Product",
+ });
+ for (const action of renderer.root.findAllByProps({
+ accessibilityLabel: "Import Video",
+ })) {
+ expect(action.props.disabled).toBe(true);
+ expect(action.props.accessibilityHint).toBe(
+ "Folder creation is in progress",
+ );
+ expect(action.props.accessibilityValue).toEqual({
+ text: "Creating folder Product",
+ });
+ }
+
+ await act(async () => {
+ folderDeferred.resolve({
+ id: "folder_123",
+ name: "Product",
+ color: "blue",
+ parentId: null,
+ videoCount: 0,
+ });
+ await folderDeferred.promise;
+ await Promise.resolve();
+ });
+ });
+});