Skip to content
TypeScript

refactor(mobile): media previews share file leases and close on blur in one place (#25527)

Julius Marminge220eb73524ca
diff --git a/apps/mobile/src/components/ComposerContextAttachment.tsx b/apps/mobile/src/components/ComposerContextAttachment.tsx
index b198c5add65..edb5522f3d0 100644
--- a/apps/mobile/src/components/ComposerContextAttachment.tsx
+++ b/apps/mobile/src/components/ComposerContextAttachment.tsx
@@ -5,10 +5,13 @@ import * as Dialog from "./ui/Dialog";
import type { ComposerContextRecord, EnvironmentId } from "@t3tools/contracts";
import { Pressable, View } from "react-native";
import { Image } from "expo-image";
-import { useEffect, useId, useState } from "react";
+import { useId, useState } from "react";
import type { DraftComposerAttachment } from "../lib/composerImages";
import { composerAttachmentInlineUri, isFileBackedComposerAttachment } from "../lib/composerImages";
-import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
+import {
+ loadLocalAttachmentPreview,
+ useLocalAttachmentPreview,
+} from "../lib/localAttachmentPreview";
import { downloadAndShareAttachment } from "../lib/attachmentDownload";
import { assetImageSource } from "../lib/assetImageSource";
import { useAssetUrlState, useRefreshAssetUrl } from "../state/assets";
@@ -35,31 +38,13 @@ export function ComposerContextAttachment(props: {
const remoteEnvironmentId = local || inlineUri ? null : (props.environmentId ?? null);
const asset = useAssetUrlState(remoteEnvironmentId, resource);
const refresh = useRefreshAssetUrl(remoteEnvironmentId, resource);
- const [localUri, setLocalUri] = useState<string | null>(null);
- const [error, setError] = useState<string | null>(null);
+ const localPreview = useLocalAttachmentPreview(local ?? null);
+ const error = localPreview.error ? "The local file is unavailable. Attach it again." : null;
const [sharing, setSharing] = useState(false);
const [previewOpen, setPreviewOpen] = useState(false);
- useEffect(() => {
- if (!local) return;
- const controller = new AbortController();
- let dispose: (() => void) | undefined;
- void loadLocalAttachmentPreview(local, controller.signal)
- .then((preview) => {
- if (!preview) return;
- if (controller.signal.aborted) return preview.dispose();
- dispose = preview.dispose;
- setLocalUri(preview.uri);
- setError(null);
- })
- .catch(() => {
- if (!controller.signal.aborted) setError("The local file is unavailable. Attach it again.");
- });
- return () => {
- controller.abort();
- dispose?.();
- };
- }, [local]);
- const uri = local ? localUri : (inlineUri ?? (asset._tag === "Success" ? asset.url : null));
+ const uri = local
+ ? localPreview.uri
+ : (inlineUri ?? (asset._tag === "Success" ? asset.url : null));
const share = async () => {
if (sharing) return;
setSharing(true);
diff --git a/apps/mobile/src/components/FilePreviewModal.tsx b/apps/mobile/src/components/FilePreviewModal.tsx
index 77116c88001..8079379fd48 100644
--- a/apps/mobile/src/components/FilePreviewModal.tsx
+++ b/apps/mobile/src/components/FilePreviewModal.tsx
@@ -1,15 +1,5 @@
import * as Dialog from "./ui/Dialog";
-import { useNavigation } from "@react-navigation/native";
-import {
- useCallback,
- useContext,
- useEffect,
- useEffectEvent,
- useState,
- useSyncExternalStore,
- useMemo,
-} from "react";
-import { Keyboard } from "react-native";
+import { useContext, useEffect, useEffectEvent, useState } from "react";
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
import {
@@ -17,7 +7,8 @@ import {
nativeViewerErrorMessage,
shareLocalAttachment,
} from "../lib/attachmentDownload";
-import { useRefreshAssetUrl } from "../state/assets";
+import { usePreviewPresentation } from "../lib/previewPresentation";
+import { refreshAssetUrl } from "../state/assets";
import { filePreviewGallery, filePreviewKey, filePreviewName } from "../lib/filePreviewGallery";
import { FilePreviewGallery } from "./FilePreviewGallery";
import { FilePreview } from "./FilePreview";
@@ -33,77 +24,47 @@ export type {
ResolvedFilePreviewSource,
} from "./FilePreviewModal.types";
-function PreviewItemResolver(props: {
- readonly source: FilePreviewItem;
- readonly onResolved: (source: ResolvedFilePreviewSource) => void;
- readonly onRequestClose: () => void;
- readonly onOpenError?: (error: unknown) => void;
-}) {
- const { source } = props;
- const environmentId = "environmentId" in source ? source.environmentId : null;
- const refreshAssetUrl = useRefreshAssetUrl(
- environmentId,
- "resource" in source ? source.resource : null,
- );
- // Resolve once per presentation; background URL refreshes must not reopen the native viewer.
- const [uri, setUri] = useState<string | null>("uri" in source ? source.uri : null);
- const onRequestClose = useEffectEvent(props.onRequestClose);
- const onResolutionError = useEffectEvent((error: unknown, fallbackMessage: string) => {
- if (props.onOpenError) props.onOpenError(error);
- else Dialog.alert("Could not open preview", fallbackMessage);
- onRequestClose();
- });
- useEffect(() => Keyboard.dismiss(), []);
- useEffect(() => {
- if (environmentId === null || uri !== null) return;
- let cancelled = false;
- // Refresh expired URLs before handing them to Quick Look or ACTION_VIEW, which retain them.
- void refreshAssetUrl()
- .then((url) => {
- if (cancelled) return;
- if (!url) throw new Error("Reconnect to this environment and try again.");
- setUri(url + (source.srcFragment ?? ""));
- })
- .catch((error: unknown) => {
- if (cancelled) return;
- onResolutionError(
- error,
- "Reconnect to this environment and try again. The file may have been moved or deleted.",
- );
- });
- return () => {
- cancelled = true;
- };
- }, [environmentId, uri, refreshAssetUrl, source.srcFragment]);
- useEffect(() => {
- if (!("attachment" in source)) return;
- const controller = new AbortController();
- let release: (() => void) | undefined;
- void loadLocalAttachmentPreview(source.attachment, controller.signal)
- .then((file) => {
- if (!file) return;
- if (controller.signal.aborted) {
- file.dispose();
- return;
- }
- release = file.dispose;
- setUri(file.uri);
- })
- .catch((error: unknown) => {
- if (controller.signal.aborted) return;
- onResolutionError(error, "Attach the file again and retry.");
- });
- return () => {
- controller.abort();
- release?.();
- };
- }, [source]);
+class PreviewResolutionError extends Error {
+ constructor(
+ override readonly cause: unknown,
+ readonly fallbackMessage: string,
+ ) {
+ super(fallbackMessage, { cause });
+ }
+}
- const onResolved = useEffectEvent(props.onResolved);
- useEffect(() => {
- if (uri !== null) onResolved({ ...source, name: filePreviewName(source), uri });
- }, [uri, source]);
- return null;
+interface ResolvedPreviewItem {
+ readonly source: ResolvedFilePreviewSource;
+ readonly dispose?: () => void;
+}
+
+async function resolvePreviewItem(
+ item: FilePreviewItem,
+ signal: AbortSignal,
+): Promise<ResolvedPreviewItem | null> {
+ const name = filePreviewName(item);
+ if ("attachment" in item) {
+ const file = await loadLocalAttachmentPreview(item.attachment, signal).catch(
+ (error: unknown) => {
+ throw new PreviewResolutionError(error, "Attach the file again and retry.");
+ },
+ );
+ return file && { source: { ...item, name, uri: file.uri }, dispose: file.dispose };
+ }
+ if (!("environmentId" in item)) return { source: { ...item, name } };
+ // Refresh expired URLs before handing them to Quick Look or ACTION_VIEW, which retain them.
+ const url = await refreshAssetUrl(item.environmentId, item.resource, signal)
+ .then((value) => {
+ if (!value) throw new Error("Reconnect to this environment and try again.");
+ return value;
+ })
+ .catch((error: unknown) => {
+ throw new PreviewResolutionError(
+ error,
+ "Reconnect to this environment and try again. The file may have been moved or deleted.",
+ );
+ });
+ return { source: { ...item, name, uri: url + (item.srcFragment ?? "") } };
}
function ResolvedFilePreview(props: {
@@ -113,25 +74,60 @@ function ResolvedFilePreview(props: {
}) {
// Freeze the group at opening; streaming messages and URL refreshes must not reopen the viewer.
const [items] = useState(() => filePreviewGallery(props.source, []));
- const [resolved, setResolved] = useState<Record<string, ResolvedFilePreviewSource>>({});
- const onResolved = useCallback((item: ResolvedFilePreviewSource, key: string) => {
- setResolved((current) => ({ ...current, [key]: item }));
- }, []);
- const selected = resolved[filePreviewKey(props.source)];
- const gallery = useMemo(
- () =>
- items.flatMap((item) => {
- const value = resolved[filePreviewKey(item)];
- return value ? [value] : [];
- }),
- [items, resolved],
+ const selectedKey = filePreviewKey(props.source);
+ const [gallery, setGallery] = useState<readonly ResolvedFilePreviewSource[] | null>(() =>
+ items.every((item) => "uri" in item)
+ ? items.map((item) => ({ ...item, name: filePreviewName(item) }))
+ : null,
);
- const ready = selected && gallery.length === items.length;
+ const onResolutionError = useEffectEvent((error: PreviewResolutionError) => {
+ if (props.onOpenError) props.onOpenError(error.cause);
+ else Dialog.alert("Could not open preview", error.fallbackMessage);
+ props.onRequestClose();
+ });
+ // Resolves once per presentation and holds local file leases until it closes.
+ useEffect(() => {
+ if (items.every((item) => "uri" in item)) return;
+ const controller = new AbortController();
+ // The first failure closes the preview at once and cancels the rest of the gallery.
+ const fail = (error: unknown) => {
+ if (controller.signal.aborted) return;
+ controller.abort();
+ onResolutionError(
+ error instanceof PreviewResolutionError
+ ? error
+ : new PreviewResolutionError(error, "Try again."),
+ );
+ };
+ const resolving = Promise.allSettled(
+ items.map((item) =>
+ resolvePreviewItem(item, controller.signal).catch((error: unknown) => {
+ fail(error);
+ throw error;
+ }),
+ ),
+ );
+ void resolving.then((settled) => {
+ if (controller.signal.aborted) return;
+ const sources = settled.flatMap((item) =>
+ item.status === "fulfilled" && item.value ? [item.value.source] : [],
+ );
+ if (sources.length === items.length) setGallery(sources);
+ });
+ return () => {
+ controller.abort();
+ void resolving.then((settled) => {
+ for (const item of settled) if (item.status === "fulfilled") item.value?.dispose?.();
+ });
+ };
+ }, [items]);
+ const selected = gallery?.[items.findIndex((item) => filePreviewKey(item) === selectedKey)];
+ if (!gallery || !selected) return null;
const onOpenError = (error: unknown) => {
if (props.onOpenError) return props.onOpenError(error);
Dialog.alert("Could not open preview", nativeViewerErrorMessage(error), [
{ text: "Cancel", style: "cancel" },
- ...(selected?.kind === "document"
+ ...(selected.kind === "document"
? [
{
text: "Save or share",
@@ -154,24 +150,11 @@ function ResolvedFilePreview(props: {
]);
};
return (
- <>
- {items.map((item) => (
- <PreviewItemResolver
- key={filePreviewKey(item)}
- source={item}
- onResolved={(value) => onResolved(value, filePreviewKey(item))}
- onRequestClose={props.onRequestClose}
- onOpenError={props.onOpenError}
- />
- ))}
- {ready ? (
- <FilePreview
- source={{ ...selected, gallery }}
- onRequestClose={props.onRequestClose}
- onOpenError={onOpenError}
- />
- ) : null}
- </>
+ <FilePreview
+ source={{ ...selected, gallery }}
+ onRequestClose={props.onRequestClose}
+ onOpenError={onOpenError}
+ />
);
}
@@ -182,41 +165,13 @@ export function FilePreviewModal(props: {
readonly onOpenError?: (error: unknown) => void;
}) {
const group = useContext(FilePreviewGallery);
- const source = useMemo(
- () =>
- props.source === null
- ? null
- : {
- ...props.source,
- gallery: filePreviewGallery(props.source, group),
- },
- [props.source, group],
- );
- const navigation = useNavigation();
- const subscribeToFocus = useCallback(
- (listener: () => void) => {
- const offFocus = navigation.addListener("focus", listener);
- const offBlur = navigation.addListener("blur", listener);
- return () => {
- offFocus();
- offBlur();
- };
- },
- [navigation],
- );
- // The legacy envelope's focus context may describe a different route than this v5 card.
- const isFocused = useSyncExternalStore(
- subscribeToFocus,
- navigation.isFocused,
- navigation.isFocused,
- );
- const hasSource = props.source !== null;
- const onRequestClose = useEffectEvent(props.onRequestClose);
- useEffect(() => {
- if (!isFocused && hasSource) onRequestClose();
- }, [isFocused, hasSource]);
+ const source =
+ props.source === null
+ ? null
+ : { ...props.source, gallery: filePreviewGallery(props.source, group) };
+ usePreviewPresentation(source && filePreviewKey(source), props.onRequestClose);
- if (!source || !isFocused) return null;
+ if (!source) return null;
return (
<ResolvedFilePreview
key={filePreviewKey(source)}
diff --git a/apps/mobile/src/components/PdfPreview.android.tsx b/apps/mobile/src/components/PdfPreview.android.tsx
index 5492c4ce7c6..32e79d576e1 100644
--- a/apps/mobile/src/components/PdfPreview.android.tsx
+++ b/apps/mobile/src/components/PdfPreview.android.tsx
@@ -1,4 +1,8 @@
-import { useEffect, useRef, useState } from "react";
+import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
+import { Atom, AsyncResult } from "effect/reactivity";
+import { useState } from "react";
import { View } from "react-native";
import Pdf from "react-native-pdf-jsi";
@@ -7,39 +11,55 @@ import { pdfInitialPage, pdfLinkUrl, preparePdfPreview } from "../lib/pdfPreview
import { tryOpenExternalUrl } from "../lib/openExternalUrl";
import { ControlPill } from "./ui/ControlPill";
-function NativePdfPreview(props: { readonly uri: string; readonly onRetry: () => void }) {
- const [localUri, setLocalUri] = useState<string | null>(null);
- const [error, setError] = useState<string | null>(null);
- const cached = useRef<Awaited<ReturnType<typeof preparePdfPreview>>>(null);
+const preparedPdfAtom = Atom.family((uri: string) =>
+ Atom.make(
+ // The downloaded copy lives as long as a viewer reads it; Retry refreshes the atom,
+ // which closes the scope and discards the copy before downloading again. Acquisition
+ // stays interruptible so closing the viewer aborts the download.
+ Effect.acquireRelease(
+ Effect.tryPromise({
+ try: (signal) => {
+ const prepared = preparePdfPreview(uri, signal);
+ // An interrupt can land after the copy exists but before acquireRelease owns it.
+ signal.addEventListener("abort", () => {
+ void prepared.then(
+ (file) => file?.dispose(),
+ () => undefined,
+ );
+ });
+ return prepared;
+ },
+ catch: (cause) => (cause instanceof Error ? cause.message : "The PDF could not be loaded."),
+ }).pipe(
+ Effect.flatMap((file) => (file === null ? Effect.interrupt : Effect.succeed(file))),
+ Effect.interruptible,
+ ),
+ (file) => Effect.sync(file.dispose),
+ ),
+ ).pipe(Atom.withLabel(`android-pdf-preview:${uri}`)),
+);
- useEffect(() => {
- const controller = new AbortController();
- void preparePdfPreview(props.uri, controller.signal)
- .then((file) => {
- if (controller.signal.aborted) file?.dispose();
- else {
- cached.current = file;
- setLocalUri(file?.uri ?? null);
- }
- })
- .catch((cause: unknown) => {
- if (!controller.signal.aborted) {
- setError(cause instanceof Error ? cause.message : "The PDF could not be loaded.");
- }
- });
- return () => {
- controller.abort();
- cached.current?.dispose();
- cached.current = null;
- };
- }, [props.uri]);
+export function PdfPreview(props: { readonly uri: string }) {
+ const atom = preparedPdfAtom(props.uri);
+ const prepared = useAtomValue(atom);
+ const refresh = useAtomRefresh(atom);
+ // A render failure belongs to the downloaded copy that failed; Retry replaces it.
+ const [unrenderable, setUnrenderable] = useState<unknown>(null);
+ const file = prepared._tag === "Success" && !prepared.waiting ? prepared.value : null;
+ const error =
+ file !== null && unrenderable === file
+ ? "The PDF could not be rendered. It may be damaged or password protected."
+ : prepared._tag === "Failure" && !prepared.waiting
+ ? Option.getOrElse(AsyncResult.error(prepared), () => "The PDF could not be loaded.")
+ : null;
+ const localUri = file?.uri ?? null;
if (error) {
return (
<View className="flex-1 gap-4 bg-card">
<FilePreviewNotice title="Could not load PDF">{error}</FilePreviewNotice>
<View className="items-center">
- <ControlPill label="Try again" variant="pill" onPress={props.onRetry} />
+ <ControlPill label="Try again" variant="pill" onPress={refresh} />
</View>
</View>
);
@@ -59,22 +79,9 @@ function NativePdfPreview(props: { readonly uri: string; readonly onRetry: () =>
if (url !== null) void tryOpenExternalUrl(url, "file-preview");
}}
onError={() => {
- cached.current?.dispose();
- cached.current = null;
- setError("The PDF could not be rendered. It may be damaged or password protected.");
+ setUnrenderable(file);
}}
style={{ flex: 1, width: "100%" }}
/>
);
}
-
-export function PdfPreview(props: { readonly uri: string }) {
- const [attempt, setAttempt] = useState(0);
- return (
- <NativePdfPreview
- key={`${props.uri}:${attempt}`}
- uri={props.uri}
- onRetry={() => setAttempt((value) => value + 1)}
- />
- );
-}
diff --git a/apps/mobile/src/components/VideoPreviewModal.ios.tsx b/apps/mobile/src/components/VideoPreviewModal.ios.tsx
index 0eec525abba..5479e1be521 100644
--- a/apps/mobile/src/components/VideoPreviewModal.ios.tsx
+++ b/apps/mobile/src/components/VideoPreviewModal.ios.tsx
@@ -1,15 +1,14 @@
import * as Dialog from "./ui/Dialog";
-import { useIsFocused } from "@react-navigation/native";
import { requireNativeModule } from "expo";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { AsyncResult } from "effect/reactivity";
-import { useEffect, useEffectEvent, useId, useState } from "react";
-import { Keyboard } from "react-native";
+import { useEffect, useEffectEvent, useId } from "react";
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
+import { usePreviewPresentation, videoPreviewKey } from "../lib/previewPresentation";
import { fullscreenVideoClosed, fullscreenVideoOpened } from "../lib/videoAudioSession";
import { mediaVideoPreviewUri, type VideoPreviewSource } from "../lib/videoPreviewSource";
-import { useAssetUrlState, useRefreshAssetUrl } from "../state/assets";
+import { refreshAssetUrl } from "../state/assets";
import { usePreparedConnection } from "../state/session";
import {
acquireAudioSession,
@@ -44,43 +43,29 @@ function NativeVideoPreview(props: {
const onRequestClose = useEffectEvent(props.onRequestClose);
const environmentId =
source.type === "media" && "environmentId" in source ? source.environmentId : null;
- const resource = source.type === "media" && "resource" in source ? source.resource : null;
const preparedConnection = usePreparedConnection(environmentId);
- const assetUrl = useAssetUrlState(environmentId, resource);
- const refreshAssetUrl = useEffectEvent(useRefreshAssetUrl(environmentId, resource));
const name = source.type === "media" ? source.name : source.attachment.name;
- // The first minted URL is kept so a background refresh does not restart playback.
- const resolvedUrl =
- source.type === "media"
- ? mediaVideoPreviewUri(source, assetUrl._tag === "Success" ? assetUrl.url : null)
- : null;
- const [playbackUrl, setPlaybackUrl] = useState<string | null>(resolvedUrl);
- const loadError =
- resource !== null && playbackUrl === null
- ? preparedConnection._tag === "None"
+ // Mints a fresh URL for each presentation: AVKit retains the URL and offers no retry,
+ // so a cached link that expired while the app was suspended would fail to play.
+ const resolvePlaybackUrl = useEffectEvent(async (): Promise<string> => {
+ if (source.type !== "media") throw new Error("Could not load this video.");
+ if (!("resource" in source)) return source.uri;
+ const url = await refreshAssetUrl(source.environmentId, source.resource);
+ const playbackUrl = mediaVideoPreviewUri(source, url);
+ if (playbackUrl !== null) return playbackUrl;
+ throw new Error(
+ preparedConnection._tag === "None"
? "Reconnect to this environment and open the video again."
- : assetUrl._tag === "Failure"
- ? "Could not load this video. Check the connection and try again."
- : null
- : null;
+ : "Could not load this video. Check the connection and try again.",
+ );
+ });
+ const reauthorize = useEffectEvent(() => {
+ if (source.type === "media" && "resource" in source) {
+ void refreshAssetUrl(source.environmentId, source.resource);
+ }
+ });
- useEffect(() => Keyboard.dismiss(), []);
useEffect(() => {
- fullscreenVideoOpened();
- return () => fullscreenVideoClosed();
- }, []);
- useEffect(() => {
- // oxlint-disable-next-line react/set-state-in-effect -- The native player latches the first resolved URL to keep its playback session.
- if (playbackUrl === null && resolvedUrl !== null) setPlaybackUrl(resolvedUrl);
- }, [playbackUrl, resolvedUrl]);
- useEffect(() => {
- if (!loadError) return;
- Dialog.alert("Could not open video", loadError);
- onRequestClose();
- }, [loadError]);
-
- useEffect(() => {
- if (localAttachment === null && playbackUrl === null) return;
const controller = new AbortController();
let token: ReturnType<typeof acquireAudioSession> | null = null;
const release = () => {
@@ -106,12 +91,14 @@ function NativeVideoPreview(props: {
} else release();
});
let ready = false;
+ fullscreenVideoOpened();
void (async () => {
const file =
localAttachment !== null
? await loadLocalAttachmentPreview(localAttachment, controller.signal)
: null;
if (localAttachment !== null && !file) return;
+ const uri = file?.uri ?? (await resolvePlaybackUrl());
if (controller.signal.aborted) {
file?.dispose();
return;
@@ -125,12 +112,7 @@ function NativeVideoPreview(props: {
}
ready = true;
const presented = await settlePromise(() =>
- NativeControls.presentVideo(
- file?.uri ?? playbackUrl!,
- name,
- source.sourceIdentifier ?? "",
- identifier,
- ),
+ NativeControls.presentVideo(uri, name, source.sourceIdentifier ?? "", identifier),
);
// Native completion follows dismissal, so local playback keeps its file lease.
file?.dispose();
@@ -140,8 +122,8 @@ function NativeVideoPreview(props: {
})().catch((error: unknown) => {
release();
if (controller.signal.aborted) return;
- // AVKit gives no retry, so re-mint now; the cached URL may simply have expired.
- if (ready) void refreshAssetUrl();
+ // AVKit gives no retry, so re-mint now; the minted URL may already be unusable.
+ if (ready) reauthorize();
Dialog.alert(
"Could not open video",
ready
@@ -154,11 +136,12 @@ function NativeVideoPreview(props: {
});
return () => {
controller.abort();
+ fullscreenVideoClosed();
subscription.remove();
release();
void NativeControls.dismissVideo(identifier).catch(() => undefined);
};
- }, [localAttachment, name, source.sourceIdentifier, playbackUrl, identifier]);
+ }, [localAttachment, name, source.sourceIdentifier, identifier]);
return null;
}
@@ -167,13 +150,10 @@ export function VideoPreviewModal(props: {
readonly source: VideoPreviewSource | null;
readonly onRequestClose: () => void;
}) {
- const isFocused = useIsFocused();
- const hasSource = props.source !== null;
- const onRequestClose = useEffectEvent(props.onRequestClose);
- useEffect(() => {
- if (!isFocused && hasSource) onRequestClose();
- }, [isFocused, hasSource]);
-
- if (!props.source || !isFocused) return null;
+ usePreviewPresentation(
+ props.source === null ? null : videoPreviewKey(props.source),
+ props.onRequestClose,
+ );
+ if (!props.source) return null;
return <NativeVideoPreview source={props.source} onRequestClose={props.onRequestClose} />;
}
diff --git a/apps/mobile/src/components/VideoPreviewModal.tsx b/apps/mobile/src/components/VideoPreviewModal.tsx
index 9b2b64c68c4..4e63851dcd3 100644
--- a/apps/mobile/src/components/VideoPreviewModal.tsx
+++ b/apps/mobile/src/components/VideoPreviewModal.tsx
@@ -1,11 +1,10 @@
-import { useIsFocused } from "@react-navigation/native";
import { videoMimeType } from "@t3tools/shared/video";
-import { useEffect, useEffectEvent, useState } from "react";
-import { Keyboard, Modal, Pressable, View } from "react-native";
+import { Modal, Pressable, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppActivityIndicator } from "./ui/AppActivityIndicator";
-import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
+import { useLocalAttachmentPreview } from "../lib/localAttachmentPreview";
+import { usePreviewPresentation, videoPreviewKey } from "../lib/previewPresentation";
import { useMediaActions } from "../state/mediaActions";
import { type MediaActionsSource } from "../lib/mediaActionsSource";
import {
@@ -56,40 +55,9 @@ function useMediaPlayback(source: MediaVideoPreviewSource): PlaybackState {
function useLocalPlayback(source: LocalVideoPreviewSource): PlaybackState {
const { attachment } = source;
- const [uri, setUri] = useState<string | null>(null);
- const [error, setError] = useState<string | null>(null);
- // Keep the file lease across metadata updates while Android is playing it.
- const loadAttachment = useEffectEvent((signal: AbortSignal) =>
- loadLocalAttachmentPreview(attachment, signal),
- );
- const { id: attachmentId, fileUri } = attachment;
- useEffect(() => {
- // oxlint-disable-next-line react/set-state-in-effect -- A new attachment clears the previous attachment's result before loading.
- setUri(null);
- setError(null);
- const controller = new AbortController();
- const loading = loadAttachment(controller.signal);
- void loading.then(
- (file) => {
- if (file === null) return;
- if (controller.signal.aborted) file.dispose();
- else setUri(file.uri);
- },
- (cause: unknown) => {
- if (!controller.signal.aborted) {
- setError(cause instanceof Error ? cause.message : "Could not load this video.");
- }
- },
- );
- return () => {
- controller.abort();
- void loading.then(
- (file) => file?.dispose(),
- () => undefined,
- );
- };
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A different attachment restarts the load even when it resolves to the same cached file URI.
- }, [attachmentId, fileUri]);
+ const preview = useLocalAttachmentPreview(attachment);
+ const { uri } = preview;
+ const error = preview.error ? preview.error.message || "Could not load this video." : null;
const mimeType = videoMimeType(attachment) ?? attachment.mimeType;
return {
uri,
@@ -137,7 +105,6 @@ function OpenVideoPreviewModal(props: {
const insets = useSafeAreaInsets();
const mediaActions = useMediaActions(playback.actionsSource, props.onRequestClose);
- useEffect(() => Keyboard.dismiss(), []);
return (
<Modal
visible
@@ -208,23 +175,21 @@ export function VideoPreviewModal(props: {
readonly source: VideoPreviewSource | null;
readonly onRequestClose: () => void;
}) {
- const isFocused = useIsFocused();
- const hasSource = props.source !== null;
- const { onRequestClose } = props;
- useEffect(() => {
- if (!isFocused && hasSource) onRequestClose();
- }, [isFocused, hasSource, onRequestClose]);
+ usePreviewPresentation(
+ props.source === null ? null : videoPreviewKey(props.source),
+ props.onRequestClose,
+ );
const { source } = props;
- if (source === null || !isFocused) return null;
+ if (source === null) return null;
return source.type === "local" ? (
<LocalPreviewModal
- key={`local:${source.attachment.id}:${source.attachment.fileUri}`}
+ key={videoPreviewKey(source)}
source={source}
onRequestClose={props.onRequestClose}
/>
) : (
<MediaPreviewModal
- key={mediaVideoThumbnailKey(source)}
+ key={videoPreviewKey(source)}
source={source}
onRequestClose={props.onRequestClose}
/>
diff --git a/apps/mobile/src/components/VideoThumbnailImage.tsx b/apps/mobile/src/components/VideoThumbnailImage.tsx
index cfb8ceeb2ac..6f6fea83063 100644
--- a/apps/mobile/src/components/VideoThumbnailImage.tsx
+++ b/apps/mobile/src/components/VideoThumbnailImage.tsx
@@ -1,38 +1,53 @@
+import { useAtomValue } from "@effect/atom-react";
+import * as Effect from "effect/Effect";
+import { Atom, AsyncResult } from "effect/reactivity";
import { Image } from "expo-image";
import { useIsFocused } from "@react-navigation/native";
import type { VideoThumbnail } from "expo-video";
-import { useEffect, useState } from "react";
import { StyleSheet } from "react-native";
import type { DraftComposerFileAttachment } from "../lib/composerImages";
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
import { cachedVideoThumbnail, loadVideoThumbnail } from "../lib/videoThumbnails";
+interface VideoThumbnailTarget {
+ readonly cacheKey: string;
+ readonly source: string | DraftComposerFileAttachment;
+}
+
+// Plain-object keys compare structurally (Effect `Equal`/`Hash`).
+const videoThumbnailAtom = Atom.family((target: VideoThumbnailTarget) =>
+ Atom.make(
+ Effect.promise((signal) =>
+ loadVideoThumbnail(
+ target.cacheKey,
+ async (sourceSignal) =>
+ typeof target.source === "string"
+ ? { uri: target.source, dispose: () => undefined }
+ : loadLocalAttachmentPreview(target.source, sourceSignal),
+ signal,
+ ),
+ ),
+ ).pipe(Atom.withLabel(`video-thumbnail:${target.cacheKey}`)),
+);
+
+const noVideoThumbnail = Atom.make(AsyncResult.initial<VideoThumbnail | null>()).pipe(
+ Atom.withLabel("video-thumbnail:none"),
+);
+
export function VideoThumbnailImage(props: {
readonly cacheKey: string;
readonly source: string | DraftComposerFileAttachment | null;
readonly contentFit?: "cover" | "contain";
}) {
const { cacheKey, source } = props;
+ // Extraction runs only while the screen is focused; leaving it interrupts the load.
const isFocused = useIsFocused();
- const [loaded, setLoaded] = useState<{ key: string; thumbnail: VideoThumbnail } | null>(null);
- const thumbnail = loaded?.key === cacheKey ? loaded.thumbnail : cachedVideoThumbnail(cacheKey);
-
- useEffect(() => {
- if (!source || !isFocused) return;
- const controller = new AbortController();
- void loadVideoThumbnail(
- cacheKey,
- async (signal) =>
- typeof source === "string"
- ? { uri: source, dispose: () => undefined }
- : loadLocalAttachmentPreview(source, signal),
- controller.signal,
- ).then((thumbnail) => {
- if (thumbnail && !controller.signal.aborted) setLoaded({ key: cacheKey, thumbnail });
- });
- return () => controller.abort();
- }, [cacheKey, source, isFocused]);
+ const loaded = useAtomValue(
+ source && isFocused ? videoThumbnailAtom({ cacheKey, source }) : noVideoThumbnail,
+ );
+ const thumbnail =
+ (loaded._tag === "Success" ? loaded.value : null) ?? cachedVideoThumbnail(cacheKey);
return thumbnail ? (
<Image
diff --git a/apps/mobile/src/features/files/AttachmentFileScreen.tsx b/apps/mobile/src/features/files/AttachmentFileScreen.tsx
index a88b561fbec..493efc7cf0d 100644
--- a/apps/mobile/src/features/files/AttachmentFileScreen.tsx
+++ b/apps/mobile/src/features/files/AttachmentFileScreen.tsx
@@ -5,7 +5,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native"
import type { MenuAction } from "@react-native-menu/menu";
import { EnvironmentId } from "@t3tools/contracts";
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
-import { useEffect, useRef, useState } from "react";
+import { useRef, useState } from "react";
import { Platform, View } from "react-native";
import {
@@ -165,12 +165,11 @@ export function AttachmentFileScreen(props: AttachmentFileScreenProps) {
if (navigation.canGoBack()) navigation.goBack();
};
const { uri, resource } = document;
- useEffect(() => {
- if (nativeViewer !== "pending" || !uri) return;
- // oxlint-disable-next-line react/set-state-in-effect -- Presenting the viewer waits on the resolved file.
+ // A file only the native viewer can show opens it as soon as the file resolves.
+ if (nativeViewer === "pending" && uri) {
setNativeViewer("open");
setNativeOpen(true);
- }, [nativeViewer, uri]);
+ }
// Mint a fresh URL: cached URLs may expire in the background before Quick Look or ACTION_VIEW opens.
const nativeSource = ((): FilePreviewSource | null => {
const kind = nativeKind ?? "document";
diff --git a/apps/mobile/src/lib/attachmentDocument.ts b/apps/mobile/src/lib/attachmentDocument.ts
index c19e2826898..09650d2be1a 100644
--- a/apps/mobile/src/lib/attachmentDocument.ts
+++ b/apps/mobile/src/lib/attachmentDocument.ts
@@ -1,18 +1,21 @@
-import { AsyncResult } from "effect/reactivity";
+import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
+import { Atom, AsyncResult } from "effect/reactivity";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import * as Dialog from "../components/ui/Dialog";
import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
-import type { EnvironmentId } from "@t3tools/contracts";
+import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";
import { fetch } from "expo/fetch";
import { File } from "expo-file-system";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
import { useEffect, useRef, useState } from "react";
import type { FileBackedComposerAttachment } from "./composerImages";
-import { loadLocalAttachmentPreview } from "./localAttachmentPreview";
+import { localAttachmentPreviewAtom, localAttachmentPreviewState } from "./localAttachmentPreview";
import { downloadAndShareAttachment, shareLocalAttachment } from "./attachmentDownload";
-import { useRefreshAssetUrl } from "../state/assets";
+import { refreshAssetUrl, useFreshAssetUrl, useRefreshAssetUrl } from "../state/assets";
import { attachmentDocumentPresentation } from "./attachmentDocumentPresentation";
const isLocalUri = (uri: string) => /^(file|content):/.test(uri);
@@ -20,6 +23,55 @@ const isLocalUri = (uri: string) => /^(file|content):/.test(uri);
/** Signed asset URLs live for an hour; treat anything older than this as worth re-minting. */
const STALE_URL_MS = 5 * 60_000;
+interface AttachmentTextKey {
+ readonly uri: string;
+ /** When a remote `uri` was signed; null for local files. */
+ readonly authorizedAt: number | null;
+ readonly environmentId: EnvironmentId | null;
+ readonly resource: AssetResource;
+ readonly sizeBytes: number;
+ readonly revision: number;
+}
+
+async function readAttachmentText(key: AttachmentTextKey, signal: AbortSignal) {
+ if (isLocalUri(key.uri)) {
+ return readFilePreviewResponse({ ok: true, body: new File(key.uri).readableStream() }, signal);
+ }
+ // Reauthorize before source reads; the opening URL may have expired.
+ let target = key.uri;
+ if (key.authorizedAt === null || Date.now() - key.authorizedAt > STALE_URL_MS) {
+ const refreshed =
+ key.environmentId === null
+ ? null
+ : await refreshAssetUrl(key.environmentId, key.resource, signal);
+ if (!refreshed) throw new Error("Reconnect to this environment and try again.");
+ target = refreshed;
+ }
+ const response = await fetch(target, {
+ signal,
+ headers: {
+ ...(key.sizeBytes > 0 ? { Range: `bytes=0-${FILE_TEXT_PREVIEW_MAX_BYTES}` } : {}),
+ ...(key.revision > 0 ? { "Cache-Control": "no-cache" } : {}),
+ },
+ });
+ return readFilePreviewResponse(response, signal);
+}
+
+// Plain-object keys compare structurally (Effect `Equal`/`Hash`). Unmounting the
+// last reader interrupts the read, which aborts the fetch.
+const attachmentTextAtom = Atom.family((key: AttachmentTextKey) =>
+ Atom.make(
+ Effect.tryPromise({
+ try: (signal) => readAttachmentText(key, signal),
+ catch: (cause) => (cause instanceof Error ? cause : new Error("Could not read this file.")),
+ }),
+ ).pipe(Atom.withLabel("attachment-text")),
+);
+
+const noAttachmentText = Atom.make(
+ AsyncResult.initial<{ text: string; truncated: boolean }, Error>(),
+).pipe(Atom.withLabel("attachment-text:none"));
+
/** Captured bytes never resolve against the workspace. */
export function useAttachmentDocument(input: {
readonly name: string;
@@ -42,117 +94,45 @@ export function useAttachmentDocument(input: {
};
const environmentId = input.attachment ? null : input.environmentId;
const refresh = useRefreshAssetUrl(environmentId, resource);
- const [localUri, setLocalUri] = useState<string | null>(null);
- const [remoteUri, setRemoteUri] = useState<string | null>(null);
- const [content, setContent] = useState<{ text: string; truncated: boolean } | null>(null);
- const table = content && delimiter ? parseDelimitedPreview(content.text, delimiter) : null;
- const [error, setError] = useState<string | null>(null);
- const [contentError, setContentError] = useState<string | null>(null);
- const textReadUrl = useRef<{ uri: string; authorizedAt: number } | null>(null);
const [rendered, setRendered] = useState(true);
+ const [revision, setRevision] = useState(0);
+ const [sharing, setSharing] = useState(false);
+ const attachment = input.attachment;
+ const localPreviewAtom = localAttachmentPreviewAtom(attachment);
+ const localPreview = localAttachmentPreviewState(useAtomValue(localPreviewAtom));
+ const refreshLocalPreview = useAtomRefresh(localPreviewAtom);
+ const remote = useFreshAssetUrl(environmentId, attachment ? null : resource, revision);
+ const remoteUrl = AsyncResult.isSuccess(remote) && !remote.waiting ? remote.value : null;
+ const uri = attachment ? localPreview.uri : (remoteUrl?.url ?? null);
+ const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);
+ const text = useAtomValue(
+ uri && needsText
+ ? attachmentTextAtom({
+ uri,
+ authorizedAt: remoteUrl?.authorizedAt ?? null,
+ environmentId,
+ resource,
+ sizeBytes: input.sizeBytes,
+ revision,
+ })
+ : noAttachmentText,
+ );
+ const content = AsyncResult.isSuccess(text) ? text.value : null;
+ const contentError = AsyncResult.isFailure(text)
+ ? (Option.getOrNull(AsyncResult.error(text))?.message ?? "Could not read this file.")
+ : null;
+ const table = content && delimiter ? parseDelimitedPreview(content.text, delimiter) : null;
const presentation = attachmentDocumentPresentation({
kind,
hasTable: table !== null,
hasEnvironment: input.environmentId !== null,
rendered,
});
- const [revision, setRevision] = useState(0);
- const [sharing, setSharing] = useState(false);
- const uri = input.attachment ? localUri : remoteUri;
- const attachment = input.attachment;
- useEffect(() => {
- if (attachment) return;
- let cancelled = false;
- // Await a fresh signed URL: cached links can expire while the client is suspended.
- // oxlint-disable-next-line react/set-state-in-effect -- A new preview request clears its previous URL and error.
- setRemoteUri(null);
- setError(null);
- textReadUrl.current = null;
- void refresh()
- .then((url) => {
- if (cancelled) return;
- if (!url) throw new Error("Reconnect to this environment and try again.");
- textReadUrl.current = { uri: url, authorizedAt: Date.now() };
- setRemoteUri(url);
- })
- .catch((cause: unknown) => {
- if (!cancelled)
- setError(cause instanceof Error ? cause.message : "The attachment is unavailable.");
- });
- return () => {
- cancelled = true;
- };
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reauthorize the remote file.
- }, [attachment, refresh, revision]);
- useEffect(() => {
- if (!attachment) return;
- // Clear old attachment bytes or a failed load could share them under the new name.
- // oxlint-disable-next-line react/set-state-in-effect -- A new attachment invalidates the last one.
- setLocalUri(null);
- setContent(null);
- setContentError(null);
- const controller = new AbortController();
- let release: (() => void) | undefined;
- void loadLocalAttachmentPreview(attachment, controller.signal)
- .then((file) => {
- if (!file) return;
- if (controller.signal.aborted) return file.dispose();
- release = file.dispose;
- setLocalUri(file.uri);
- setError(null);
- })
- .catch((cause: unknown) => {
- if (!controller.signal.aborted)
- setError(cause instanceof Error ? cause.message : "The local file is unavailable.");
- });
- return () => {
- controller.abort();
- release?.();
- };
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reacquire a local file lease after a failed load.
- }, [attachment, revision]);
- const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);
- const sizeBytes = input.sizeBytes;
- useEffect(() => {
- if (!uri || !needsText) return;
- const controller = new AbortController();
- // oxlint-disable-next-line react/set-state-in-effect -- A new external resource must clear the previous response before loading.
- setContent(null);
- setContentError(null);
- const response = isLocalUri(uri)
- ? Promise.resolve().then(() => ({ ok: true, body: new File(uri).readableStream() }))
- : (async () => {
- // Reauthorize before source reads; the opening URL may have expired.
- const authorized = textReadUrl.current;
- let target = authorized?.uri ?? uri;
- if (!authorized || Date.now() - authorized.authorizedAt > STALE_URL_MS) {
- const refreshed = await refresh();
- if (!refreshed) throw new Error("Reconnect to this environment and try again.");
- target = refreshed;
- if (!controller.signal.aborted) {
- // Keep the source-read URL and its age together without restarting active media.
- textReadUrl.current = { uri: refreshed, authorizedAt: Date.now() };
- }
- }
- return fetch(target, {
- signal: controller.signal,
- headers: {
- ...(sizeBytes > 0 ? { Range: `bytes=0-${FILE_TEXT_PREVIEW_MAX_BYTES}` } : {}),
- ...(revision > 0 ? { "Cache-Control": "no-cache" } : {}),
- },
- });
- })();
- void response
- .then((value) => readFilePreviewResponse(value, controller.signal))
- .then((value) => {
- if (!controller.signal.aborted) setContent(value);
- })
- .catch((cause: unknown) => {
- if (!controller.signal.aborted)
- setContentError(cause instanceof Error ? cause.message : "Could not read this file.");
- });
- return () => controller.abort();
- }, [uri, needsText, revision, sizeBytes, refresh]);
+ const error = attachment
+ ? localPreview.error && (localPreview.error.message || "The local file is unavailable.")
+ : AsyncResult.isFailure(remote)
+ ? (Option.getOrNull(AsyncResult.error(remote))?.message ?? "The attachment is unavailable.")
+ : null;
const share = async () => {
if (!uri || sharing) return;
setSharing(true);
@@ -185,12 +165,15 @@ export function useAttachmentDocument(input: {
resource,
content,
table,
- error: error ?? (needsText ? contentError : null),
+ error: error ?? contentError,
needsText,
rendered,
setRendered,
revision,
- retry: () => setRevision((value) => value + 1),
+ retry: () => {
+ setRevision((value) => value + 1);
+ if (attachment) refreshLocalPreview();
+ },
share,
sharing,
};
diff --git a/apps/mobile/src/lib/localAttachmentPreview.test.ts b/apps/mobile/src/lib/localAttachmentPreview.test.ts
index 8b6926f11a3..6f747189ed3 100644
--- a/apps/mobile/src/lib/localAttachmentPreview.test.ts
+++ b/apps/mobile/src/lib/localAttachmentPreview.test.ts
@@ -24,7 +24,14 @@ vi.mock("expo-file-system", () => ({
},
}));
-import { loadLocalAttachmentPreview } from "./localAttachmentPreview";
+import { AtomRegistry, type AsyncResult } from "effect/reactivity";
+
+import {
+ loadLocalAttachmentPreview,
+ localAttachmentPreviewAtom,
+ type LocalAttachmentPreviewState,
+ localAttachmentPreviewState,
+} from "./localAttachmentPreview";
const attachment = {
type: "file" as const,
@@ -93,3 +100,51 @@ describe("loadLocalAttachmentPreview", () => {
},
);
});
+
+describe("localAttachmentPreviewAtom", () => {
+ const settled = (
+ registry: AtomRegistry.AtomRegistry,
+ target: typeof attachment,
+ ): { state: Promise<LocalAttachmentPreviewState>; unsubscribe: () => void } => {
+ const atom = localAttachmentPreviewAtom(target);
+ const { promise, resolve } = Promise.withResolvers<LocalAttachmentPreviewState>();
+ const onChange = (result: AsyncResult.AsyncResult<unknown, unknown>) => {
+ if (result._tag !== "Initial") resolve(localAttachmentPreviewState(registry.get(atom)));
+ };
+ const unsubscribe = registry.subscribe(atom, onChange, { immediate: true });
+ return { state: promise, unsubscribe };
+ };
+
+ it("shares one lease per file and releases it when the last reader leaves", async () => {
+ const released = Promise.withResolvers<void>();
+ const release = vi.fn(() => released.resolve());
+ mocks.retain.mockReturnValueOnce(release);
+ const registry = AtomRegistry.make();
+ const first = settled(registry, attachment);
+ // A metadata update on the same draft file reads the same lease.
+ const renamed = settled(registry, { ...attachment, name: "renamed.mov" });
+ expect((await first.state).uri).toContain("/Documents/");
+ expect((await renamed.state).uri).toBe((await first.state).uri);
+ expect(mocks.retain).toHaveBeenCalledTimes(1);
+ first.unsubscribe();
+ expect(release).not.toHaveBeenCalled();
+ renamed.unsubscribe();
+ // The scope finalizer runs on the Effect scheduler; await the release itself.
+ await released.promise;
+ expect(release).toHaveBeenCalledTimes(1);
+ registry.dispose();
+ });
+
+ it("reports a missing file as an error", async () => {
+ mocks.exists.mockReturnValue(false);
+ const registry = AtomRegistry.make();
+ const reader = settled(registry, { ...attachment, id: "missing" });
+ const state = await reader.state;
+ expect(state.uri).toBeNull();
+ expect(state.error?.message).toBe(
+ "This attachment is no longer available. Attach the file again.",
+ );
+ reader.unsubscribe();
+ registry.dispose();
+ });
+});
diff --git a/apps/mobile/src/lib/localAttachmentPreview.ts b/apps/mobile/src/lib/localAttachmentPreview.ts
index e144fe09dfe..1957001371b 100644
--- a/apps/mobile/src/lib/localAttachmentPreview.ts
+++ b/apps/mobile/src/lib/localAttachmentPreview.ts
@@ -1,4 +1,10 @@
+import { useAtomValue } from "@effect/atom-react";
import { videoMimeType } from "@t3tools/shared/video";
+import * as Effect from "effect/Effect";
+import * as Equal from "effect/Equal";
+import * as Hash from "effect/Hash";
+import * as Option from "effect/Option";
+import { Atom, AsyncResult } from "effect/reactivity";
import type { FileBackedComposerAttachment } from "./composerImages";
import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
@@ -59,3 +65,69 @@ export async function loadLocalAttachmentPreview(
throw new Error("This attachment is no longer available. Attach the file again.", { cause });
}
}
+
+/**
+ * Keyed by file identity only: a metadata update on the same draft must not
+ * dispose the lease of a file a viewer is still showing.
+ */
+class LocalAttachmentPreviewKey implements Equal.Equal {
+ constructor(readonly attachment: FileBackedComposerAttachment) {}
+ [Equal.symbol](that: unknown): boolean {
+ return (
+ that instanceof LocalAttachmentPreviewKey &&
+ that.attachment.id === this.attachment.id &&
+ that.attachment.fileUri === this.attachment.fileUri
+ );
+ }
+ [Hash.symbol](): number {
+ return Hash.string(`${this.attachment.id}\u0000${this.attachment.fileUri}`);
+ }
+}
+
+const localAttachmentPreviewFamily = Atom.family((key: LocalAttachmentPreviewKey) =>
+ Atom.make(
+ // The lease lives as long as the atom: unmounting the last reader (or a
+ // refresh) closes the scope and releases the file.
+ Effect.acquireRelease(
+ Effect.tryPromise({
+ try: (signal) => loadLocalAttachmentPreview(key.attachment, signal),
+ catch: (cause) =>
+ cause instanceof Error ? cause : new Error("The local file is unavailable."),
+ }).pipe(Effect.flatMap((file) => (file === null ? Effect.interrupt : Effect.succeed(file)))),
+ (file) => Effect.sync(file.dispose),
+ ),
+ ).pipe(Atom.withLabel(`local-attachment-preview:${key.attachment.id}`)),
+);
+
+const noLocalAttachmentPreview = Atom.make(
+ AsyncResult.initial<AttachmentPreviewFile, Error>(),
+).pipe(Atom.withLabel("local-attachment-preview:none"));
+
+export function localAttachmentPreviewAtom(
+ attachment: FileBackedComposerAttachment | null,
+): Atom.Atom<AsyncResult.AsyncResult<AttachmentPreviewFile, Error>> {
+ return attachment === null
+ ? noLocalAttachmentPreview
+ : localAttachmentPreviewFamily(new LocalAttachmentPreviewKey(attachment));
+}
+
+export interface LocalAttachmentPreviewState {
+ readonly uri: string | null;
+ readonly error: Error | null;
+}
+
+export function localAttachmentPreviewState(
+ result: AsyncResult.AsyncResult<AttachmentPreviewFile, Error>,
+): LocalAttachmentPreviewState {
+ return {
+ // A refresh has already released the previous lease while it reacquires.
+ uri: result._tag === "Success" && !result.waiting ? result.value.uri : null,
+ error: result._tag === "Failure" ? Option.getOrNull(AsyncResult.error(result)) : null,
+ };
+}
+
+export function useLocalAttachmentPreview(
+ attachment: FileBackedComposerAttachment | null,
+): LocalAttachmentPreviewState {
+ return localAttachmentPreviewState(useAtomValue(localAttachmentPreviewAtom(attachment)));
+}
diff --git a/apps/mobile/src/lib/previewPresentation.ts b/apps/mobile/src/lib/previewPresentation.ts
new file mode 100644
index 00000000000..16ff63eb365
--- /dev/null
+++ b/apps/mobile/src/lib/previewPresentation.ts
@@ -0,0 +1,38 @@
+import { useNavigation } from "@react-navigation/native";
+import { useEffect, useEffectEvent } from "react";
+import { Keyboard } from "react-native";
+
+import { mediaVideoThumbnailKey, type VideoPreviewSource } from "./videoPreviewSource";
+
+/** Identity of a video preview: a different file is a new presentation. */
+export function videoPreviewKey(source: VideoPreviewSource): string {
+ return source.type === "local"
+ ? `local:${source.attachment.id}:${source.attachment.fileUri}`
+ : mediaVideoThumbnailKey(source);
+}
+
+/**
+ * A full-screen preview owns the screen while it is open: each presented
+ * source dismisses the keyboard, and the preview closes when its route loses
+ * focus, so navigating away never leaves a native viewer or modal behind.
+ * `presentationKey` is the presented source's identity, or null when closed.
+ */
+export function usePreviewPresentation(
+ presentationKey: string | null,
+ onRequestClose: () => void,
+): void {
+ // The v5 card host sits inside a legacy presentation envelope whose focus context
+ // can describe a different route. The preview belongs to this navigation route.
+ const navigation = useNavigation();
+ const close = useEffectEvent(onRequestClose);
+ // oxlint-disable-next-line t3code/react-effect-budget -- Navigation blur is an external event and the open state belongs to the caller.
+ useEffect(() => {
+ if (presentationKey === null) return;
+ Keyboard.dismiss();
+ if (!navigation.isFocused()) {
+ close();
+ return;
+ }
+ return navigation.addListener("blur", () => close());
+ }, [presentationKey, navigation]);
+}
diff --git a/apps/mobile/src/lib/useMediaVideoPlayback.test.tsx b/apps/mobile/src/lib/useMediaVideoPlayback.test.tsx
index 703a1acd3ff..c52563b4b4e 100644
--- a/apps/mobile/src/lib/useMediaVideoPlayback.test.tsx
+++ b/apps/mobile/src/lib/useMediaVideoPlayback.test.tsx
@@ -1,3 +1,5 @@
+import { RegistryContext } from "@effect/atom-react";
+import { AtomRegistry } from "effect/reactivity";
import { act, type ReactNode } from "react";
import { createRoot } from "react-dom/client";
import type { AppStateStatus } from "react-native";
@@ -158,38 +160,43 @@ function setup(kind: "thread" | "PR", compact = false) {
mocks.thumbnail.mockReset().mockResolvedValue(null);
const container = document.createElement("div");
const root = createRoot(container);
+ // Configured like the app's registry: the React default keeps unmounted atoms for 400ms,
+ // which would hold thumbnail loads open across renders and tests.
+ const registry = AtomRegistry.make();
const environmentId = EnvironmentId.make("test");
return {
render(visible = true) {
act(() =>
root.render(
- kind === "thread" ? (
- <ThreadMediaVisibleContext value={visible}>
- <ThreadMarkdownVideo
- source={{
- type: "media",
- name: "clip.mp4",
- mimeType: "video/mp4",
- environmentId,
- resource: {
- _tag: "github-media",
- cwd: "/project",
- url: "https://github.com/user-attachments/assets/video",
- },
- }}
- />
- </ThreadMediaVisibleContext>
- ) : (
- <PullRequestMediaContext value={{ environmentId, cwd: "/project" }}>
- <PullRequestMediaVisibleContext value={visible}>
- <PullRequestMedia
- url="https://github.com/user-attachments/assets/video"
- kind="video"
- compact={compact}
+ <RegistryContext.Provider value={registry}>
+ {kind === "thread" ? (
+ <ThreadMediaVisibleContext value={visible}>
+ <ThreadMarkdownVideo
+ source={{
+ type: "media",
+ name: "clip.mp4",
+ mimeType: "video/mp4",
+ environmentId,
+ resource: {
+ _tag: "github-media",
+ cwd: "/project",
+ url: "https://github.com/user-attachments/assets/video",
+ },
+ }}
/>
- </PullRequestMediaVisibleContext>
- </PullRequestMediaContext>
- ),
+ </ThreadMediaVisibleContext>
+ ) : (
+ <PullRequestMediaContext value={{ environmentId, cwd: "/project" }}>
+ <PullRequestMediaVisibleContext value={visible}>
+ <PullRequestMedia
+ url="https://github.com/user-attachments/assets/video"
+ kind="video"
+ compact={compact}
+ />
+ </PullRequestMediaVisibleContext>
+ </PullRequestMediaContext>
+ )}
+ </RegistryContext.Provider>,
),
);
},
@@ -215,6 +222,7 @@ function setup(kind: "thread" | "PR", compact = false) {
},
[Symbol.dispose]() {
act(() => root.unmount());
+ registry.dispose();
},
};
}
@@ -263,14 +271,16 @@ it.each([false, true])(
"stops inactive PR thumbnail requests (compact: %s) and restarts on return",
async (compact) => {
using screen = setup("PR", compact);
+ mocks.thumbnail.mockReturnValue(new Promise(() => {}));
screen.render(false);
expect(mocks.thumbnail).not.toHaveBeenCalled();
await act(async () => screen.render(true));
expect(mocks.thumbnail).toHaveBeenCalledTimes(1);
const signal = mocks.thumbnail.mock.calls[0]![2];
expect(signal.aborted).toBe(false);
+ const aborted = new Promise((resolve) => signal.addEventListener("abort", resolve));
screen.render(false);
- expect(signal.aborted).toBe(true);
+ await act(() => aborted);
expect(mocks.thumbnail).toHaveBeenCalledTimes(1);
await act(async () => screen.render(true));
expect(mocks.thumbnail).toHaveBeenCalledTimes(2);
diff --git a/apps/mobile/src/state/assets.ts b/apps/mobile/src/state/assets.ts
index 37ae24ecc05..3eb0d2fe718 100644
--- a/apps/mobile/src/state/assets.ts
+++ b/apps/mobile/src/state/assets.ts
@@ -7,12 +7,16 @@ import {
createProjectFaviconUrlAtomFamily,
EMPTY_ASSET_URL_ATOM,
} from "@t3tools/client-runtime/state/assets";
+import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import { Atom, AsyncResult } from "effect/reactivity";
import { useCallback } from "react";
import { connectionAtomRuntime } from "../connection/runtime";
import { projectFaviconDatabaseCache } from "../lib/projectFaviconDatabaseCache";
import { type AssetUrlState, deriveAssetUrlState } from "./asset-url-state";
+import { appAtomRegistry } from "./atom-registry";
import { environmentProjectCloneListAtom } from "./projectClones";
import { environmentSession, usePreparedConnection } from "./session";
import { useEnvironmentPresentation } from "./presentation";
@@ -92,3 +96,79 @@ export function useRefreshAssetUrl(
return state._tag === "Success" ? state.url : null;
}, [createUrl, environmentId, httpBaseUrl, resource]);
}
+
+/** {@link useRefreshAssetUrl} for async tasks that resolve several resources at once. */
+export async function refreshAssetUrl(
+ environmentId: EnvironmentId,
+ resource: AssetResource,
+ signal?: AbortSignal,
+): Promise<string | null> {
+ const connectionAtom = environmentSession.preparedConnectionValueAtom(environmentId);
+ if (appAtomRegistry.get(connectionAtom)._tag === "None") return null;
+ const atom = assetEnvironment.createUrl({ environmentId, input: { resource } });
+ const result = await executeAtomQuery(appAtomRegistry, atom, {
+ label: atom.label?.[0] ?? "asset url",
+ refresh: true,
+ reportFailure: false,
+ ...(signal ? { signal } : {}),
+ });
+ // The query can wait through a reconnect; resolve against the connection that answered it.
+ const connection = appAtomRegistry.get(connectionAtom);
+ if (connection._tag === "None") return null;
+ const state = assetUrlStateFromResult(result, connection.value.httpBaseUrl);
+ return state._tag === "Success" ? state.url : null;
+}
+
+export interface AuthorizedAssetUrl {
+ readonly url: string;
+ readonly authorizedAt: number;
+}
+
+interface FreshAssetUrlKey {
+ readonly environmentId: EnvironmentId | null;
+ readonly resource: AssetResource;
+ /** A reconnect changes the base URL, and any URL minted against the old one is unusable. */
+ readonly httpBaseUrl: string | null;
+ /** Bumped by Retry so a file replaced on disk is reauthorized. */
+ readonly revision: number;
+}
+
+// Plain-object keys compare structurally (Effect `Equal`/`Hash`).
+const freshAssetUrlFamily = Atom.family((key: FreshAssetUrlKey) =>
+ Atom.make(
+ Effect.tryPromise({
+ try: async (signal): Promise<AuthorizedAssetUrl> => {
+ const url =
+ key.environmentId === null
+ ? null
+ : await refreshAssetUrl(key.environmentId, key.resource, signal);
+ if (!url) throw new Error("Reconnect to this environment and try again.");
+ return { url, authorizedAt: Date.now() };
+ },
+ catch: (cause) =>
+ cause instanceof Error ? cause : new Error("The attachment is unavailable."),
+ }),
+ ).pipe(Atom.withLabel("fresh-asset-url")),
+);
+
+const noFreshAssetUrl = Atom.make(AsyncResult.initial<AuthorizedAssetUrl, Error>()).pipe(
+ Atom.withLabel("fresh-asset-url:none"),
+);
+
+/**
+ * A signed URL minted when the reader mounts, not a cached one: cached links can
+ * expire while the client is suspended.
+ */
+export function useFreshAssetUrl(
+ environmentId: EnvironmentId | null,
+ resource: AssetResource | null,
+ revision: number,
+): AsyncResult.AsyncResult<AuthorizedAssetUrl, Error> {
+ const connection = usePreparedConnection(environmentId);
+ const httpBaseUrl = connection._tag === "Some" ? connection.value.httpBaseUrl : null;
+ return useAtomValue(
+ resource === null
+ ? noFreshAssetUrl
+ : freshAssetUrlFamily({ environmentId, resource, httpBaseUrl, revision }),
+ );
+}