Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(mobile): redesign dashboard and library tabs
Richie McIlroyaee7ccb62e69
diff --git a/apps/mobile/app/(tabs)/index.tsx b/apps/mobile/app/(tabs)/index.tsxindex bb95f17f5..bf03710b8 100644--- a/apps/mobile/app/(tabs)/index.tsx+++ b/apps/mobile/app/(tabs)/index.tsx@@ -1,15 +1,17 @@import { FlashList } from "@shopify/flash-list";import * as Clipboard from "expo-clipboard";-import { router } from "expo-router";+import { router, useFocusEffect } from "expo-router";import { SymbolView } from "expo-symbols";-import * as WebBrowser from "expo-web-browser";-import { useCallback, useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {ActionSheetIOS,+ ActivityIndicator,Alert,Linking,+ Modal,Platform,Pressable,+ ScrollView,Share,StyleSheet,Text,@@ -19,9 +21,10 @@ import type {MobileCapSummary,MobileCapsListResponse,MobileFolder,+ MobileSpace,} from "@/api/mobile";import { MobileApiError } from "@/api/mobile";-import { apiBaseUrl, useAuth } from "@/auth/AuthContext";+import { useAuth } from "@/auth/AuthContext";import { SignInPanel } from "@/auth/SignInPanel";import { CapSettingsSheet } from "@/caps/CapSettingsSheet";import { showCapPasswordActions } from "@/caps/passwordActions";@@ -33,15 +36,23 @@ 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 {+ CapRefreshControl,+ CapRefreshOverlay,+} from "@/components/CapRefreshControl";import { OrgSwitcher } from "@/components/OrgSwitcher";import { Screen } from "@/components/Screen";import { colors, fonts, radius, squircle } from "@/theme";+import { useRecordingUploadLibraryRevision } from "@/uploads/recording-upload-provider";type ListItem =- | { type: "section"; id: "folders" | "videos"; title: string }+ | { type: "section"; id: "folders"; title: string }+ | { type: "space-switcher" }+ | { type: "folder-crumb"; folder: MobileFolder }+ | { type: "error"; message: string }| { type: "folder"; folder: MobileFolder }- | { type: "cap"; cap: MobileCapSummary };+ | { type: "cap"; cap: MobileCapSummary }+ | { type: "empty" };const folderColorOptions: Array<{label: string;@@ -60,6 +71,29 @@ const folderTintByColor = {yellow: colors.yellow9,} as const;+const activeUploadPhases = new Set([+ "uploading",+ "processing",+ "generating_thumbnail",+]);+const processingRefreshIntervalMs = 3000;+const statusBatchSize = 25;+const stickyHeaderIndices = [0];++const uploadsMatch = (+ left: MobileCapSummary["upload"],+ right: MobileCapSummary["upload"],+) =>+ left === right ||+ (left !== null &&+ right !== null &&+ left.uploaded === right.uploaded &&+ left.total === right.total &&+ left.phase === right.phase &&+ left.processingProgress === right.processingProgress &&+ left.processingMessage === right.processingMessage &&+ left.processingError === right.processingError);+const getCapsErrorMessage = (error: unknown) => {if (error instanceof MobileApiError) {if (error.status === 401) return "Your session expired. Sign in again.";@@ -103,12 +137,197 @@ const showPhotosSettingsAlert = () => {);};+const formatSpaceRole = (role: MobileSpace["role"]) =>+ role ? role.slice(0, 1).toUpperCase() + role.slice(1) : null;++function SpaceSwitcher({+ spaces,+ selectedSpaceId,+ capCount,+ onChange,+}: {+ spaces: readonly MobileSpace[];+ selectedSpaceId: string | null;+ capCount: number | null;+ onChange: (spaceId: string | null) => void;+}) {+ const [open, setOpen] = useState(false);+ const selectedSpace = spaces.find((space) => space.id === selectedSpaceId);+ const selectedLabel = selectedSpace?.name ?? "My Caps";+ const capCountLabel =+ capCount === null ? null : `${capCount} ${capCount === 1 ? "cap" : "caps"}`;+ const options = useMemo(+ () => [+ { id: null, label: "My Caps" },+ ...spaces.map((space) => ({+ id: space.id,+ label: `${space.name}${space.hasPassword ? " · Locked" : ""}${formatSpaceRole(space.role) ? ` · ${formatSpaceRole(space.role)}` : ""}`,+ })),+ ],+ [spaces],+ );++ const openSwitcher = () => {+ if (Platform.OS === "ios") {+ const activeIndex = options.findIndex(+ (option) => option.id === selectedSpaceId,+ );+ ActionSheetIOS.showActionSheetWithOptions(+ {+ cancelButtonIndex: options.length,+ disabledButtonIndices: activeIndex >= 0 ? [activeIndex] : undefined,+ disabledButtonTintColor: colors.gray9,+ message: selectedLabel,+ options: [...options.map((option) => option.label), "Cancel"],+ title: "Space",+ tintColor: colors.blue11,+ userInterfaceStyle: "light",+ },+ (index) => {+ const option = options[index];+ if (option && option.id !== selectedSpaceId) onChange(option.id);+ },+ );+ return;+ }+ setOpen(true);+ };++ return (+ <>+ <Pressable+ accessibilityRole="button"+ accessibilityLabel="Switch space"+ accessibilityHint="Shows My Caps and available spaces"+ accessibilityValue={{+ text: capCountLabel+ ? `${selectedLabel}, ${capCountLabel}`+ : selectedLabel,+ }}+ onPress={openSwitcher}+ style={({ pressed }) => [+ styles.spaceTrigger,+ pressed ? styles.spaceTriggerPressed : null,+ ]}+ >+ <View style={styles.spaceTriggerLabel}>+ <Text numberOfLines={1} style={styles.spaceTriggerText}>+ {selectedLabel}+ </Text>+ <SymbolView+ name="chevron.up.chevron.down"+ size={15}+ tintColor={colors.gray10}+ weight="semibold"+ />+ </View>+ {capCountLabel ? (+ <Text style={styles.spaceCapCount}>{capCountLabel}</Text>+ ) : null}+ </Pressable>+ <Modal+ allowSwipeDismissal+ animationType="slide"+ onRequestClose={() => setOpen(false)}+ onDismiss={() => setOpen(false)}+ presentationStyle="formSheet"+ visible={open}+ >+ <View style={styles.spaceSheet}>+ <View style={styles.spaceSheetHeader}>+ <Text style={styles.spaceSheetTitle}>Choose a space</Text>+ <Pressable+ accessibilityRole="button"+ accessibilityLabel="Close space selector"+ onPress={() => setOpen(false)}+ style={styles.spaceSheetClose}+ >+ <SymbolView+ name="xmark"+ size={15}+ tintColor={colors.gray11}+ weight="semibold"+ />+ </Pressable>+ </View>+ <ScrollView contentContainerStyle={styles.spaceSheetContent}>+ {options.map((option) => {+ const space = option.id+ ? spaces.find((item) => item.id === option.id)+ : null;+ const selected = option.id === selectedSpaceId;+ const detail = space+ ? space.kind === "organization"+ ? `Organization${formatSpaceRole(space.role) ? ` · ${formatSpaceRole(space.role)}` : ""}`+ : `${space.privacy} space${formatSpaceRole(space.role) ? ` · ${formatSpaceRole(space.role)}` : ""}`+ : "Personal library";+ return (+ <Pressable+ key={option.id ?? "my-caps"}+ accessibilityRole="button"+ accessibilityState={{ selected }}+ onPress={() => {+ setOpen(false);+ if (!selected) onChange(option.id);+ }}+ style={({ pressed }) => [+ styles.spaceRow,+ pressed ? styles.spaceRowPressed : null,+ ]}+ >+ <View style={styles.spaceRowIcon}>+ <SymbolView+ name={+ space?.hasPassword+ ? "lock.fill"+ : space?.kind === "organization"+ ? "building.2.fill"+ : space+ ? "person.3.fill"+ : "person.fill"+ }+ size={17}+ tintColor={colors.blue11}+ weight="medium"+ />+ </View>+ <View style={styles.spaceRowCopy}>+ <Text numberOfLines={1} style={styles.spaceRowName}>+ {option.id === null ? option.label : space?.name}+ </Text>+ <Text numberOfLines={1} style={styles.spaceRowDetail}>+ {detail}+ </Text>+ </View>+ {selected ? (+ <SymbolView+ name="checkmark"+ size={18}+ tintColor={colors.blue11}+ weight="semibold"+ />+ ) : null}+ </Pressable>+ );+ })}+ </ScrollView>+ </View>+ </Modal>+ </>+ );+}+export default function CapsScreen() {const auth = useAuth();+ const authStatus = auth.status;+ const apiClient = auth.client;+ const libraryRevision = useRecordingUploadLibraryRevision();+ const [selectedSpaceId, setSelectedSpaceId] = useState<string | null>(null);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 [loadingMore, setLoadingMore] = useState(false);const [loadError, setLoadError] = useState<string | null>(null);const [savingId, setSavingId] = useState<string | null>(null);const [updatingSharingId, setUpdatingSharingId] = useState<string | null>(@@ -119,28 +338,187 @@ export default function CapsScreen() {const [creatingFolderName, setCreatingFolderName] = useState<string | null>(null,);+ const backgroundLoadInFlight = useRef(false);+ const loadMoreInFlight = useRef(false);+ const loadRequestId = useRef(0);+ const spaces = auth.bootstrap?.spaces ?? [];+ const selectedSpace = spaces.find((space) => space.id === selectedSpaceId);+ const selectedCollectionName = selectedSpace?.name ?? "My Caps";+ const canManageSelectedCollection = selectedSpace?.canManage ?? true;+ const thumbnailAuthorization = auth.apiKey+ ? `Bearer ${auth.apiKey}`+ : undefined;++ useEffect(() => {+ if (selectedSpaceId && !selectedSpace) {+ loadRequestId.current += 1;+ setSelectedSpaceId(null);+ setFolder(null);+ setResult(null);+ }+ }, [selectedSpace, selectedSpaceId]);++ const load = useCallback(+ async (showLoading = true) => {+ if (authStatus !== "signedIn") return;+ const requestId = ++loadRequestId.current;+ if (showLoading) setLoading(true);+ try {+ const response = await apiClient.listCaps({+ folderId: folder?.id ?? null,+ spaceId: selectedSpaceId,+ page: 1,+ limit: 30,+ });+ if (requestId !== loadRequestId.current) return;+ setResult(response);+ setLoadError(null);+ } catch (error) {+ if (requestId !== loadRequestId.current) return;+ setLoadError(getCapsErrorMessage(error));+ } finally {+ if (showLoading && requestId === loadRequestId.current) {+ setLoading(false);+ }+ }+ },+ [apiClient, authStatus, folder?.id, selectedSpaceId],+ );++ useFocusEffect(+ useCallback(() => {+ void load(libraryRevision === 0);+ }, [libraryRevision, load]),+ );++ const loadMore = useCallback(async () => {+ if (+ authStatus !== "signedIn" ||+ loading ||+ refreshing ||+ loadMoreInFlight.current ||+ !result?.hasMore+ ) {+ return;+ }- const load = useCallback(async () => {- if (auth.status !== "signedIn") return;- setLoading(true);+ const requestId = loadRequestId.current;+ const currentPage = result.page;+ loadMoreInFlight.current = true;+ setLoadingMore(true);try {- const response = await auth.client.listCaps({+ const response = await apiClient.listCaps({folderId: folder?.id ?? null,- page: 1,- limit: 30,+ spaceId: selectedSpaceId,+ page: currentPage + 1,+ limit: result.limit,+ });+ if (requestId !== loadRequestId.current) return;+ setResult((current) => {+ if (!current || current.page !== currentPage) return current;+ const capIds = new Set(current.caps.map((cap) => cap.id));+ return {+ ...current,+ caps: [+ ...current.caps,+ ...response.caps.filter((cap) => !capIds.has(cap.id)),+ ],+ page: response.page,+ total: response.total,+ collectionTotal: response.collectionTotal,+ hasMore: response.hasMore,+ };});- setResult(response);- setLoadError(null);} catch (error) {- setLoadError(getCapsErrorMessage(error));+ if (requestId === loadRequestId.current) {+ setLoadError(getCapsErrorMessage(error));+ }} finally {- setLoading(false);+ loadMoreInFlight.current = false;+ setLoadingMore(false);}- }, [auth, folder?.id]);+ }, [+ apiClient,+ authStatus,+ folder?.id,+ loading,+ refreshing,+ result,+ selectedSpaceId,+ ]);- useEffect(() => {- void load();- }, [load]);+ const activeCapIds = useMemo(+ () =>+ result?.caps.flatMap((cap) =>+ cap.ownedByCurrentUser !== false &&+ cap.upload &&+ activeUploadPhases.has(cap.upload.phase)+ ? [cap.id]+ : [],+ ) ?? [],+ [result],+ );+ const activeCapIdsKey = activeCapIds.join(",");++ useFocusEffect(+ useCallback(() => {+ if (authStatus !== "signedIn" || activeCapIdsKey.length === 0) return;+ const ids = activeCapIdsKey.split(",");+ let cancelled = false;+ const poll = async () => {+ if (backgroundLoadInFlight.current) return;+ backgroundLoadInFlight.current = true;+ try {+ const responses = await Promise.all(+ Array.from(+ { length: Math.ceil(ids.length / statusBatchSize) },+ (_, index) =>+ apiClient.getCapStatuses(+ ids.slice(+ index * statusBatchSize,+ (index + 1) * statusBatchSize,+ ),+ ),+ ),+ );+ if (cancelled) return;+ const responseCaps = responses.flatMap((response) => response.caps);+ const statuses = new Map(+ responseCaps.map((cap) => [cap.id, cap.upload]),+ );+ setResult((current) => {+ if (!current) return current;+ let changed = false;+ const caps = current.caps.map((cap) => {+ if (!statuses.has(cap.id)) return cap;+ const upload = statuses.get(cap.id) ?? null;+ if (uploadsMatch(cap.upload, upload)) return cap;+ changed = true;+ return { ...cap, upload };+ });+ return changed ? { ...current, caps } : current;+ });+ const terminal =+ responseCaps.length !== ids.length ||+ responseCaps.some(+ (cap) => !cap.upload || !activeUploadPhases.has(cap.upload.phase),+ );+ if (terminal) await load(false);+ } catch {+ } finally {+ backgroundLoadInFlight.current = false;+ }+ };+ void poll();+ const timer = setInterval(() => {+ void poll();+ }, processingRefreshIntervalMs);+ return () => {+ cancelled = true;+ clearInterval(timer);+ };+ }, [activeCapIdsKey, apiClient, authStatus, load]),+ );const refresh = useCallback(async () => {setRefreshing(true);@@ -291,11 +669,12 @@ export default function CapsScreen() {const showCapSettings = useCallback((cap: MobileCapSummary) => {setSettingsCap(cap);}, []);+ const openCap = useCallback((cap: MobileCapSummary) => {+ router.push(`/caps/${cap.id}`);+ }, []);const viewAnalytics = useCallback((cap: MobileCapSummary) => {- const url = new URL("/dashboard/analytics", apiBaseUrl);- url.searchParams.set("capId", cap.id);- void WebBrowser.openBrowserAsync(url.toString());+ router.push({ pathname: "/analytics", params: { capId: cap.id } });}, []);const createFolder = useCallback(@@ -310,7 +689,11 @@ export default function CapsScreen() {setCreatingFolder(true);setCreatingFolderName(trimmedName);try {- await auth.client.createFolder({ name: trimmedName, color });+ await auth.client.createFolder({+ name: trimmedName,+ color,+ spaceId: selectedSpace?.id,+ });setFolder(null);await Promise.all([auth.refresh(), load()]);} catch (error) {@@ -325,7 +708,7 @@ export default function CapsScreen() {setCreatingFolderName(null);}},- [auth, creatingFolder, load],+ [auth, creatingFolder, load, selectedSpace],);const showFolderColorSheet = useCallback(@@ -435,8 +818,10 @@ export default function CapsScreen() {);const items = useMemo<ListItem[]>(() => {- if (!result) return [];- const nextItems: ListItem[] = [];+ const nextItems: ListItem[] = [{ type: "space-switcher" }];+ if (folder) nextItems.push({ type: "folder-crumb", folder });+ if (loadError) nextItems.push({ type: "error", message: loadError });+ if (!result) return nextItems;if (result.folders.length > 0) {nextItems.push({ type: "section", id: "folders", title: "Folders" });nextItems.push(@@ -447,15 +832,15 @@ export default function CapsScreen() {);}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 })),);+ } else {+ nextItems.push({ type: "empty" });}return nextItems;- }, [result]);+ }, [folder, loadError, result]);- const userName = auth.bootstrap?.user.name?.split(" ")[0];const folderCreationHint = creatingFolder? "Folder creation is in progress": "Creates a folder for organizing Caps";@@ -469,6 +854,12 @@ export default function CapsScreen() {const dashboardActionHint = creatingFolder? "Folder creation is in progress": null;+ const isEmptyMyCaps =+ selectedSpaceId === null &&+ folder === null &&+ result !== null &&+ result.folders.length === 0 &&+ result.caps.length === 0;const savingCap =savingId !== null? settingsCap?.id === savingId@@ -499,7 +890,7 @@ export default function CapsScreen() {: undefined;if (auth.status === "loading") {- return <Screen title="My Caps" loading />;+ return <Screen loading />;}if (auth.status === "signedOut") {@@ -511,119 +902,84 @@ export default function CapsScreen() {}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="Record Video"- accessibilityHint="Opens the camera recorder"- onPress={() => router.push("./record")}- disabled={creatingFolder}- size="sm"- style={styles.actionButton}- symbol="video.fill"- variant="blue"- />- <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 : (+ <Screen loading={loading && !result}>+ <View style={styles.listWrap}><FlashList+ ListHeaderComponent={+ <>+ {auth.bootstrap ? (+ <View style={styles.topBar}>+ <OrgSwitcher+ bootstrap={auth.bootstrap}+ onChange={async (organizationId) => {+ loadRequestId.current += 1;+ setSelectedSpaceId(null);+ setFolder(null);+ setResult(null);+ await auth.setActiveOrganization(organizationId);+ }}+ />+ </View>+ ) : null}+ {canManageSelectedCollection || selectedSpaceId === null ? (+ <View style={styles.actions}>+ {canManageSelectedCollection ? (+ <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"+ />+ ) : null}+ {selectedSpaceId === null &&+ result &&+ (result.folders.length > 0 || result.caps.length > 0) ? (+ <ActionButton+ label="Import Media"+ 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"+ />+ ) : null}+ </View>+ ) : null}+ </>+ }data={items}+ ListFooterComponent={+ loadingMore ? (+ <View style={styles.listFooter}>+ <ActivityIndicator color={colors.blue11} />+ </View>+ ) : null+ }keyExtractor={(item) =>item.type === "section"? `section-${item.id}`- : item.type === "folder"- ? `folder-${item.folder.id}`- : `cap-${item.cap.id}`+ : item.type === "space-switcher"+ ? "space-switcher"+ : item.type === "folder-crumb"+ ? `folder-crumb-${item.folder.id}`+ : item.type === "error"+ ? "error"+ : item.type === "folder"+ ? `folder-${item.folder.id}`+ : item.type === "empty"+ ? `empty-${selectedSpaceId ?? "my-caps"}-${folder?.id ?? "root"}`+ : `cap-${item.cap.id}`}refreshControl={<CapRefreshControl refreshing={refreshing} onRefresh={refresh} />@@ -631,42 +987,89 @@ export default function CapsScreen() {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>- }+ onEndReached={() => {+ void loadMore();+ }}+ onEndReachedThreshold={0.4}+ stickyHeaderIndices={stickyHeaderIndices}renderItem={({ item }) =>item.type === "section" ? (<View style={styles.sectionHeader}><Text style={styles.sectionTitle}>{item.title}</Text></View>+ ) : item.type === "space-switcher" ? (+ <View style={styles.spaceSwitcherRow}>+ <SpaceSwitcher+ spaces={spaces}+ selectedSpaceId={selectedSpaceId}+ capCount={result?.collectionTotal ?? result?.total ?? null}+ onChange={(spaceId) => {+ loadRequestId.current += 1;+ setSelectedSpaceId(spaceId);+ setFolder(null);+ setResult(null);+ setLoadError(null);+ }}+ />+ </View>+ ) : item.type === "folder-crumb" ? (+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={`Back to ${selectedCollectionName}`}+ onPress={() => setFolder(null)}+ style={styles.folderCrumb}+ >+ <Text style={styles.folderCrumbText}>+ {selectedCollectionName}+ </Text>+ <SymbolView+ name="chevron.right"+ size={14}+ tintColor={colors.gray9}+ weight="medium"+ />+ <View style={styles.folderCrumbIcon}>+ <SymbolView+ name="folder.fill"+ size={20}+ tintColor={folderTintByColor[item.folder.color]}+ weight="medium"+ />+ </View>+ <Text numberOfLines={1} style={styles.folderCurrent}>+ {item.folder.name}+ </Text>+ </Pressable>+ ) : item.type === "error" ? (+ <View+ accessibilityLabel={`Library error: ${item.message}`}+ 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}>{item.message}</Text>+ </View>+ <ActionButton+ label="Try again"+ accessibilityHint="Reloads your Cap library"+ onPress={() => {+ void load();+ }}+ size="sm"+ style={styles.errorButton}+ symbol="arrow.clockwise"+ />+ </View>) : item.type === "folder" ? (<PressableaccessibilityRole="button"@@ -701,15 +1104,78 @@ export default function CapsScreen() {weight="medium"/></Pressable>+ ) : item.type === "empty" ? (+ <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}>+ {isEmptyMyCaps+ ? "Welcome! Record or Import your first Cap"+ : folder+ ? `No Caps in ${folder.name}`+ : `No Caps in ${selectedCollectionName}`}+ </Text>+ <Text style={styles.emptyText}>+ {isEmptyMyCaps+ ? "Bring videos into Cap and share them instantly."+ : "Caps added to this space will appear here."}+ </Text>+ {isEmptyMyCaps ? (+ <View style={styles.emptyActions}>+ <ActionButton+ label="Record"+ accessibilityLabel="Record"+ accessibilityHint="Opens the camera recorder"+ onPress={() => router.push("/record")}+ disabled={creatingFolder}+ style={styles.emptyButton}+ symbol="video.fill"+ variant="dark"+ />+ <ActionButton+ label="Import Media"+ accessibilityHint={+ dashboardActionHint ?? "Opens import options"+ }+ accessibilityValue={folderCreationAccessibilityValue}+ onPress={() => router.push("/upload")}+ disabled={creatingFolder}+ style={styles.emptyButton}+ symbol="square.and.arrow.up"+ variant="secondary"+ />+ </View>+ ) : null}+ </View>) : (<CapCardcap={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)}+ thumbnailAuthorization={thumbnailAuthorization}+ onAnalyticsPress={+ item.cap.ownedByCurrentUser !== false+ ? viewAnalytics+ : undefined+ }+ onCopyPress={copyCapLink}+ onPress={openCap}+ onSharePress={shareCapLink}+ onVisibilityPress={+ item.cap.ownedByCurrentUser !== false+ ? showSharingActions+ : undefined+ }+ onMenuPress={+ item.cap.ownedByCurrentUser !== false+ ? showCapSettings+ : undefined+ }visibilityBusy={updatingSharingId === item.cap.id}visibilityDisabled={updatingSharingId !== null}visibilityDisabledHint={@@ -726,7 +1192,8 @@ export default function CapsScreen() {)}/>- )}+ <CapRefreshOverlay refreshing={refreshing} />+ </View><CapSettingsSheetcap={settingsCap}visible={settingsCap !== null}@@ -772,8 +1239,15 @@ const styles = StyleSheet.create({flexBasis: 104,paddingHorizontal: 12,},+ listWrap: {+ flex: 1,+ },listContent: {- paddingBottom: 22,+ paddingBottom: 112,+ },+ listFooter: {+ alignItems: "center",+ paddingVertical: 20,},folderCrumb: {minHeight: 40,@@ -823,6 +1297,117 @@ const styles = StyleSheet.create({paddingTop: 8,paddingBottom: 24,},+ spaceSwitcherRow: {+ paddingTop: 8,+ paddingBottom: 24,+ backgroundColor: colors.gray1,+ },+ spaceTrigger: {+ alignSelf: "stretch",+ maxWidth: "100%",+ minHeight: 36,+ flexDirection: "row",+ alignItems: "center",+ justifyContent: "space-between",+ gap: 16,+ borderRadius: radius.sm,+ paddingHorizontal: 2,+ ...squircle,+ },+ spaceTriggerLabel: {+ minWidth: 0,+ flexShrink: 1,+ flexDirection: "row",+ alignItems: "center",+ gap: 8,+ },+ spaceTriggerPressed: {+ opacity: 0.62,+ },+ spaceTriggerText: {+ flexShrink: 1,+ fontFamily: fonts.medium,+ fontSize: 24,+ lineHeight: 30,+ color: colors.gray12,+ },+ spaceCapCount: {+ fontFamily: fonts.regular,+ fontSize: 14,+ lineHeight: 20,+ color: colors.gray9,+ },+ spaceSheet: {+ flex: 1,+ backgroundColor: colors.gray1,+ paddingTop: 18,+ },+ spaceSheetHeader: {+ minHeight: 48,+ flexDirection: "row",+ alignItems: "center",+ gap: 12,+ paddingHorizontal: 20,+ paddingBottom: 10,+ borderBottomWidth: StyleSheet.hairlineWidth,+ borderBottomColor: colors.gray4,+ },+ spaceSheetTitle: {+ flex: 1,+ fontFamily: fonts.medium,+ fontSize: 22,+ lineHeight: 28,+ color: colors.gray12,+ },+ spaceSheetClose: {+ width: 32,+ height: 32,+ borderRadius: radius.full,+ alignItems: "center",+ justifyContent: "center",+ backgroundColor: colors.gray3,+ },+ spaceSheetContent: {+ padding: 14,+ paddingBottom: 32,+ },+ spaceRow: {+ minHeight: 64,+ flexDirection: "row",+ alignItems: "center",+ gap: 12,+ borderRadius: radius.sm,+ paddingHorizontal: 10,+ paddingVertical: 8,+ ...squircle,+ },+ spaceRowPressed: {+ backgroundColor: colors.gray3,+ },+ spaceRowIcon: {+ width: 36,+ height: 36,+ borderRadius: radius.sm,+ alignItems: "center",+ justifyContent: "center",+ backgroundColor: colors.blue3,+ ...squircle,+ },+ spaceRowCopy: {+ flex: 1,+ minWidth: 0,+ gap: 2,+ },+ spaceRowName: {+ fontFamily: fonts.medium,+ fontSize: 16,+ color: colors.gray12,+ },+ spaceRowDetail: {+ fontFamily: fonts.regular,+ fontSize: 12,+ color: colors.gray9,+ },sectionTitle: {fontFamily: fonts.medium,fontSize: 24,diff --git a/apps/mobile/app/(tabs)/upload.tsx b/apps/mobile/app/(tabs)/upload.tsxindex aa790e62a..0f0a76369 100644--- a/apps/mobile/app/(tabs)/upload.tsx+++ b/apps/mobile/app/(tabs)/upload.tsx@@ -2,7 +2,6 @@ import * as DocumentPicker from "expo-document-picker";import * as ImagePicker from "expo-image-picker";import { router } from "expo-router";import { SymbolView } from "expo-symbols";-import * as WebBrowser from "expo-web-browser";import { useEffect, useReducer, useRef, useState } from "react";import {ActionSheetIOS,@@ -17,7 +16,7 @@ import {} from "react-native";import Svg, { Path } from "react-native-svg";import type { UploadFile } from "@/api/mobile";-import { apiBaseUrl, useAuth } from "@/auth/AuthContext";+import { useAuth } from "@/auth/AuthContext";import { SignInPanel } from "@/auth/SignInPanel";import { ActionButton } from "@/components/ActionButton";import { GlassSurface } from "@/components/GlassSurface";@@ -227,12 +226,12 @@ export default function UploadScreen() {const loomImportSubtitle =loomImportError ??(sourceLoading === "loom"- ? "Continue in the browser sheet to import from Loom."+ ? "Opening the native Loom importer.": activeId !== null? activeUploadPreparing? "Finish preparing this upload before importing from Loom.": "Finish the current upload before importing from Loom."- : "Import a Loom share link or bulk import from CSV");+ : "Import a Loom share link without leaving Cap");const activeUploadAccessibilityLabel = activeUploadFileName? activeUploadPreparing? `Preparing upload ${activeUploadFileName}`@@ -612,8 +611,7 @@ export default function UploadScreen() {if (!beginUploadSource("loom")) return;try {- const url = new URL("/dashboard/import/loom", apiBaseUrl);- await WebBrowser.openBrowserAsync(url.toString());+ router.push("/loom-import");} catch (error) {setSourceError({message: getUploadSourceErrorMessage(error, "loom"),@@ -641,6 +639,27 @@ export default function UploadScreen() {title="Import"subtitle="Import videos from external sources or upload from your device."scroll+ contentInsetBottom={112}+ headerLeft={+ <Pressable+ accessibilityRole="button"+ accessibilityLabel="Back"+ accessibilityHint="Returns to the previous screen"+ hitSlop={8}+ onPress={() => router.back()}+ style={({ pressed }) => [+ styles.backButton,+ pressed ? styles.backButtonPressed : null,+ ]}+ >+ <SymbolView+ name="chevron.left"+ size={17}+ tintColor={colors.gray12}+ weight="semibold"+ />+ </Pressable>+ }><GlassSurfacefallbackStyle={styles.importCardFallback}@@ -728,7 +747,7 @@ export default function UploadScreen() {<Viewstyle={[styles.importProgressFill,- { width: `${activeProgress}%` },+ { transform: [{ scaleX: activeProgress / 100 }] },]}/></View>@@ -773,7 +792,7 @@ export default function UploadScreen() {accessibilityValue={uploadSourceActionValue("loom")}accessibilityHint={uploadSourceActionHint("loom",- "Opens Loom import in a browser sheet",+ "Opens native Loom import",)}onPress={() => {void openLoomImport();@@ -805,7 +824,7 @@ export default function UploadScreen() {? activeUploadHint: loomImportError? "Retries Loom import"- : "Opens Loom import in a browser sheet"+ : "Opens native Loom import"}accessibilityState={{busy: uploadSourceBusy,@@ -943,7 +962,7 @@ export default function UploadScreen() {style={[styles.progressFill,{- width: `${queueProgress}%`,+ transform: [{ scaleX: queueProgress / 100 }],},]}/>@@ -1064,6 +1083,18 @@ export default function UploadScreen() {}const styles = StyleSheet.create({+ backButton: {+ width: 40,+ height: 40,+ borderRadius: radius.full,+ alignItems: "center",+ justifyContent: "center",+ backgroundColor: colors.gray3,+ ...squircle,+ },+ backButtonPressed: {+ backgroundColor: colors.gray4,+ },importCard: {borderRadius: radius.md,borderWidth: StyleSheet.hairlineWidth,@@ -1136,6 +1167,8 @@ const styles = StyleSheet.create({},importProgressFill: {height: "100%",+ width: "100%",+ transformOrigin: "left",borderRadius: radius.full,backgroundColor: colors.buttonBlue,},@@ -1248,6 +1281,8 @@ const styles = StyleSheet.create({},progressFill: {height: "100%",+ width: "100%",+ transformOrigin: "left",borderRadius: radius.full,backgroundColor: colors.buttonBlue,},diff --git a/apps/mobile/src/screens/dashboard-upload-visibility.test.tsx b/apps/mobile/src/screens/dashboard-upload-visibility.test.tsxindex b0880df9d..2971152e2 100644--- a/apps/mobile/src/screens/dashboard-upload-visibility.test.tsx+++ b/apps/mobile/src/screens/dashboard-upload-visibility.test.tsx@@ -10,15 +10,30 @@ import UploadScreen from "../../app/(tabs)/upload";type AuthStub = {status: "signedIn";+ apiKey: string;bootstrap: {activeOrganizationId: string;+ spaces?: Array<{+ id: string;+ name: string;+ iconUrl: null;+ kind: "organization" | "space";+ privacy: "Public" | "Private";+ role: "owner" | "admin" | "member" | null;+ canManage: boolean;+ hasPassword: boolean;+ }>;user: {email: string;name: string | null;};};client: {- createFolder: (input: { color?: string; name: string }) => Promise<{+ createFolder: (input: {+ color?: string;+ name: string;+ spaceId?: string;+ }) => Promise<{color: string;id: string;name: string;@@ -30,15 +45,30 @@ type AuthStub = {upload: null;};}>;- listCaps: () => Promise<{+ getCapStatuses: (ids: readonly string[]) => Promise<{+ caps: Array<{+ id: string;+ upload: Record<string, unknown> | null;+ }>;+ }>;+ listCaps: (input?: {+ limit?: number;+ page?: number;+ spaceId?: string | null;+ }) => Promise<{caps: unknown[];+ collectionTotal?: number;folders: unknown[];+ hasMore?: boolean;+ limit?: number;+ page?: number;pagination: {hasNextPage: boolean;page: number;totalPages: number;};rootFolders: unknown[];+ total?: number;}>;updateCapSharing: (id: string,@@ -57,6 +87,7 @@ type JsonNode = ReactTestRendererJSON | ReactTestRendererJSON[] | string | null;const createAuth = (): AuthStub => ({status: "signedIn",+ apiKey: "api-key",bootstrap: {activeOrganizationId: "org_123",user: {@@ -65,14 +96,15 @@ const createAuth = (): AuthStub => ({},},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,- }),+ createFolder: vi.fn(+ (input: { color?: string; name: string; spaceId?: string }) =>+ Promise.resolve({+ id: "folder_123",+ name: input.name,+ color: input.color ?? "normal",+ parentId: null,+ videoCount: 0,+ }),),getCap: () =>Promise.resolve({@@ -80,9 +112,11 @@ const createAuth = (): AuthStub => ({upload: null,},}),+ getCapStatuses: () => Promise.resolve({ caps: [] }),listCaps: () =>Promise.resolve({caps: [],+ collectionTotal: 45,folders: [],pagination: {hasNextPage: false,@@ -90,6 +124,7 @@ const createAuth = (): AuthStub => ({totalPages: 1,},rootFolders: [],+ total: 0,}),updateCapSharing: vi.fn((id: string, input: { public: boolean }) =>Promise.resolve({@@ -146,6 +181,10 @@ const uploadQueueActionsState = vi.hoisted((): { value: unknown[] } => ({value: [],}));+const recordingUploadState = vi.hoisted(() => ({+ libraryRevision: 0,+}));+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -279,6 +318,7 @@ vi.mock("react-native", async () => {},Pressable: createHost("Pressable"),RefreshControl: createHost("RefreshControl"),+ ScrollView: createHost("ScrollView"),Share: {share: vi.fn(),},@@ -306,15 +346,24 @@ vi.mock("@shopify/flash-list", async () => {FlashList: ({data,ListEmptyComponent,+ ListFooterComponent,+ ListHeaderComponent,+ onEndReached,renderItem,+ stickyHeaderIndices,}: {data?: unknown[];ListEmptyComponent?: ReactNode;+ ListFooterComponent?: ReactNode;+ ListHeaderComponent?: ReactNode;+ onEndReached?: () => void;renderItem?: (info: { index: number; item: unknown }) => ReactNode;+ stickyHeaderIndices?: number[];}) =>React.createElement("FlashList",- null,+ { data, onEndReached, stickyHeaderIndices },+ ListHeaderComponent,data && data.length > 0? data.map((item, index) =>React.createElement(@@ -324,6 +373,7 @@ vi.mock("@shopify/flash-list", async () => {),): ListEmptyComponent,+ ListFooterComponent,),};});@@ -332,11 +382,16 @@ vi.mock("expo-clipboard", () => ({setStringAsync: vi.fn(),}));-vi.mock("expo-router", () => ({- router: {- push: vi.fn(),- },-}));+vi.mock("expo-router", async () => {+ const React = await import("react");+ return {+ router: {+ push: vi.fn(),+ },+ useFocusEffect: (callback: Parameters<typeof React.useEffect>[0]) =>+ React.useEffect(callback, [callback]),+ };+});vi.mock("expo-web-browser", () => ({openBrowserAsync: vi.fn(),@@ -347,6 +402,10 @@ vi.mock("@/auth/AuthContext", () => ({useAuth: () => authState.value,}));+vi.mock("@/uploads/recording-upload-provider", () => ({+ useRecordingUploadLibraryRevision: () => recordingUploadState.libraryRevision,+}));+vi.mock("@/auth/SignInPanel", async () => {const React = await import("react");return {@@ -376,6 +435,16 @@ vi.mock("@/components/ActionButton", async () => {};});+vi.mock("@/components/CapRefreshControl", async () => {+ const React = await import("react");+ return {+ CapRefreshControl: (props: { [key: string]: unknown }) =>+ React.createElement("CapRefreshControl", props),+ CapRefreshOverlay: (props: { [key: string]: unknown }) =>+ React.createElement("CapRefreshOverlay", props),+ };+});+vi.mock("@/components/Screen", async () => {const React = await import("react");@@ -393,7 +462,7 @@ vi.mock("@/components/Screen", async () => {}) =>React.createElement("Screen",- null,+ { title },title ? React.createElement("Text", null, title) : null,subtitle ? React.createElement("Text", null, subtitle) : null,loading ? React.createElement("Text", null, "Loading") : children,@@ -547,7 +616,9 @@ vi.mock("@/uploads/uploadQueue", async (importOriginal) => {describe("upload and dashboard visibility", () => {beforeEach(() => {+ vi.useRealTimers();authState.value = createAuth();+ recordingUploadState.libraryRevision = 0;uploadQueueState.value.items = [];uploadQueueActionsState.value = [];});@@ -576,7 +647,7 @@ describe("upload and dashboard visibility", () => {).toBe(true);expect(hasProps(tree, {- accessibilityHint: "Opens Loom import in a browser sheet",+ accessibilityHint: "Opens native Loom import",accessibilityLabel: "Open Loom import",}),).toBe(true);@@ -624,20 +695,17 @@ describe("upload and dashboard visibility", () => {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();+ const { router } = await import("expo-router");+ vi.mocked(router.push).mockClear();await act(async () => {callback(2);});- expect(openBrowserAsync).toHaveBeenCalledWith(- "https://cap.so/dashboard/import/loom",- );+ expect(router.push).toHaveBeenCalledWith("/loom-import");});- it("opens Loom import in the native browser sheet", async () => {+ it("opens native Loom import", async () => {const renderer = await renderComponent(React.createElement(UploadScreen));const [loomAction] = renderer.root.findAllByProps({accessibilityLabel: "Import from Loom",@@ -648,200 +716,23 @@ describe("upload and dashboard visibility", () => {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();+ const { router } = await import("expo-router");+ vi.mocked(router.push).mockClear();- expect(loomAction.props.accessibilityHint).toBe(- "Opens Loom import in a browser sheet",- );+ expect(loomAction.props.accessibilityHint).toBe("Opens native Loom import");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");+ expect(router.push).toHaveBeenCalledWith("/loom-import");+ vi.mocked(router.push).mockClear();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();- });+ expect(router.push).toHaveBeenCalledWith("/loom-import");});it("locks upload sources while the file picker is opening", async () => {@@ -2014,27 +1905,175 @@ describe("upload and dashboard visibility", () => {).toBe(true);});- it("shows dashboard import actions", async () => {- const tree = await renderTree(React.createElement(CapsScreen));+ it("shows dashboard record and import actions", async () => {+ const renderer = await renderComponent(React.createElement(CapsScreen));+ const tree = renderer.toJSON();const text = getTextNodes(tree);expect(text).toContain("My Caps");+ expect(text).toContain("45 caps");+ const [screen] = renderer.root.findAll(+ (node) => String(node.type) === "Screen",+ );+ if (!screen) throw new Error("Dashboard screen was not rendered");+ expect(screen.props.title).toBeUndefined();expect(text.filter((item) => item === "New Folder").length).toBeGreaterThan(0,);- expect(text).not.toContain("Record");+ expect(text).not.toContain("Record Video");+ expect(text).not.toContain("Import Video");+ expect(text.filter((item) => item === "Record")).toHaveLength(1);+ expect(text.filter((item) => item === "Import Media")).toHaveLength(1);+ const [recordAction] = renderer.root.findAll(+ (node) =>+ String(node.type) === "ActionButton" &&+ node.props.accessibilityLabel === "Record",+ );+ if (!recordAction)+ throw new Error("Dashboard record action was not rendered");+ const [importAction] = renderer.root.findAllByProps({+ accessibilityLabel: "Import Media",+ });+ if (!importAction)+ throw new Error("Dashboard import action was not rendered");+ expect(recordAction.props).toMatchObject({+ accessibilityHint: "Opens the camera recorder",+ symbol: "video.fill",+ variant: "dark",+ });+ expect(importAction.props.variant).toBe("secondary");+ expect(+ renderer.root.findAllByProps({ accessibilityLabel: "Import Media" }),+ ).toHaveLength(1);+ expect(+ renderer.root.findAllByProps({ accessibilityLabel: "Import" }),+ ).toHaveLength(0);+ const [list] = renderer.root.findAll(+ (node) => String(node.type) === "FlashList",+ );+ if (!list) throw new Error("Dashboard list was not rendered");+ expect(list.props.stickyHeaderIndices).toEqual([0]);+ expect(+ (list.props.data as Array<{ type: string }>).map((item) => item.type),+ ).toEqual(["space-switcher", "empty"]);+ expect(+ list.findAll((node) => String(node.type) === "OrgSwitcher").length,+ ).toBeGreaterThan(0);+ expect(+ list.findAllByProps({ accessibilityLabel: "New Folder" }).length,+ ).toBeGreaterThan(0);expect(- text.filter((item) => item === "Import Video").length,+ list.findAllByProps({ accessibilityLabel: "Switch space" }).length,).toBeGreaterThan(0);expect(hasStyle(tree, { marginBottom: 40 })).toBe(true);- expect(text.join("")).toContain("Hey Richie! Import your first Cap");+ expect(text).toContain("Welcome! Record or Import your first Cap");expect(hasProp(tree, "accessibilityLabel", "Cap logo")).toBe(true);expect(hasProps(tree, {accessibilityHint: "Opens import options",- accessibilityLabel: "Import Video",+ accessibilityLabel: "Import Media",}),).toBe(true);++ const { router } = await import("expo-router");+ const push = vi.mocked(router.push);+ push.mockClear();+ await act(async () => {+ recordAction.props.onPress();+ });+ expect(push).toHaveBeenCalledWith("/record");++ push.mockClear();+ await act(async () => {+ importAction.props.onPress();+ });+ expect(push).toHaveBeenCalledWith("/upload");+ });++ it("switches from My Caps into an available space", async () => {+ const auth = createAuth();+ auth.bootstrap.spaces = [+ {+ id: "org_123",+ name: "All Cap",+ iconUrl: null,+ kind: "organization",+ privacy: "Public",+ role: "owner",+ canManage: true,+ hasPassword: false,+ },+ {+ id: "space_123",+ name: "Product",+ iconUrl: null,+ kind: "space",+ privacy: "Private",+ role: "member",+ canManage: false,+ hasPassword: false,+ },+ ];+ auth.client.listCaps = vi.fn(() =>+ Promise.resolve({+ caps: [],+ folders: [],+ pagination: {+ hasNextPage: false,+ page: 1,+ totalPages: 1,+ },+ rootFolders: [],+ }),+ );+ authState.value = auth;+ const renderer = await renderComponent(React.createElement(CapsScreen));+ const [switcher] = renderer.root.findAllByProps({+ accessibilityLabel: "Switch space",+ });+ if (!switcher) throw new Error("Space switcher was not rendered");+ const { ActionSheetIOS } = await import("react-native");+ const showActionSheetWithOptions = vi.mocked(+ ActionSheetIOS.showActionSheetWithOptions,+ );+ showActionSheetWithOptions.mockClear();++ await act(async () => {+ switcher.props.onPress();+ });++ const [options, select] = showActionSheetWithOptions.mock.calls[0] ?? [];+ expect(options).toMatchObject({+ disabledButtonIndices: [0],+ options: ["My Caps", "All Cap · Owner", "Product · Member", "Cancel"],+ title: "Space",+ });+ if (!select) throw new Error("Space action callback was not registered");++ await act(async () => {+ select(2);+ await Promise.resolve();+ });++ expect(auth.client.listCaps).toHaveBeenLastCalledWith(+ expect.objectContaining({ spaceId: "space_123" }),+ );+ const text = getTextNodes(renderer.toJSON());+ expect(text).toContain("Product");+ expect(text).toContain("No Caps in Product");+ expect(+ renderer.root.findAllByProps({ accessibilityLabel: "New Folder" }),+ ).toHaveLength(0);+ expect(+ renderer.root.findAll(+ (node) =>+ String(node.type) === "ActionButton" &&+ node.props.accessibilityLabel === "Record",+ ),+ ).toHaveLength(0);+ expect(+ renderer.root.findAllByProps({ accessibilityLabel: "Import Media" }),+ ).toHaveLength(0);});it("announces dashboard load errors with a retry action", async () => {@@ -2079,6 +2118,140 @@ describe("upload and dashboard visibility", () => {expect(auth.client.listCaps).toHaveBeenCalledTimes(2);});+ it("loads the next dashboard page without replacing visible Caps", async () => {+ const auth = createAuth();+ auth.client.listCaps = vi.fn((input?: { page?: number }) =>+ Promise.resolve({+ caps: [+ {+ id: input?.page === 2 ? "cap_2" : "cap_1",+ title: input?.page === 2 ? "Second Cap" : "First Cap",+ upload: null,+ },+ ],+ folders: [],+ hasMore: input?.page !== 2,+ limit: 30,+ page: input?.page ?? 1,+ pagination: {+ hasNextPage: input?.page !== 2,+ page: input?.page ?? 1,+ totalPages: 2,+ },+ rootFolders: [],+ total: 2,+ }),+ );+ authState.value = auth;+ const renderer = await renderComponent(React.createElement(CapsScreen));+ const [list] = renderer.root.findAll(+ (node) => String(node.type) === "FlashList",+ );+ if (!list) throw new Error("Dashboard list was not rendered");++ await act(async () => {+ await list.props.onEndReached();+ });++ expect(auth.client.listCaps).toHaveBeenLastCalledWith(+ expect.objectContaining({ limit: 30, page: 2 }),+ );+ const capCards = renderer.root.findAll((node) => {+ const cap = node.props.cap as { id?: string } | undefined;+ return (+ String(node.type) === "CapCard" &&+ (cap?.id === "cap_1" || cap?.id === "cap_2")+ );+ });+ expect(capCards.map((card) => card.props.cap.id)).toEqual([+ "cap_1",+ "cap_2",+ ]);+ expect(capCards[0]?.props.thumbnailAuthorization).toBe("Bearer api-key");+ });++ it("refreshes a new recording until server processing finishes", async () => {+ vi.useFakeTimers();+ const auth = createAuth();+ const response = (upload: Record<string, unknown> | null) => ({+ caps: [+ {+ id: "cap_123",+ title: "Cap Recording",+ upload,+ },+ ],+ folders: [],+ pagination: {+ hasNextPage: false,+ page: 1,+ totalPages: 1,+ },+ rootFolders: [],+ });+ auth.client.listCaps = vi+ .fn()+ .mockResolvedValueOnce({ ...response(null), caps: [] })+ .mockResolvedValueOnce(+ response({+ phase: "processing",+ processingError: null,+ processingMessage: "Muxing segments into MP4...",+ processingProgress: 25,+ total: 100,+ uploaded: 100,+ }),+ )+ .mockResolvedValue(response(null));+ auth.client.getCapStatuses = vi+ .fn()+ .mockResolvedValueOnce({+ caps: [+ {+ id: "cap_123",+ upload: {+ phase: "processing",+ processingError: null,+ processingMessage: "Generating thumbnail...",+ processingProgress: 70,+ total: 100,+ uploaded: 100,+ },+ },+ ],+ })+ .mockResolvedValue({ caps: [{ id: "cap_123", upload: null }] });+ authState.value = auth;++ const renderer = await renderComponent(React.createElement(CapsScreen));+ expect(auth.client.listCaps).toHaveBeenCalledTimes(1);++ recordingUploadState.libraryRevision = 1;+ await act(async () => {+ renderer.update(React.createElement(CapsScreen));+ await Promise.resolve();+ });+ expect(auth.client.listCaps).toHaveBeenCalledTimes(2);+ expect(auth.client.getCapStatuses).toHaveBeenCalledTimes(1);+ expect(auth.client.getCapStatuses).toHaveBeenCalledWith(["cap_123"]);++ await act(async () => {+ await vi.advanceTimersByTimeAsync(3000);+ });+ expect(auth.client.getCapStatuses).toHaveBeenCalledTimes(2);+ expect(auth.client.listCaps).toHaveBeenCalledTimes(3);+ const [capCard] = renderer.root.findAll((node) => {+ const cap = node.props.cap as { id?: string } | undefined;+ return cap?.id === "cap_123";+ });+ expect(capCard?.props.cap.upload).toBeNull();++ await act(async () => {+ renderer.unmount();+ });+ vi.useRealTimers();+ });+it("renders dashboard folders with native folder rows", async () => {const auth = createAuth();auth.client.listCaps = () =>@@ -2112,10 +2285,19 @@ describe("upload and dashboard visibility", () => {expect(text).toContain("Folders");expect(text).toContain("Product");expect(text.join("")).toContain("2 videos");+ expect(text).not.toContain("Welcome! Record or Import your first Cap");+ expect(text).toContain("No Caps in My Caps");+ expect(text).toContain("Caps added to this space will appear here.");expect(hasStyle(tree, { paddingBottom: 24 })).toBe(true);expect(hasProp(tree, "accessibilityLabel", "Open folder Product")).toBe(true,);+ expect(+ renderer.root.findAllByProps({ accessibilityLabel: "Record" }),+ ).toHaveLength(0);+ expect(+ renderer.root.findAllByProps({ accessibilityLabel: "Import Media" }),+ ).toHaveLength(1);const [folderRow] = renderer.root.findAllByProps({accessibilityLabel: "Open folder Product",@@ -2189,7 +2371,7 @@ describe("upload and dashboard visibility", () => {showActionSheetWithOptions.mockClear();await act(async () => {- capCard.props.onVisibilityPress();+ capCard.props.onVisibilityPress(cap);});const [, sharingCallback] = showActionSheetWithOptions.mock.calls[0] ?? [];@@ -2223,6 +2405,50 @@ describe("upload and dashboard visibility", () => {});});+ it("keeps Caps owned by another space member read-only", async () => {+ const auth = createAuth();+ const cap = {+ commentCount: 2,+ createdAt: "2026-05-18T10:00:00.000Z",+ durationSeconds: 125,+ folderId: null,+ id: "video_123",+ ownedByCurrentUser: false,+ ownerName: "Morgan",+ protected: false,+ public: false,+ reactionCount: 3,+ shareUrl: "https://cap.so/s/video_123",+ thumbnailUrl: null,+ title: "Product review",+ updatedAt: "2026-05-18T10:30:00.000Z",+ upload: null,+ viewCount: 0,+ };+ auth.client.listCaps = vi.fn(() =>+ Promise.resolve({+ caps: [cap],+ folders: [],+ pagination: {+ hasNextPage: false,+ page: 1,+ totalPages: 1,+ },+ rootFolders: [],+ }),+ );+ authState.value = auth;+ const renderer = await renderComponent(React.createElement(CapsScreen));+ const [capCard] = renderer.root.findAllByProps({ cap });+ if (!capCard) throw new Error("Cap card was not rendered");++ expect(capCard.props.onCopyPress).toEqual(expect.any(Function));+ expect(capCard.props.onSharePress).toEqual(expect.any(Function));+ expect(capCard.props.onAnalyticsPress).toBeUndefined();+ expect(capCard.props.onVisibilityPress).toBeUndefined();+ expect(capCard.props.onMenuPress).toBeUndefined();+ });+it("opens the native iOS folder creation prompt and color sheet", async () => {const auth = createAuth();authState.value = auth;@@ -2351,7 +2577,7 @@ describe("upload and dashboard visibility", () => {text: "Creating folder Product",});for (const action of renderer.root.findAllByProps({- accessibilityLabel: "Import Video",+ accessibilityLabel: "Import Media",})) {expect(action.props.disabled).toBe(true);expect(action.props.accessibilityHint).toBe(