Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(mobile): add cap detail screen
Richie McIlroy4bcb6230e3f6
diff --git a/apps/mobile/app/caps/[id].tsx b/apps/mobile/app/caps/[id].tsxnew file mode 100644index 000000000..4fb96c809--- /dev/null+++ b/apps/mobile/app/caps/[id].tsx@@ -0,0 +1,1105 @@+import * as Clipboard from "expo-clipboard";+import { router, Stack, useLocalSearchParams } from "expo-router";+import { type SFSymbol, SymbolView } from "expo-symbols";+import { useVideoPlayer, VideoView } from "expo-video";+import * as WebBrowser from "expo-web-browser";+import { useCallback, useEffect, useMemo, useState } from "react";+import {+ ActionSheetIOS,+ Alert,+ KeyboardAvoidingView,+ Linking,+ Platform,+ Pressable,+ Share,+ StyleSheet,+ Text,+ TextInput,+ View,+} from "react-native";+import type { MobileCapDetail, MobilePlaybackResponse } 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 { GlassSurface } from "@/components/GlassSurface";+import { Screen } from "@/components/Screen";+import { colors, fonts, radius, squircle } from "@/theme";+import { formatRelativeDate } from "@/utils/format";++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();+ },+ },+ ],+ );+};++const getCapDetailErrorMessage = (error: unknown) =>+ error instanceof Error ? error.message : "Unable to load this Cap";++type CapDetailOperation = "comment" | "save" | "visibility";++type AnalyticsMetricProps = {+ symbol: SFSymbol;+ value: number;+};++function AnalyticsMetric({ symbol, value }: AnalyticsMetricProps) {+ return (+ <View style={styles.metric}>+ <SymbolView+ name={symbol}+ size={15}+ tintColor={colors.gray8}+ weight="medium"+ />+ <Text style={styles.metricText}>{value}</Text>+ </View>+ );+}++export default function CapDetailScreen() {+ const { id } = useLocalSearchParams<{ id: string }>();+ const auth = useAuth();+ const [detail, setDetail] = useState<MobileCapDetail | null>(null);+ const [playback, setPlayback] = useState<MobilePlaybackResponse | null>(null);+ const [comment, setComment] = useState("");+ const [loading, setLoading] = useState(true);+ const [activeOperation, setActiveOperation] =+ useState<CapDetailOperation | null>(null);+ const [loadError, setLoadError] = useState<string | null>(null);+ const [copied, setCopied] = useState(false);+ const [saved, setSaved] = useState(false);+ const [settingsVisible, setSettingsVisible] = useState(false);+ const player = useVideoPlayer(null);++ const load = useCallback(async () => {+ if (auth.status !== "signedIn" || typeof id !== "string") return;+ setLoading(true);+ setLoadError(null);+ try {+ const [nextDetail, nextPlayback] = await Promise.all([+ auth.client.getCap(id),+ auth.client.getPlayback(id),+ ]);+ setDetail(nextDetail);+ setPlayback(nextPlayback);+ } catch (error) {+ setDetail(null);+ setPlayback(null);+ setLoadError(getCapDetailErrorMessage(error));+ } finally {+ setLoading(false);+ }+ }, [auth, id]);++ useEffect(() => {+ load().catch(() => {});+ }, [load]);++ useEffect(() => {+ if (!playback?.url) return;+ player.replace(playback.url);+ }, [playback?.url, player]);++ useEffect(() => {+ if (!copied) return;+ const timeout = setTimeout(() => setCopied(false), 1600);+ return () => clearTimeout(timeout);+ }, [copied]);++ useEffect(() => {+ if (!saved) return;+ const timeout = setTimeout(() => setSaved(false), 1600);+ return () => clearTimeout(timeout);+ }, [saved]);++ const textComments = useMemo(+ () => detail?.comments.filter((item) => item.type === "text") ?? [],+ [detail],+ );+ const reactions = useMemo(+ () => detail?.comments.filter((item) => item.type === "emoji") ?? [],+ [detail],+ );+ const isActionInProgress = activeOperation !== null;+ const isPostingComment = activeOperation === "comment";+ const isSavingVideo = activeOperation === "save";+ const isUpdatingVisibility = activeOperation === "visibility";+ const actionInProgressHint = "Current Cap action is in progress";+ const saveVideoLabel = saved ? "Saved" : "Save video";+ const saveVideoAccessibilityText =+ isSavingVideo && detail+ ? `Saving video for ${detail.cap.title}`+ : saved && detail+ ? `Saved video for ${detail.cap.title}`+ : undefined;+ const saveVideoAccessibilityLabel = saved+ ? saveVideoAccessibilityText+ : undefined;+ const saveVideoAccessibilityValue =+ isSavingVideo && saveVideoAccessibilityText+ ? { text: saveVideoAccessibilityText }+ : undefined;+ const saveVideoHint = isSavingVideo+ ? "Save is in progress"+ : isActionInProgress+ ? actionInProgressHint+ : "Saves this video to Photos";+ const sharingStatusHint = isUpdatingVisibility+ ? "Sharing update is in progress"+ : isActionInProgress+ ? actionInProgressHint+ : "Opens sharing settings";+ const sharingStatusLabel = detail?.cap.public ? "Shared" : "Not shared";+ const sharingStatusAccessibilityValue =+ isUpdatingVisibility && detail+ ? `Updating sharing for ${detail.cap.title}`+ : undefined;+ const commentHint = isPostingComment+ ? "Comment is being sent"+ : isActionInProgress+ ? actionInProgressHint+ : "Add a comment to this Cap";+ const sendCommentHint = isPostingComment+ ? "Comment is being sent"+ : isActionInProgress+ ? actionInProgressHint+ : comment.trim().length > 0+ ? "Adds this comment"+ : "Enter a comment before sending";+ const sendCommentLabel = isPostingComment ? "Sending..." : "Send";+ const sendCommentAccessibilityLabel =+ isPostingComment && detail+ ? `Sending comment on ${detail.cap.title}`+ : "Send comment";+ const canSendComment = comment.trim().length > 0 && !isActionInProgress;++ const createComment = async () => {+ const trimmed = comment.trim();+ if (!trimmed || !detail || isActionInProgress) return;+ setActiveOperation("comment");+ try {+ const created = await auth.client.createComment(detail.cap.id, {+ content: trimmed,+ timestamp: null,+ });+ setDetail({+ ...detail,+ comments: [...detail.comments, created],+ cap: {+ ...detail.cap,+ commentCount: detail.cap.commentCount + 1,+ },+ });+ setComment("");+ } catch (error) {+ Alert.alert(+ "Comment failed",+ error instanceof Error ? error.message : "Unable to add that comment.",+ );+ } finally {+ setActiveOperation(null);+ }+ };++ const createReaction = async (emoji: string) => {+ if (!detail) return;+ try {+ const created = await auth.client.createReaction(detail.cap.id, {+ content: emoji,+ timestamp: null,+ });+ setDetail({+ ...detail,+ comments: [...detail.comments, created],+ cap: {+ ...detail.cap,+ reactionCount: detail.cap.reactionCount + 1,+ },+ });+ } catch (error) {+ Alert.alert(+ "Reaction failed",+ error instanceof Error ? error.message : "Unable to add that reaction.",+ );+ }+ };++ const copyLink = async () => {+ if (!detail) return;+ try {+ await Clipboard.setStringAsync(detail.shareUrl);+ setCopied(true);+ } catch (error) {+ Alert.alert(+ "Copy failed",+ error instanceof Error ? error.message : "Unable to copy this link.",+ );+ }+ };++ const shareLink = async () => {+ if (!detail) return;+ await Share.share({ url: detail.shareUrl, message: detail.shareUrl });+ };++ const updateVisibility = async (isPublic: boolean) => {+ if (!detail || isActionInProgress) return;+ setActiveOperation("visibility");+ try {+ const cap = await auth.client.updateCapSharing(detail.cap.id, {+ public: isPublic,+ });+ setDetail((current) => (current ? { ...current, cap } : current));+ await auth.refresh();+ } catch (error) {+ Alert.alert(+ "Sharing update failed",+ error instanceof Error+ ? error.message+ : "Unable to update sharing for this Cap.",+ );+ } finally {+ setActiveOperation(null);+ }+ };++ const showPasswordActions = () => {+ if (!detail || auth.status !== "signedIn") return;+ showCapPasswordActions({+ cap: detail.cap,+ client: auth.client,+ onUpdated: async (cap) => {+ setDetail((current) => (current ? { ...current, cap } : current));+ await auth.refresh();+ },+ });+ };++ const showTitleActions = () => {+ if (!detail || auth.status !== "signedIn") return;+ showCapTitleActions({+ cap: detail.cap,+ client: auth.client,+ onUpdated: async (cap) => {+ setDetail((current) => (current ? { ...current, cap } : current));+ await auth.refresh();+ },+ });+ };++ const downloadVideo = async () => {+ if (!detail || isActionInProgress) return;+ setActiveOperation("save");+ try {+ await saveCapVideoToPhotos(auth.client, detail.cap.id);+ setSaved(true);+ } catch (error) {+ if (error instanceof PhotosPermissionDeniedError) {+ showPhotosSettingsAlert();+ return;+ }+ Alert.alert(+ "Save failed",+ error instanceof Error ? error.message : "Unable to save this video.",+ );+ } finally {+ setActiveOperation(null);+ }+ };++ const deleteCap = () => {+ if (!detail || isActionInProgress) return;+ const confirmDelete = () => {+ void (async () => {+ setSettingsVisible(false);+ await auth.client.deleteCap(detail.cap.id);+ await auth.refresh();+ router.back();+ })();+ };++ if (Platform.OS === "ios") {+ ActionSheetIOS.showActionSheetWithOptions(+ {+ cancelButtonIndex: 1,+ destructiveButtonIndex: 0,+ message: "This Cap will be removed from your library.",+ options: ["Delete Cap", "Cancel"],+ title: "Delete Cap",+ tintColor: colors.blue11,+ userInterfaceStyle: "light",+ },+ (index) => {+ if (index === 0) confirmDelete();+ },+ );+ return;+ }++ Alert.alert("Delete Cap", "This Cap will be removed from your library.", [+ { text: "Cancel", style: "cancel" },+ {+ text: "Delete",+ style: "destructive",+ onPress: confirmDelete,+ },+ ]);+ };++ const showMoreActions = () => {+ setSettingsVisible(true);+ };++ const viewAnalytics = () => {+ if (!detail || isActionInProgress) return;+ const url = new URL("/dashboard/analytics", apiBaseUrl);+ url.searchParams.set("capId", detail.cap.id);+ void WebBrowser.openBrowserAsync(url.toString());+ };++ if (auth.status === "signedOut") {+ return (+ <Screen scroll>+ <SignInPanel title="Sign in to view" />+ </Screen>+ );+ }++ return (+ <KeyboardAvoidingView+ style={styles.keyboard}+ behavior={Platform.OS === "ios" ? "padding" : undefined}+ >+ <Stack.Screen+ options={{+ headerShown: true,+ headerTransparent: true,+ headerBlurEffect: "systemThinMaterialLight",+ headerShadowVisible: false,+ headerStyle: { backgroundColor: colors.glass },+ headerTintColor: colors.gray12,+ headerTitleStyle: { fontFamily: fonts.medium },+ headerRight: () =>+ detail ? (+ <Pressable+ accessibilityRole="button"+ accessibilityLabel="More actions"+ accessibilityHint={+ isActionInProgress+ ? actionInProgressHint+ : "Opens Cap settings"+ }+ accessibilityState={{ disabled: isActionInProgress }}+ disabled={isActionInProgress}+ hitSlop={10}+ onPress={showMoreActions}+ style={({ pressed }) => [+ styles.headerAction,+ pressed && !isActionInProgress+ ? styles.headerActionPressed+ : null,+ isActionInProgress ? styles.headerActionDisabled : null,+ ]}+ >+ <SymbolView+ name="ellipsis.circle"+ size={22}+ tintColor={isActionInProgress ? colors.gray9 : colors.gray12}+ weight="medium"+ />+ </Pressable>+ ) : null,+ title: detail?.cap.title ?? "Cap",+ }}+ />+ <Screen loading={loading} scroll safeEdges={["left", "right"]}>+ {loadError ? (+ <View+ accessibilityLabel={`Cap detail error: ${loadError}`}+ accessibilityLiveRegion="polite"+ accessibilityRole="alert"+ style={styles.errorCard}+ >+ <SymbolView+ name="exclamationmark.triangle"+ size={26}+ tintColor={colors.red9}+ weight="medium"+ />+ <Text style={styles.errorTitle}>Unable to load Cap</Text>+ <Text style={styles.errorBody}>{loadError}</Text>+ <ActionButton+ label="Try again"+ accessibilityHint="Reloads this Cap"+ onPress={() => {+ void load();+ }}+ symbol="arrow.clockwise"+ style={styles.retryButton}+ />+ </View>+ ) : detail ? (+ <>+ <View style={styles.videoFrame}>+ {playback?.url ? (+ <VideoView+ player={player}+ style={styles.video}+ fullscreenOptions={{ enable: true }}+ allowsPictureInPicture+ />+ ) : (+ <View style={styles.videoPlaceholder}>+ <Text style={styles.placeholderText}>Processing video</Text>+ </View>+ )}+ </View>+ <View style={styles.titleBlock}>+ <Text style={styles.title}>{detail.cap.title}</Text>+ <Text style={styles.meta}>+ {formatRelativeDate(detail.cap.createdAt)} ·{" "}+ {detail.cap.ownerName}+ </Text>+ <View style={styles.statusRow}>+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={`Change sharing for ${detail.cap.title}`}+ accessibilityHint={sharingStatusHint}+ accessibilityState={{ disabled: isActionInProgress }}+ accessibilityValue={+ isUpdatingVisibility+ ? {+ text:+ sharingStatusAccessibilityValue ??+ sharingStatusLabel,+ }+ : undefined+ }+ disabled={isActionInProgress}+ hitSlop={6}+ onPress={() => setSettingsVisible(true)}+ style={({ pressed }) => [+ styles.shareStatusButton,+ pressed && !isActionInProgress+ ? styles.shareStatusButtonPressed+ : null,+ isActionInProgress+ ? styles.shareStatusButtonDisabled+ : null,+ ]}+ >+ <SymbolView+ name={detail.cap.public ? "globe" : "lock.open"}+ size={14}+ tintColor={+ isActionInProgress ? colors.gray9 : colors.gray10+ }+ weight="medium"+ />+ <Text+ style={[+ styles.shareStatusText,+ isActionInProgress+ ? styles.shareStatusTextDisabled+ : null,+ ]}+ >+ {sharingStatusLabel}+ </Text>+ <SymbolView+ name="chevron.down"+ size={10}+ tintColor={+ isActionInProgress ? colors.gray9 : colors.gray10+ }+ weight="semibold"+ />+ </Pressable>+ {detail.cap.protected ? (+ <View style={styles.passwordPill}>+ <SymbolView+ name="lock.fill"+ size={12}+ tintColor={colors.gray10}+ weight="semibold"+ />+ <Text style={styles.passwordPillText}>+ Password protected+ </Text>+ </View>+ ) : null}+ </View>+ </View>+ <View style={styles.actions}>+ <ActionButton+ label={copied ? "Copied" : "Copy link"}+ accessibilityHint="Copies this Cap link"+ variant="secondary"+ onPress={copyLink}+ style={styles.actionButton}+ symbol={copied ? "checkmark" : "doc.on.doc"}+ />+ <ActionButton+ label="Share"+ accessibilityHint="Opens the native share sheet"+ variant="secondary"+ onPress={shareLink}+ style={styles.actionButton}+ symbol="square.and.arrow.up"+ />+ <ActionButton+ label={saveVideoLabel}+ accessibilityLabel={saveVideoAccessibilityLabel}+ accessibilityValue={saveVideoAccessibilityValue}+ accessibilityHint={saveVideoHint}+ variant="secondary"+ onPress={downloadVideo}+ disabled={isActionInProgress && !isSavingVideo}+ loading={isSavingVideo}+ style={styles.actionButton}+ symbol={saved ? "checkmark" : "square.and.arrow.down"}+ />+ </View>+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={`View analytics for ${detail.cap.title}`}+ accessibilityHint="Opens analytics in a browser sheet"+ onPress={viewAnalytics}+ style={({ pressed }) => [+ styles.analyticsPanel,+ pressed && styles.analyticsPanelPressed,+ ]}+ >+ <View style={styles.analyticsMetrics}>+ <AnalyticsMetric symbol="eye" value={detail.cap.viewCount} />+ <AnalyticsMetric+ symbol="text.bubble"+ value={detail.cap.commentCount}+ />+ <AnalyticsMetric+ symbol="face.smiling"+ value={detail.cap.reactionCount}+ />+ </View>+ <Text style={styles.analyticsLink}>View analytics</Text>+ </Pressable>+ {detail.summary ? (+ <GlassSurface+ fallbackStyle={styles.sectionFallback}+ isInteractive+ style={styles.section}+ tintColor={colors.gray1}+ >+ <Text style={styles.sectionTitle}>Summary</Text>+ <Text style={styles.bodyText}>{detail.summary}</Text>+ </GlassSurface>+ ) : null}+ {detail.chapters.length > 0 ? (+ <GlassSurface+ fallbackStyle={styles.sectionFallback}+ isInteractive+ style={styles.section}+ tintColor={colors.gray1}+ >+ <Text style={styles.sectionTitle}>Chapters</Text>+ {detail.chapters.map((chapter) => (+ <View+ key={`${chapter.start}-${chapter.title}`}+ style={styles.chapter}+ >+ <Text style={styles.chapterTime}>+ {Math.floor(chapter.start / 60)}:+ {Math.floor(chapter.start % 60)+ .toString()+ .padStart(2, "0")}+ </Text>+ <Text numberOfLines={2} style={styles.chapterTitle}>+ {chapter.title}+ </Text>+ </View>+ ))}+ </GlassSurface>+ ) : null}+ <GlassSurface+ fallbackStyle={styles.sectionFallback}+ isInteractive+ style={styles.section}+ tintColor={colors.gray1}+ >+ <View style={styles.sectionHeader}>+ <Text style={styles.sectionTitle}>Reactions</Text>+ <Text style={styles.countText}>{reactions.length}</Text>+ </View>+ <View style={styles.reactions}>+ {["👍", "👏", "🔥", "💙"].map((emoji) => (+ <ActionButton+ key={emoji}+ label={emoji}+ accessibilityHint="Adds this reaction"+ variant="secondary"+ onPress={() => createReaction(emoji)}+ style={styles.reactionButton}+ >+ {emoji}+ </ActionButton>+ ))}+ </View>+ </GlassSurface>+ <GlassSurface+ fallbackStyle={styles.sectionFallback}+ isInteractive+ style={styles.section}+ tintColor={colors.gray1}+ >+ <View style={styles.sectionHeader}>+ <Text style={styles.sectionTitle}>Comments</Text>+ <Text style={styles.countText}>{textComments.length}</Text>+ </View>+ <View style={styles.commentInputRow}>+ <TextInput+ accessibilityHint={commentHint}+ accessibilityLabel="Comment"+ accessibilityState={{ disabled: isActionInProgress }}+ autoCapitalize="sentences"+ autoCorrect+ editable={!isActionInProgress}+ enablesReturnKeyAutomatically+ keyboardAppearance="light"+ onChangeText={setComment}+ onSubmitEditing={() => {+ void createComment();+ }}+ placeholder="Add a comment"+ placeholderTextColor={colors.gray9}+ returnKeyType="send"+ selectionColor={colors.blue11}+ style={[+ styles.commentInput,+ isActionInProgress ? styles.commentInputDisabled : null,+ ]}+ submitBehavior="blurAndSubmit"+ value={comment}+ multiline+ />+ <ActionButton+ label={sendCommentLabel}+ accessibilityLabel={sendCommentAccessibilityLabel}+ accessibilityHint={sendCommentHint}+ onPress={createComment}+ disabled={!canSendComment && !isPostingComment}+ loading={isPostingComment}+ style={styles.sendButton}+ symbol="paperplane.fill"+ />+ </View>+ {textComments.map((item) => (+ <View key={item.id} style={styles.comment}>+ <View style={styles.commentIcon}>+ <SymbolView+ name="text.bubble"+ size={16}+ tintColor={colors.blue11}+ weight="medium"+ />+ </View>+ <View style={styles.commentBody}>+ <Text numberOfLines={1} style={styles.commentAuthor}>+ {item.author.name ?? "Cap user"}+ </Text>+ <Text style={styles.commentText}>{item.content}</Text>+ </View>+ </View>+ ))}+ </GlassSurface>+ </>+ ) : null}+ </Screen>+ <CapSettingsSheet+ cap={detail?.cap ?? null}+ visible={settingsVisible && detail !== null}+ onClose={() => setSettingsVisible(false)}+ onCopyLink={() => {+ void copyLink();+ }}+ onDelete={() => deleteCap()}+ onPassword={() => showPasswordActions()}+ onRename={() => showTitleActions()}+ onSaveVideo={() => {+ void downloadVideo();+ }}+ onShareLink={() => {+ void shareLink();+ }}+ onViewAnalytics={() => viewAnalytics()}+ onVisibilityChange={(_cap, isPublic) => {+ void updateVisibility(isPublic);+ }}+ saveDisabled={isActionInProgress}+ saveDisabledHint={saveVideoHint}+ saveDisabledValue={isSavingVideo ? undefined : "Unavailable"}+ saveDisabledAccessibilityValue={+ isSavingVideo ? saveVideoAccessibilityText : undefined+ }+ visibilityDisabled={isActionInProgress}+ visibilityDisabledHint={sharingStatusHint}+ visibilityDisabledAccessibilityValue={sharingStatusAccessibilityValue}+ />+ </KeyboardAvoidingView>+ );+}++const styles = StyleSheet.create({+ keyboard: {+ flex: 1,+ },+ headerAction: {+ width: 36,+ height: 36,+ borderRadius: radius.full,+ alignItems: "center",+ justifyContent: "center",+ },+ headerActionPressed: {+ backgroundColor: colors.gray3,+ },+ headerActionDisabled: {+ opacity: 0.55,+ },+ videoFrame: {+ width: "100%",+ aspectRatio: 16 / 9,+ borderRadius: radius.md,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.gray3,+ overflow: "hidden",+ backgroundColor: colors.black,+ marginBottom: 14,+ ...squircle,+ },+ video: {+ width: "100%",+ height: "100%",+ },+ videoPlaceholder: {+ flex: 1,+ alignItems: "center",+ justifyContent: "center",+ },+ placeholderText: {+ fontFamily: fonts.medium,+ color: colors.gray10,+ },+ titleBlock: {+ gap: 4,+ marginBottom: 14,+ },+ title: {+ fontFamily: fonts.medium,+ fontSize: 24,+ lineHeight: 30,+ color: colors.gray12,+ },+ meta: {+ fontFamily: fonts.regular,+ fontSize: 14,+ lineHeight: 20,+ color: colors.gray10,+ },+ statusRow: {+ flexDirection: "row",+ alignItems: "center",+ flexWrap: "wrap",+ gap: 8,+ marginTop: 4,+ },+ shareStatusButton: {+ minHeight: 30,+ maxWidth: "100%",+ flexDirection: "row",+ alignItems: "center",+ gap: 6,+ borderRadius: radius.full,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.gray4,+ backgroundColor: colors.gray1,+ paddingHorizontal: 11,+ ...squircle,+ },+ shareStatusButtonPressed: {+ backgroundColor: colors.gray3,+ borderColor: colors.gray5,+ },+ shareStatusButtonDisabled: {+ backgroundColor: colors.gray2,+ borderColor: colors.gray3,+ },+ shareStatusText: {+ fontFamily: fonts.regular,+ fontSize: 14,+ lineHeight: 19,+ color: colors.gray10,+ },+ shareStatusTextDisabled: {+ color: colors.gray9,+ },+ passwordPill: {+ minHeight: 30,+ maxWidth: "100%",+ flexDirection: "row",+ alignItems: "center",+ gap: 6,+ borderRadius: radius.full,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.gray4,+ backgroundColor: colors.gray1,+ paddingHorizontal: 11,+ ...squircle,+ },+ passwordPillText: {+ fontFamily: fonts.regular,+ fontSize: 14,+ lineHeight: 19,+ color: colors.gray10,+ },+ actions: {+ flexDirection: "row",+ flexWrap: "wrap",+ gap: 8,+ marginBottom: 18,+ },+ actionButton: {+ flexBasis: 112,+ flexGrow: 1,+ },+ analyticsPanel: {+ minHeight: 42,+ flexDirection: "row",+ alignItems: "center",+ justifyContent: "space-between",+ gap: 12,+ borderRadius: radius.md,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.gray3,+ backgroundColor: colors.gray1,+ paddingHorizontal: 14,+ paddingVertical: 10,+ marginBottom: 20,+ ...squircle,+ },+ analyticsPanelPressed: {+ backgroundColor: colors.gray2,+ borderColor: colors.blue10,+ },+ analyticsMetrics: {+ flexDirection: "row",+ alignItems: "center",+ flexWrap: "wrap",+ gap: 16,+ flexShrink: 1,+ },+ metric: {+ flexDirection: "row",+ alignItems: "center",+ gap: 7,+ },+ metricText: {+ fontFamily: fonts.regular,+ fontSize: 14,+ color: colors.gray12,+ },+ analyticsLink: {+ fontFamily: fonts.regular,+ fontSize: 12,+ lineHeight: 17,+ color: colors.blue11,+ },+ errorCard: {+ borderRadius: radius.md,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.gray3,+ backgroundColor: colors.gray1,+ alignItems: "center",+ gap: 10,+ paddingHorizontal: 18,+ paddingVertical: 24,+ ...squircle,+ },+ errorTitle: {+ fontFamily: fonts.medium,+ fontSize: 19,+ color: colors.gray12,+ textAlign: "center",+ },+ errorBody: {+ fontFamily: fonts.regular,+ fontSize: 14,+ lineHeight: 20,+ color: colors.gray10,+ textAlign: "center",+ },+ retryButton: {+ marginTop: 4,+ minWidth: 150,+ },+ section: {+ borderRadius: radius.md,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.gray3,+ gap: 10,+ padding: 16,+ marginBottom: 20,+ ...squircle,+ },+ sectionFallback: {+ backgroundColor: colors.gray1,+ },+ sectionHeader: {+ flexDirection: "row",+ alignItems: "center",+ gap: 8,+ },+ sectionTitle: {+ fontFamily: fonts.medium,+ fontSize: 18,+ lineHeight: 23,+ color: colors.gray12,+ },+ countText: {+ fontFamily: fonts.medium,+ fontSize: 14,+ color: colors.gray10,+ },+ bodyText: {+ fontFamily: fonts.regular,+ fontSize: 15,+ lineHeight: 23,+ color: colors.gray11,+ },+ chapter: {+ minHeight: 48,+ flexDirection: "row",+ alignItems: "center",+ gap: 10,+ borderRadius: radius.sm,+ backgroundColor: colors.gray2,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.gray3,+ padding: 10,+ ...squircle,+ },+ chapterTime: {+ width: 44,+ fontFamily: fonts.medium,+ fontSize: 13,+ color: colors.blue11,+ },+ chapterTitle: {+ flex: 1,+ fontFamily: fonts.medium,+ fontSize: 14,+ color: colors.gray12,+ },+ reactions: {+ flexDirection: "row",+ gap: 8,+ },+ reactionButton: {+ width: 52,+ },+ commentInputRow: {+ flexDirection: "row",+ alignItems: "flex-end",+ gap: 8,+ },+ commentInput: {+ flex: 1,+ minHeight: 46,+ maxHeight: 120,+ borderRadius: radius.md,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.gray4,+ backgroundColor: colors.gray2,+ paddingHorizontal: 12,+ paddingVertical: 10,+ fontFamily: fonts.regular,+ fontSize: 15,+ color: colors.gray12,+ ...squircle,+ },+ commentInputDisabled: {+ backgroundColor: colors.gray3,+ color: colors.gray10,+ },+ sendButton: {+ width: 92,+ },+ comment: {+ flexDirection: "row",+ gap: 10,+ backgroundColor: colors.gray2,+ borderRadius: radius.md,+ borderWidth: StyleSheet.hairlineWidth,+ borderColor: colors.gray3,+ padding: 12,+ ...squircle,+ },+ commentIcon: {+ width: 30,+ height: 30,+ borderRadius: radius.sm,+ alignItems: "center",+ justifyContent: "center",+ backgroundColor: colors.blue3,+ ...squircle,+ },+ commentBody: {+ flex: 1,+ minWidth: 0,+ gap: 3,+ },+ commentAuthor: {+ fontFamily: fonts.medium,+ fontSize: 14,+ color: colors.gray12,+ },+ commentText: {+ fontFamily: fonts.regular,+ fontSize: 14,+ lineHeight: 20,+ color: colors.gray11,+ },+});diff --git a/apps/mobile/src/screens/cap-detail.test.tsx b/apps/mobile/src/screens/cap-detail.test.tsxnew file mode 100644index 000000000..c987b6fae--- /dev/null+++ b/apps/mobile/src/screens/cap-detail.test.tsx@@ -0,0 +1,671 @@+import { Comment, User, Video } from "@cap/web-domain";+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 type {+ MobileCapDetail,+ MobileComment,+ MobilePlaybackResponse,+} from "@/api/mobile";+import CapDetailScreen from "../../app/caps/[id]";++type HostProps = {+ children?: ReactNode;+ [key: string]: unknown;+};++type JsonNode = ReactTestRendererJSON | ReactTestRendererJSON[] | string | null;++type AuthStub = {+ status: "signedIn";+ client: {+ createComment: ReturnType<typeof vi.fn>;+ createReaction: ReturnType<typeof vi.fn>;+ deleteCap: ReturnType<typeof vi.fn>;+ getCap: ReturnType<typeof vi.fn>;+ getPlayback: ReturnType<typeof vi.fn>;+ updateCapSharing: ReturnType<typeof vi.fn>;+ };+ refresh: ReturnType<typeof vi.fn>;+};++(+ globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const detail: MobileCapDetail = {+ cap: {+ id: Video.VideoId.make("video_123"),+ shareUrl: "https://cap.so/s/video_123",+ title: "Launch review",+ createdAt: "2026-05-18T10:00:00.000Z",+ updatedAt: "2026-05-18T10:30:00.000Z",+ ownerName: "Richie",+ durationSeconds: 125,+ thumbnailUrl: null,+ folderId: null,+ public: true,+ protected: true,+ viewCount: 17,+ commentCount: 2,+ reactionCount: 3,+ upload: null,+ },+ summary: "A short launch walkthrough.",+ chapters: [],+ transcriptionStatus: "COMPLETE",+ comments: [],+ shareUrl: "https://cap.so/s/video_123",+};++const playback: MobilePlaybackResponse = {+ kind: "mp4",+ transcriptUrl: null,+ url: "https://cap.so/video.mp4",+};++const createdComment = (content: string): MobileComment => ({+ id: Comment.CommentId.make("comment_123"),+ videoId: Video.VideoId.make("video_123"),+ type: "text",+ content,+ timestamp: null,+ parentCommentId: null,+ createdAt: "2026-05-18T10:31:00.000Z",+ updatedAt: "2026-05-18T10:31:00.000Z",+ author: {+ id: User.UserId.make("user_123"),+ name: "Richie",+ imageUrl: null,+ },+});++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 renderComponent = async (+ node: ReactElement,+): Promise<ReactTestRenderer> => {+ let renderer: ReactTestRenderer | null = null;+ await act(async () => {+ renderer = TestRenderer.create(node);+ await Promise.resolve();+ await Promise.resolve();+ });+ return renderer as unknown as ReactTestRenderer;+};++const getTextNodes = (node: JsonNode): string[] => {+ if (!node) return [];+ if (typeof node === "string") return [node];+ if (Array.isArray(node)) return node.flatMap(getTextNodes);+ return node.children?.flatMap(getTextNodes) ?? [];+};++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 resolveStyle = (+ style: unknown,+ pressed = false,+): Record<string, unknown> => {+ const resolved =+ typeof style === "function"+ ? (style as (state: { pressed: boolean }) => unknown)({ pressed })+ : style;+ const styles = Array.isArray(resolved) ? resolved : [resolved];+ return Object.assign({}, ...styles.filter(Boolean));+};++const createAuth = (): AuthStub => ({+ status: "signedIn",+ client: {+ createComment: vi.fn(),+ createReaction: vi.fn(),+ deleteCap: vi.fn(),+ getCap: vi.fn(() => Promise.resolve(detail)),+ getPlayback: vi.fn(() => Promise.resolve(playback)),+ updateCapSharing: vi.fn(),+ },+ refresh: vi.fn(() => Promise.resolve()),+});++vi.mock("react-native", async () => {+ const React = await import("react");+ const createHost =+ (name: string) =>+ ({ children, ...props }: HostProps) =>+ React.createElement(name, props, children);++ return {+ ActionSheetIOS: {+ showActionSheetWithOptions: vi.fn(),+ },+ Alert: {+ alert: vi.fn(),+ },+ KeyboardAvoidingView: createHost("KeyboardAvoidingView"),+ Linking: {+ openSettings: vi.fn(),+ },+ Platform: {+ OS: "ios",+ },+ Pressable: createHost("Pressable"),+ 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,+ },+ Text: createHost("Text"),+ TextInput: createHost("TextInput"),+ View: createHost("View"),+ };+});++vi.mock("expo-clipboard", () => ({+ setStringAsync: vi.fn(),+}));++vi.mock("expo-router", async () => {+ const React = await import("react");+ return {+ router: {+ back: vi.fn(),+ },+ Stack: {+ Screen: (props: HostProps) =>+ React.createElement("StackScreen", {+ ...props,+ testID: "stack-screen",+ }),+ },+ useLocalSearchParams: () => ({ id: "video_123" }),+ };+});++vi.mock("expo-symbols", async () => {+ const React = await import("react");+ return {+ SymbolView: (props: Record<string, unknown>) =>+ React.createElement("SymbolView", props),+ };+});++vi.mock("expo-video", async () => {+ const React = await import("react");+ return {+ VideoView: (props: Record<string, unknown>) =>+ React.createElement("VideoView", props),+ useVideoPlayer: () => ({+ replace: 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("@/caps/CapSettingsSheet", async () => {+ const React = await import("react");+ return {+ CapSettingsSheet: (props: Record<string, unknown>) =>+ React.createElement("CapSettingsSheet", {+ ...props,+ testID: "cap-settings-sheet",+ }),+ };+});++vi.mock("@/caps/passwordActions", () => ({+ showCapPasswordActions: vi.fn(),+}));++vi.mock("@/caps/saveCapVideo", () => ({+ PhotosPermissionDeniedError: class PhotosPermissionDeniedError extends Error {},+ saveCapVideoToPhotos: vi.fn(),+}));++vi.mock("@/caps/titleActions", () => ({+ showCapTitleActions: vi.fn(),+}));++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",+ {+ ...props,+ accessibilityLabel: props.accessibilityLabel ?? label,+ onPress,+ },+ children ?? label,+ ),+ };+});++vi.mock("@/components/GlassSurface", async () => {+ const React = await import("react");+ return {+ GlassSurface: ({ children }: { children?: ReactNode }) =>+ React.createElement("GlassSurface", null, children),+ };+});++vi.mock("@/components/Screen", async () => {+ const React = await import("react");+ return {+ Screen: ({+ children,+ loading,+ }: {+ children?: ReactNode;+ loading?: boolean;+ }) =>+ React.createElement(+ "Screen",+ null,+ loading ? React.createElement("Text", null, "Loading") : children,+ ),+ };+});++describe("Cap detail screen", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ authState.value = createAuth();+ });++ it("announces Cap detail load errors with a retry action", async () => {+ const auth = createAuth();+ auth.client.getCap = vi.fn(() =>+ Promise.reject(new Error("Network unavailable")),+ );+ authState.value = auth;++ const renderer = await renderComponent(+ React.createElement(CapDetailScreen),+ );+ const tree = renderer.toJSON();+ const text = getTextNodes(tree);++ expect(text).toContain("Unable to load Cap");+ expect(text).toContain("Network unavailable");+ expect(hasProp(tree, "accessibilityRole", "alert")).toBe(true);+ expect(hasProp(tree, "accessibilityLiveRegion", "polite")).toBe(true);+ expect(+ hasProp(+ tree,+ "accessibilityLabel",+ "Cap detail error: Network unavailable",+ ),+ ).toBe(true);++ const [retryButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Try again",+ });+ if (!retryButton)+ throw new Error("Cap detail retry action was not rendered");+ expect(retryButton.props.accessibilityHint).toBe("Reloads this Cap");++ await act(async () => {+ retryButton.props.onPress();+ await Promise.resolve();+ });++ expect(auth.client.getCap).toHaveBeenCalledTimes(2);+ });++ it("shows web-matching sharing, analytics, and action labels", async () => {+ const renderer = await renderComponent(+ React.createElement(CapDetailScreen),+ );+ const tree = renderer.toJSON();+ const text = getTextNodes(tree);++ expect(text).toContain("Launch review");+ expect(text).toContain("Shared");+ expect(text).toContain("Password protected");+ expect(text).toContain("17");+ expect(text).toContain("2");+ expect(text).toContain("3");+ expect(text).toContain("Copy link");+ expect(text).toContain("Save video");+ expect(text).toContain("View analytics");+ expect(hasProp(tree, "accessibilityHint", "Copies this Cap link")).toBe(+ true,+ );+ expect(+ hasProp(tree, "accessibilityHint", "Opens the native share sheet"),+ ).toBe(true);+ expect(+ hasProp(tree, "accessibilityHint", "Saves this video to Photos"),+ ).toBe(true);+ expect(+ hasProp(tree, "accessibilityLabel", "Change sharing for Launch review"),+ ).toBe(true);+ expect(hasProp(tree, "accessibilityHint", "Opens sharing settings")).toBe(+ true,+ );+ expect(+ hasProp(tree, "accessibilityLabel", "View analytics for Launch review"),+ ).toBe(true);+ expect(+ hasProp(tree, "accessibilityHint", "Opens analytics in a browser sheet"),+ ).toBe(true);+ });++ it("uses native affordances for the header menu and comment composer", async () => {+ const renderer = await renderComponent(+ React.createElement(CapDetailScreen),+ );+ const stackScreen = renderer.root.findByProps({+ testID: "stack-screen",+ });+ const headerRight = stackScreen.props.options+ .headerRight as () => ReactNode;+ let headerRenderer: ReactTestRenderer | null = null;++ await act(async () => {+ headerRenderer = TestRenderer.create(headerRight() as ReactElement);+ });++ const headerAction = (+ headerRenderer as unknown as ReactTestRenderer+ ).root.findByProps({+ accessibilityLabel: "More actions",+ });+ expect(headerAction.props.accessibilityState).toEqual({+ disabled: false,+ });+ expect(headerAction.props.accessibilityHint).toBe("Opens Cap settings");+ expect(headerAction.props.hitSlop).toBe(10);+ expect(resolveStyle(headerAction.props.style, true)).toMatchObject({+ backgroundColor: "#f0f0f0",+ });++ const [commentInput] = renderer.root.findAllByProps({+ accessibilityLabel: "Comment",+ });+ if (!commentInput) throw new Error("Comment input was not rendered");++ expect(commentInput.props.accessibilityState).toEqual({+ disabled: false,+ });+ expect(commentInput.props.enablesReturnKeyAutomatically).toBe(true);+ expect(commentInput.props.keyboardAppearance).toBe("light");+ expect(commentInput.props.returnKeyType).toBe("send");+ expect(commentInput.props.selectionColor).toBe("#0d74ce");+ expect(commentInput.props.submitBehavior).toBe("blurAndSubmit");++ const [disabledSend] = renderer.root.findAllByProps({+ accessibilityLabel: "Send comment",+ });+ expect(disabledSend?.props.disabled).toBe(true);++ await act(async () => {+ commentInput.props.onChangeText("Ship it");+ });++ const [enabledSend] = renderer.root.findAllByProps({+ accessibilityLabel: "Send comment",+ });+ expect(enabledSend?.props.disabled).toBe(false);+ });++ it("opens native settings from the sharing status", async () => {+ const renderer = await renderComponent(+ React.createElement(CapDetailScreen),+ );+ const [shareStatus] = renderer.root.findAllByProps({+ accessibilityLabel: "Change sharing for Launch review",+ });+ if (!shareStatus) throw new Error("Sharing status row was not rendered");++ await act(async () => {+ shareStatus.props.onPress();+ });++ const [sheet] = renderer.root.findAllByProps({+ testID: "cap-settings-sheet",+ });+ expect(sheet?.props.visible).toBe(true);+ });++ it("opens analytics in the native browser sheet", async () => {+ const renderer = await renderComponent(+ React.createElement(CapDetailScreen),+ );+ const [analytics] = renderer.root.findAllByProps({+ accessibilityLabel: "View analytics for Launch review",+ });+ if (!analytics) throw new Error("Analytics row was not rendered");++ const WebBrowser = await import("expo-web-browser");+ const openBrowserAsync = vi.mocked(WebBrowser.openBrowserAsync);+ openBrowserAsync.mockClear();++ await act(async () => {+ analytics.props.onPress();+ });++ expect(openBrowserAsync).toHaveBeenCalledWith(+ "https://cap.so/dashboard/analytics?capId=video_123",+ );+ });++ it("shows a save-specific busy state without blocking sharing as saving", async () => {+ const saveDeferred = createDeferred<string>();+ const { saveCapVideoToPhotos } = await import("@/caps/saveCapVideo");+ vi.mocked(saveCapVideoToPhotos).mockReturnValueOnce(saveDeferred.promise);+ const renderer = await renderComponent(+ React.createElement(CapDetailScreen),+ );+ const [saveButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Save video",+ });+ if (!saveButton) throw new Error("Save video button was not rendered");++ await act(async () => {+ saveButton.props.onPress();+ await Promise.resolve();+ });++ const [savingButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Save video",+ });+ if (!savingButton) throw new Error("Saving button was not rendered");+ expect(savingButton.props.loading).toBe(true);+ expect(savingButton.props.accessibilityHint).toBe("Save is in progress");+ expect(savingButton.props.accessibilityValue).toEqual({+ text: "Saving video for Launch review",+ });++ const [sheet] = renderer.root.findAllByProps({+ testID: "cap-settings-sheet",+ });+ expect(sheet?.props.saveDisabled).toBe(true);+ expect(sheet?.props.saveDisabledHint).toBe("Save is in progress");+ expect(sheet?.props.saveDisabledValue).toBeUndefined();+ expect(sheet?.props.saveDisabledAccessibilityValue).toBe(+ "Saving video for Launch review",+ );+ expect(sheet?.props.visibilityDisabled).toBe(true);+ expect(sheet?.props.visibilityDisabledHint).toBe(+ "Current Cap action is in progress",+ );+ expect(sheet?.props.visibilityDisabledValue).toBeUndefined();++ await act(async () => {+ saveDeferred.resolve("Launch review.mp4");+ await saveDeferred.promise;+ });++ expect(getTextNodes(renderer.toJSON())).toContain("Saved");+ });++ it("keeps save idle while a comment is sending", async () => {+ const commentDeferred = createDeferred<MobileComment>();+ const auth = createAuth();+ auth.client.createComment.mockReturnValueOnce(commentDeferred.promise);+ authState.value = auth;+ const renderer = await renderComponent(+ React.createElement(CapDetailScreen),+ );+ const [commentInput] = renderer.root.findAllByProps({+ accessibilityLabel: "Comment",+ });+ if (!commentInput) throw new Error("Comment input was not rendered");++ await act(async () => {+ commentInput.props.onChangeText("Ship it");+ });++ const [sendButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Send comment",+ });+ if (!sendButton) throw new Error("Send button was not rendered");++ await act(async () => {+ sendButton.props.onPress();+ await Promise.resolve();+ });++ const [sendingButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Sending comment on Launch review",+ });+ const [saveButton] = renderer.root.findAllByProps({+ accessibilityLabel: "Save video",+ });+ if (!sendingButton) throw new Error("Sending button was not rendered");+ if (!saveButton) throw new Error("Save video button was not rendered");++ expect(sendingButton.props.loading).toBe(true);+ expect(sendingButton.props.accessibilityHint).toBe("Comment is being sent");+ expect(saveButton.props.loading).toBe(false);+ expect(saveButton.props.disabled).toBe(true);+ expect(saveButton.props.accessibilityHint).toBe(+ "Current Cap action is in progress",+ );+ expect(getTextNodes(renderer.toJSON())).not.toContain("Saving...");++ const [sheet] = renderer.root.findAllByProps({+ testID: "cap-settings-sheet",+ });+ expect(sheet?.props.saveDisabledValue).toBe("Unavailable");+ expect(sheet?.props.visibilityDisabledValue).toBeUndefined();++ await act(async () => {+ commentDeferred.resolve(createdComment("Ship it"));+ await commentDeferred.promise;+ });++ expect(getTextNodes(renderer.toJSON())).toContain("Ship it");+ });++ it("marks the settings sheet sharing row as updating during visibility changes", async () => {+ const sharingDeferred = createDeferred<MobileCapDetail["cap"]>();+ const auth = createAuth();+ auth.client.updateCapSharing.mockReturnValueOnce(sharingDeferred.promise);+ authState.value = auth;+ const renderer = await renderComponent(+ React.createElement(CapDetailScreen),+ );+ const [sheet] = renderer.root.findAllByProps({+ testID: "cap-settings-sheet",+ });+ if (!sheet) throw new Error("Cap settings sheet was not rendered");++ await act(async () => {+ sheet.props.onVisibilityChange(detail.cap, false);+ await Promise.resolve();+ });++ const [busySheet] = renderer.root.findAllByProps({+ testID: "cap-settings-sheet",+ });+ const [sharingStatus] = renderer.root.findAllByProps({+ accessibilityLabel: "Change sharing for Launch review",+ });+ expect(auth.client.updateCapSharing).toHaveBeenCalledWith("video_123", {+ public: false,+ });+ expect(sharingStatus?.props.accessibilityHint).toBe(+ "Sharing update is in progress",+ );+ expect(sharingStatus?.props.accessibilityState).toEqual({+ disabled: true,+ });+ expect(sharingStatus?.props.accessibilityValue).toEqual({+ text: "Updating sharing for Launch review",+ });+ expect(getTextNodes(renderer.toJSON())).toContain("Shared");+ expect(getTextNodes(renderer.toJSON())).not.toContain("Updating...");+ expect(busySheet?.props.visibilityDisabled).toBe(true);+ expect(busySheet?.props.visibilityDisabledHint).toBe(+ "Sharing update is in progress",+ );+ expect(busySheet?.props.visibilityDisabledValue).toBeUndefined();+ expect(busySheet?.props.visibilityDisabledAccessibilityValue).toBe(+ "Updating sharing for Launch review",+ );+ expect(busySheet?.props.saveDisabledValue).toBe("Unavailable");++ await act(async () => {+ sharingDeferred.resolve({ ...detail.cap, public: false });+ await sharingDeferred.promise;+ });+ });+});