Skip to content
TypeScript

fix(mobile): iOS image previews open without waiting for the gallery (#29044)

shivam70738cbd8aa9
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
index a5b8f7a44e3..f1d338a5478 100644
--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
@@ -66,7 +66,8 @@ public final class T3NativeControlsModule: Module {
identifier: identifier, promise: promise)
}.runOnQueue(.main)
- AsyncFunction("presentFiles") { (urls: [URL], titles: [String], selectedIndex: Int, sourceIdentifiers: [String], identifier: String, promise: Promise) in
+ // A nil URL is still resolving in JS and arrives later through updateFile.
+ AsyncFunction("presentFiles") { (urls: [URL?], titles: [String], selectedIndex: Int, sourceIdentifiers: [String], identifier: String, promise: Promise) in
guard !urls.isEmpty, urls.count == titles.count, urls.count == sourceIdentifiers.count,
urls.indices.contains(selectedIndex)
else {
@@ -81,6 +82,11 @@ public final class T3NativeControlsModule: Module {
file.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter)
}.runOnQueue(.main)
+ // A nil URL marks the item as one that could not be resolved.
+ AsyncFunction("updateFile") { (identifier: String, index: Int, url: URL?) in
+ if self.filePresentation?.identifier == identifier { self.filePresentation?.update(index: index, url: url) }
+ }.runOnQueue(.main)
+
OnDestroy {
let presentation = self.videoPresentation
let file = self.filePresentation
diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift
index 0ebc2420e77..791e39b2840 100644
--- a/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift
+++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift
@@ -8,24 +8,71 @@ private final class FilePreviewItem: NSObject, QLPreviewItem {
var previewItemTitle: String?
}
+private enum FilePreviewState { case loading, ready, failed }
+
private final class FilePreviewController: QLPreviewController {
var onAppear: (() -> Void)?
+ // Quick Look shows a blank page for an item without a file, so loading and failure are ours to show.
+ private let spinner = UIActivityIndicatorView(style: .large)
+ private let failure = UILabel()
+ var state = FilePreviewState.ready {
+ didSet { if isViewLoaded { showState() } }
+ }
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+ failure.text = "This image could not be loaded."
+ failure.textColor = .secondaryLabel
+ failure.textAlignment = .center
+ failure.numberOfLines = 0
+ for status in [spinner, failure] as [UIView] {
+ status.isUserInteractionEnabled = false
+ status.translatesAutoresizingMaskIntoConstraints = false
+ view.addSubview(status)
+ NSLayoutConstraint.activate([
+ status.centerXAnchor.constraint(equalTo: view.centerXAnchor),
+ status.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 64),
+ status.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, constant: -48),
+ ])
+ }
+ showState()
+ }
+
+ override func viewDidLayoutSubviews() {
+ super.viewDidLayoutSubviews()
+ view.bringSubviewToFront(spinner)
+ view.bringSubviewToFront(failure)
+ }
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
onAppear?()
}
+
+ private func showState() {
+ if state == .loading { spinner.startAnimating() } else { spinner.stopAnimating() }
+ failure.isHidden = state != .failed
+ }
}
final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
QLPreviewControllerDelegate, UIAdaptivePresentationControllerDelegate {
let identifier: String
- private var controller: UIViewController?
+ private var controller: FilePreviewController?
private let completion: (Error?) -> Void
private weak var sources: T3PresentationSources?
private let sourceIdentifiers: [String]
private var items: [FilePreviewItem] = []
- private var loading: Task<Void, Never>?
+ private var urls: [URL?] = []
+ private var states: [FilePreviewState] = []
+ private var selectedIndex = 0
+ private weak var presenter: UIViewController?
+ /// Files that arrived while their page was off screen; Quick Look may still hold the blank page.
+ private var staleIndices = Set<Int>()
+ private var currentIndexObservation: NSKeyValueObservation?
+ private var download: (index: Int, task: Task<Void, Never>)?
+ private var placeholder: Task<Void, Never>?
+ private var openError: Error?
private var dismissRequested = false
private var finished = false
@@ -38,54 +85,155 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
super.init()
}
+ /// Downloads the file before presenting so Quick Look can refuse a format the caller should share instead.
func present(url: URL, title: String, from presenter: UIViewController) {
- present(urls: [url], titles: [title], selectedIndex: 0, from: presenter)
+ load(urls: [url], titles: [title], selectedIndex: 0, from: presenter, opensWhileLoading: false)
+ }
+
+ /// Opens the selected image once it is ready, or a loading page if it is slow, and loads the rest
+ /// of the gallery behind it so a slow or broken sibling never holds the viewer back.
+ func present(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController) {
+ load(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter, opensWhileLoading: true)
}
- func present(urls: [URL], titles: [String], selectedIndex: Int, from presenter: UIViewController) {
- loading = Task { @MainActor [self] in
+ /// Delivers a URL that was still resolving when the gallery opened, or nil when it never will.
+ func update(index: Int, url: URL?) {
+ guard !finished, urls.indices.contains(index), urls[index] == nil, states[index] == .loading else { return }
+ guard let url else {
+ failed(index, error: URLError(.resourceUnavailable))
+ return
+ }
+ urls[index] = url
+ loadNext()
+ }
+
+ private func load(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController,
+ opensWhileLoading: Bool) {
+ items = titles.map { title in
+ let item = FilePreviewItem()
+ item.previewItemTitle = title
+ return item
+ }
+ self.urls = urls
+ self.selectedIndex = selectedIndex
+ self.presenter = presenter
+ states = Array(repeating: .loading, count: urls.count)
+ if opensWhileLoading {
+ // A short grace keeps the zoom from the thumbnail into a loaded image when the file is quick.
+ placeholder = Task { @MainActor [self] in
+ try? await Task.sleep(nanoseconds: 250_000_000)
+ guard !Task.isCancelled, !finished, controller == nil else { return }
+ show()
+ }
+ }
+ loadNext()
+ }
+
+ /// Downloads one file at a time, nearest the page on screen first. The page on screen takes over
+ /// from a background download, which restarts later.
+ private func loadNext() {
+ guard !finished, !dismissRequested else { return }
+ let current = controller?.currentPreviewItemIndex ?? selectedIndex
+ guard let next = urls.indices
+ .filter({ urls[$0] != nil && states[$0] == .loading })
+ .min(by: { abs($0 - current) < abs($1 - current) })
+ else { return }
+ if let download {
+ guard next == current, download.index != current else { return }
+ download.task.cancel()
+ }
+ guard let url = urls[next] else { return }
+ let title = items[next].previewItemTitle ?? ""
+ let task = Task { @MainActor [self] in
+ let result: Result<URL, Error>
do {
- for (index, url) in urls.enumerated() {
- let title = titles[index]
- let file = try await Self.prepareFile(url: url, title: title)
- guard !finished, !Task.isCancelled else {
- try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
- return
- }
- // Quick Look knows which formats it renders; refuse before presenting so the caller
- // can fall back instead of showing an "unsupported format" page.
- guard QLPreviewController.canPreview(file as NSURL) else {
+ result = .success(try await Self.prepareFile(url: url, title: title))
+ } catch {
+ result = .failure(error)
+ }
+ guard !finished, !Task.isCancelled else {
+ if case .success(let file) = result {
try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
- throw NSError(
- domain: "T3NativePresentation",
- code: 3,
- userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."]
- )
- }
- let item = FilePreviewItem()
- item.previewItemURL = file
- item.previewItemTitle = title
- items.append(item)
}
- let preview = FilePreviewController()
- preview.delegate = self
- preview.dataSource = self
- preview.currentPreviewItemIndex = selectedIndex
- preview.onAppear = { [weak self] in self?.resumePendingDismissal() }
- controller = preview
- presenter.present(preview, animated: !UIAccessibility.isReduceMotionEnabled) { [self] in
- resumePendingDismissal()
- }
- preview.presentationController?.delegate = self
- } catch {
- finish(error: error)
+ return
+ }
+ download = nil
+ switch result {
+ case .success(let file): loaded(next, file: file)
+ case .failure(let error): failed(next, error: error)
}
+ loadNext()
}
+ download = (next, task)
+ }
+
+ private func loaded(_ index: Int, file: URL) {
+ // Quick Look knows which formats it renders; refuse before presenting so the caller
+ // can fall back instead of showing an "unsupported format" page.
+ guard QLPreviewController.canPreview(file as NSURL) else {
+ try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
+ failed(index, error: NSError(
+ domain: "T3NativePresentation",
+ code: 3,
+ userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."]
+ ))
+ return
+ }
+ items[index].previewItemURL = file
+ states[index] = .ready
+ if controller != nil { refresh(index) } else if index == selectedIndex { show() }
+ }
+
+ private func failed(_ index: Int, error: Error) {
+ guard index != selectedIndex else {
+ openError = error
+ dismiss()
+ return
+ }
+ states[index] = .failed
+ refresh(index)
+ }
+
+ private func show() {
+ guard let presenter else { finish(); return }
+ placeholder?.cancel()
+ let preview = FilePreviewController()
+ preview.delegate = self
+ preview.dataSource = self
+ preview.currentPreviewItemIndex = selectedIndex
+ preview.onAppear = { [weak self] in self?.resumePendingDismissal() }
+ controller = preview
+ preview.state = states[selectedIndex]
+ currentIndexObservation = preview.observe(\.currentPreviewItemIndex) { [weak self] _, _ in
+ DispatchQueue.main.async { self?.currentItemChanged() }
+ }
+ presenter.present(preview, animated: !UIAccessibility.isReduceMotionEnabled) { [self] in
+ resumePendingDismissal()
+ }
+ preview.presentationController?.delegate = self
+ }
+
+ private func refresh(_ index: Int) {
+ guard let controller else { return }
+ guard controller.currentPreviewItemIndex == index else {
+ if states[index] == .ready { staleIndices.insert(index) }
+ return
+ }
+ if states[index] == .ready { controller.refreshCurrentPreviewItem() }
+ controller.state = states[index]
+ }
+
+ private func currentItemChanged() {
+ guard !finished, let controller, states.indices.contains(controller.currentPreviewItemIndex) else { return }
+ let index = controller.currentPreviewItemIndex
+ if staleIndices.remove(index) != nil { controller.refreshCurrentPreviewItem() }
+ controller.state = states[index]
+ loadNext()
}
func dismiss() {
dismissRequested = true
- loading?.cancel()
+ download?.task.cancel()
guard !finished else { return }
guard let controller else { finish(); return }
// Drain Close from viewDidAppear after opening or cancelling an interactive dismissal.
@@ -133,15 +281,21 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
private func finish(error: Error? = nil) {
guard !finished else { return }
finished = true
- loading?.cancel()
- loading = nil
+ download?.task.cancel()
+ download = nil
+ placeholder?.cancel()
+ placeholder = nil
+ currentIndexObservation = nil
for item in items {
if let file = item.previewItemURL {
try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
}
}
items.removeAll()
- DispatchQueue.main.async { [completion] in completion(error) }
+ urls.removeAll()
+ states.removeAll()
+ let result = error ?? openError
+ DispatchQueue.main.async { [completion] in completion(result) }
}
/// Copy original bytes so preview and sharing do not mutate a draft or workspace file.
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index e08cfe7155e..a58e0e50360 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -47,7 +47,7 @@
"generate": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON scripts/generate-uniwind-themes.mts",
"generate:highlights": "node scripts/generate-highlights.mts",
"eas-build-on-success": "node scripts/upload-sourcemaps.mts build",
- "test": "vp test run --project unit --project react",
+ "test": "vp test run --project unit --project react && T3_MOBILE_TEST_PLATFORM=android vp test run --project react src/components/FilePreviewModal.test.tsx",
"typecheck": "effect-tsgo tsrs --noEmit"
},
"dependencies": {
diff --git a/apps/mobile/src/components/FilePreview.ios.tsx b/apps/mobile/src/components/FilePreview.ios.tsx
index 45f09779f13..db62d2928fd 100644
--- a/apps/mobile/src/components/FilePreview.ios.tsx
+++ b/apps/mobile/src/components/FilePreview.ios.tsx
@@ -1,8 +1,8 @@
import * as Dialog from "./ui/Dialog";
import { requireNativeModule } from "expo";
-import { useEffect, useEffectEvent, useId } from "react";
+import { useEffect, useEffectEvent, useId, useRef, useState } from "react";
-import type { ResolvedFilePreviewSource } from "./FilePreviewModal.types";
+import type { FilePreviewImage, ResolvedFilePreviewSource } from "./FilePreviewModal.types";
const NativeControls = requireNativeModule<{
presentFile(
@@ -12,22 +12,28 @@ const NativeControls = requireNativeModule<{
identifier: string,
): Promise<void>;
presentFiles(
- uris: readonly string[],
+ uris: readonly (string | null)[],
names: readonly string[],
selectedIndex: number,
sourceIdentifiers: readonly string[],
identifier: string,
): Promise<void>;
+ updateFile(identifier: string, index: number, uri: string | null): Promise<void>;
dismissFile(identifier: string): Promise<void>;
}>("T3NativeControls");
+// Null tells the viewer an image failed; undefined means its URL has not arrived yet.
+const nativeUri = (image: FilePreviewImage) => (image.failed ? null : image.uri);
+
function NativeFilePreview(props: {
readonly source: ResolvedFilePreviewSource;
readonly onRequestClose: () => void;
readonly onOpenError?: (error: unknown) => void;
}) {
- const { uri, name, sourceIdentifier, gallery } = props.source;
const identifier = useId();
+ // Later URLs reach the open viewer through updateFile instead of presenting again.
+ const [presented] = useState(props.source);
+ const delivered = useRef<(string | null | undefined)[]>([]);
const onRequestClose = useEffectEvent(props.onRequestClose);
const onOpenError = useEffectEvent((error: unknown) => {
if (props.onOpenError) props.onOpenError(error);
@@ -37,19 +43,27 @@ function NativeFilePreview(props: {
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- presents the native file preview and dismisses it on cleanup
useEffect(() => {
let canceled = false;
- const presentation =
- gallery && gallery.length > 1
- ? NativeControls.presentFiles(
- gallery.map((item) => item.uri),
- gallery.map((item) => item.name ?? "Preview"),
- Math.max(
- 0,
- gallery.findIndex((item) => item.uri === uri),
- ),
- gallery.map((item) => item.sourceIdentifier ?? ""),
- identifier,
- )
- : NativeControls.presentFile(uri, name ?? "Preview", sourceIdentifier ?? "", identifier);
+ let presentation: Promise<void>;
+ // Images open while still loading; other files must download first so Quick Look can refuse them.
+ if (presented.kind === "image") {
+ const { images, selectedIndex } = presented;
+ delivered.current = images.map((image) => image.uri);
+ presentation = NativeControls.presentFiles(
+ images.map((image) => image.uri ?? null),
+ images.map((image) => image.name ?? "Preview"),
+ selectedIndex,
+ images.map((image) => image.sourceIdentifier ?? ""),
+ identifier,
+ );
+ } else {
+ const { uri, name, sourceIdentifier } = presented;
+ presentation = NativeControls.presentFile(
+ uri,
+ name ?? "Preview",
+ sourceIdentifier ?? "",
+ identifier,
+ );
+ }
void presentation
.catch((error: unknown) => {
if (!canceled) onOpenError(error);
@@ -61,7 +75,18 @@ function NativeFilePreview(props: {
canceled = true;
void NativeControls.dismissFile(identifier).catch(() => undefined);
};
- }, [uri, name, sourceIdentifier, identifier, gallery]);
+ }, [presented, identifier]);
+
+ const images = props.source.kind === "image" ? props.source.images : undefined;
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hands image URLs that resolve after opening to the native viewer
+ useEffect(() => {
+ images?.forEach((image, index) => {
+ const uri = nativeUri(image);
+ if (uri === undefined || delivered.current[index] === uri) return;
+ delivered.current[index] = uri;
+ void NativeControls.updateFile(identifier, index, uri).catch(() => undefined);
+ });
+ }, [images, identifier]);
return null;
}
diff --git a/apps/mobile/src/components/FilePreview.tsx b/apps/mobile/src/components/FilePreview.tsx
index 486cd9e236b..a7c2de56d83 100644
--- a/apps/mobile/src/components/FilePreview.tsx
+++ b/apps/mobile/src/components/FilePreview.tsx
@@ -6,14 +6,17 @@ import ImageViewing from "react-native-image-viewing";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { openAttachmentInViewer } from "../lib/attachmentDownload";
-import type { ResolvedFilePreviewSource } from "./FilePreviewModal.types";
-import { MediaImagePreview } from "./MediaImagePreview";
+import type {
+ ResolvedFilePreviewDocument,
+ ResolvedFilePreviewSource,
+} from "./FilePreviewModal.types";
+import { imageViewingProps, MediaImagePreview } from "./MediaImagePreview";
import { PdfPreview } from "./PdfPreview";
import { ControlPill } from "./ui/ControlPill";
import { AppText as Text } from "./ui/AppText";
function PdfDocumentPreview(props: {
- readonly source: ResolvedFilePreviewSource;
+ readonly source: ResolvedFilePreviewDocument;
readonly onRequestClose: () => void;
}) {
const insets = useSafeAreaInsets();
@@ -41,7 +44,7 @@ function PdfDocumentPreview(props: {
}
function DocumentPreview(props: {
- readonly source: ResolvedFilePreviewSource;
+ readonly source: ResolvedFilePreviewDocument;
readonly onRequestClose: () => void;
readonly onOpenError?: (error: unknown) => void;
}) {
@@ -100,18 +103,14 @@ export function FilePreview(props: {
readonly onRequestClose: () => void;
readonly onOpenError?: (error: unknown) => void;
}) {
- if (props.source.kind === "pdf") return <PdfDocumentPreview {...props} />;
- if (props.source.kind !== "image") return <DocumentPreview {...props} />;
- if (props.source.actionsSource) return <MediaImagePreview {...props} />;
+ const { source } = props;
+ if (source.kind === "pdf") return <PdfDocumentPreview {...props} source={source} />;
+ if (source.kind !== "image") return <DocumentPreview {...props} source={source} />;
+ if (source.images[source.selectedIndex]?.actionsSource)
+ return <MediaImagePreview source={source} onRequestClose={props.onRequestClose} />;
return (
<ImageViewing
- images={
- props.source.gallery?.map((item) => ({ uri: item.uri })) ?? [{ uri: props.source.uri }]
- }
- imageIndex={Math.max(
- 0,
- props.source.gallery?.findIndex((item) => item.uri === props.source.uri) ?? 0,
- )}
+ {...imageViewingProps(source)}
visible
onRequestClose={props.onRequestClose}
swipeToCloseEnabled={false}
diff --git a/apps/mobile/src/components/FilePreviewModal.test.tsx b/apps/mobile/src/components/FilePreviewModal.test.tsx
new file mode 100644
index 00000000000..3989180f628
--- /dev/null
+++ b/apps/mobile/src/components/FilePreviewModal.test.tsx
@@ -0,0 +1,140 @@
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it, vi } from "vite-plus/test";
+import { EnvironmentId, SOURCE_CONTROL_MEDIA_ASSET } from "@t3tools/contracts";
+
+const harness = vi.hoisted(() => ({
+ refreshAssetUrl: vi.fn<(environmentId: string, resource: { url: string }) => Promise<string>>(),
+ alert: vi.fn(),
+ previews: [] as unknown[],
+ mounts: 0,
+ platform: { OS: process.env.T3_MOBILE_TEST_PLATFORM === "android" ? "android" : "ios" },
+}));
+
+vi.mock("react-native", () => ({ Platform: harness.platform }));
+vi.mock("../state/assets", () => ({ refreshAssetUrl: harness.refreshAssetUrl }));
+vi.mock("../lib/localAttachmentPreview", () => ({ loadLocalAttachmentPreview: vi.fn() }));
+vi.mock("../lib/attachmentDownload", () => ({
+ downloadAndShareAttachment: vi.fn(),
+ nativeViewerErrorMessage: () => "",
+ shareLocalAttachment: vi.fn(),
+}));
+vi.mock("../lib/previewPresentation", () => ({ usePreviewPresentation: () => {} }));
+vi.mock("./ui/Dialog", () => ({ alert: harness.alert }));
+vi.mock("./FilePreview", async () => {
+ const { useState } = await import("react");
+ return {
+ FilePreview: (props: { source: unknown }) => {
+ useState(() => harness.mounts++);
+ harness.previews.push(props.source);
+ return null;
+ },
+ };
+});
+
+import type { FilePreviewItem } from "./FilePreviewModal.types";
+import { FilePreviewModal } from "./FilePreviewModal";
+
+const environmentId = EnvironmentId.make("environment");
+const image = (url: string): FilePreviewItem => ({
+ kind: "image",
+ environmentId,
+ resource: { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: "/repo", url },
+});
+
+async function openGallery(
+ selected: FilePreviewItem,
+ gallery: readonly FilePreviewItem[],
+ platform = harness.platform.OS,
+) {
+ harness.platform.OS = platform;
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ harness.previews.length = 0;
+ harness.mounts = 0;
+ harness.alert.mockClear();
+ const root = createRoot(document.createElement("div"));
+ const onRequestClose = vi.fn();
+ await act(async () =>
+ root.render(
+ <FilePreviewModal source={{ ...selected, gallery }} onRequestClose={onRequestClose} />,
+ ),
+ );
+ return { onRequestClose, [Symbol.asyncDispose]: () => act(async () => root.unmount()) };
+}
+
+it("keeps the gallery stable while a sibling is still resolving", async () => {
+ const platform = harness.platform.OS;
+ const slow = Promise.withResolvers<string>();
+ harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) =>
+ resource.url.endsWith("slow.png") ? slow.promise : "https://signed.test/a.png",
+ );
+ const selected = image("https://github.com/a.png");
+ await using _preview = await openGallery(
+ selected,
+ [image("https://github.com/slow.png"), selected],
+ platform,
+ );
+
+ if (platform === "ios") {
+ expect(harness.previews.at(-1)).toMatchObject({
+ kind: "image",
+ selectedIndex: 1,
+ images: [
+ expect.not.objectContaining({ uri: expect.anything() }),
+ { uri: "https://signed.test/a.png" },
+ ],
+ });
+ } else {
+ expect(harness.previews).toEqual([]);
+ }
+ await act(async () => slow.resolve("https://signed.test/slow.png"));
+ expect(harness.previews.at(-1)).toMatchObject({
+ selectedIndex: 1,
+ images: [{ uri: "https://signed.test/slow.png" }, { uri: "https://signed.test/a.png" }],
+ });
+ expect(harness.mounts).toBe(1);
+});
+
+it("handles a failed sibling without leaving a pending page", async () => {
+ const platform = harness.platform.OS;
+ harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) => {
+ if (resource.url.endsWith("missing.png")) throw new Error("not found");
+ return `https://signed.test/${resource.url.split("/").pop()}`;
+ });
+ const selected = image("https://github.com/a.png");
+ await using preview = await openGallery(
+ selected,
+ [selected, image("https://github.com/missing.png"), image("https://github.com/c.png")],
+ platform,
+ );
+
+ if (platform === "android") {
+ expect(preview.onRequestClose).toHaveBeenCalledOnce();
+ expect(harness.alert).toHaveBeenCalledOnce();
+ expect(harness.previews).toEqual([]);
+ return;
+ }
+
+ expect(preview.onRequestClose).not.toHaveBeenCalled();
+ expect(harness.alert).not.toHaveBeenCalled();
+ expect(harness.previews.at(-1)).toMatchObject({
+ selectedIndex: 0,
+ images: [
+ { uri: "https://signed.test/a.png" },
+ { failed: true },
+ { uri: "https://signed.test/c.png" },
+ ],
+ });
+});
+
+it("closes the preview when the selected image cannot be resolved", async () => {
+ harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) => {
+ if (resource.url.endsWith("missing.png")) throw new Error("not found");
+ return `https://signed.test/${resource.url.split("/").pop()}`;
+ });
+ const selected = image("https://github.com/missing.png");
+ await using preview = await openGallery(selected, [image("https://github.com/a.png"), selected]);
+
+ expect(preview.onRequestClose).toHaveBeenCalledOnce();
+ expect(harness.alert).toHaveBeenCalledOnce();
+});
diff --git a/apps/mobile/src/components/FilePreviewModal.tsx b/apps/mobile/src/components/FilePreviewModal.tsx
index 849bacd8ac4..0d6ddaa2f26 100644
--- a/apps/mobile/src/components/FilePreviewModal.tsx
+++ b/apps/mobile/src/components/FilePreviewModal.tsx
@@ -1,5 +1,6 @@
import * as Dialog from "./ui/Dialog";
import { useContext, useEffect, useEffectEvent, useState } from "react";
+import { Platform } from "react-native";
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
import {
@@ -12,11 +13,7 @@ import { refreshAssetUrl } from "../state/assets";
import { filePreviewGallery, filePreviewKey, filePreviewName } from "../lib/filePreviewGallery";
import { FilePreviewGallery } from "./FilePreviewGallery";
import { FilePreview } from "./FilePreview";
-import type {
- FilePreviewItem,
- FilePreviewSource,
- ResolvedFilePreviewSource,
-} from "./FilePreviewModal.types";
+import type { FilePreviewItem, FilePreviewSource } from "./FilePreviewModal.types";
export type {
FilePreviewItem,
@@ -33,25 +30,21 @@ class PreviewResolutionError extends Error {
}
}
-interface ResolvedPreviewItem {
- readonly source: ResolvedFilePreviewSource;
+interface ResolvedPreviewUri {
+ readonly uri: string;
readonly dispose?: () => void;
}
-async function resolvePreviewItem(
+async function resolvePreviewUri(
item: FilePreviewItem,
signal: AbortSignal,
-): Promise<ResolvedPreviewItem | null> {
- const name = filePreviewName(item);
+): Promise<ResolvedPreviewUri | null> {
+ if ("uri" in item) return { uri: item.uri };
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 };
+ return loadLocalAttachmentPreview(item.attachment, signal).catch((error: unknown) => {
+ throw new PreviewResolutionError(error, "Attach the file again and retry.");
+ });
}
- 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) => {
@@ -64,7 +57,7 @@ async function resolvePreviewItem(
"Reconnect to this environment and try again. The file may have been moved or deleted.",
);
});
- return { source: { ...item, name, uri: url + (item.srcFragment ?? "") } };
+ return { uri: url + (item.srcFragment ?? "") };
}
function ResolvedFilePreview(props: {
@@ -75,10 +68,11 @@ 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 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 selectedIndex = items.findIndex((item) => filePreviewKey(item) === selectedKey);
+ const progressiveGallery = Platform.OS === "ios";
+ // Undefined while resolving, null once it cannot be.
+ const [uris, setUris] = useState<readonly (string | null | undefined)[]>(() =>
+ items.map((item) => ("uri" in item ? item.uri : undefined)),
);
const onResolutionError = useEffectEvent((error: PreviewResolutionError) => {
if (props.onOpenError) props.onOpenError(error.cause);
@@ -88,42 +82,57 @@ function ResolvedFilePreview(props: {
// Resolves once per presentation and holds local file leases until it closes.
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- resolves preview files and holds their local file leases until the preview 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 leases: (() => void)[] = [];
+ const settle = (index: number, uri: string | null) =>
+ setUris((current) => current.map((value, at) => (at === index ? uri : value)));
+ items.forEach((item, index) => {
+ if ("uri" in item) return;
+ void resolvePreviewUri(item, controller.signal).then(
+ (resolved) => {
+ if (controller.signal.aborted) return resolved?.dispose?.();
+ if (resolved?.dispose) leases.push(resolved.dispose);
+ settle(index, resolved?.uri ?? null);
+ },
+ (error: unknown) => {
+ if (controller.signal.aborted) return;
+ if (progressiveGallery && index !== selectedIndex) return settle(index, null);
+ 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?.();
- });
+ for (const dispose of leases) dispose();
};
- }, [items]);
- const selected = gallery?.[items.findIndex((item) => filePreviewKey(item) === selectedKey)];
- if (!gallery || !selected) return null;
+ }, [items, selectedIndex, progressiveGallery]);
+ const selected = { ...items[selectedIndex]!, name: filePreviewName(items[selectedIndex]!) };
+ if (selected.kind === "image") {
+ // Android's viewer resets image gestures when its sources change during a presentation.
+ if (!progressiveGallery && uris.some((uri) => uri === undefined)) return null;
+ const images = items.map((item, index) => {
+ const uri = uris[index];
+ return {
+ ...item,
+ name: filePreviewName(item),
+ ...(uri ? { uri } : uri === null ? { failed: true } : {}),
+ };
+ });
+ return (
+ <FilePreview
+ source={{ kind: "image", images, selectedIndex }}
+ onRequestClose={props.onRequestClose}
+ {...(props.onOpenError ? { onOpenError: props.onOpenError } : {})}
+ />
+ );
+ }
+ const uri = uris[selectedIndex];
+ if (!uri) return null;
const onOpenError = (error: unknown) => {
if (props.onOpenError) return props.onOpenError(error);
Dialog.alert("Could not open preview", nativeViewerErrorMessage(error), [
@@ -135,14 +144,14 @@ function ResolvedFilePreview(props: {
onPress: () => {
const input = {
attachment: {
- name: filePreviewName(selected),
+ name: selected.name,
mimeType: selected.mimeType ?? "application/octet-stream",
},
signal: new AbortController().signal,
};
- const sharing = /^(file|content):/.test(selected.uri)
- ? shareLocalAttachment({ ...input, uri: selected.uri })
- : downloadAndShareAttachment({ ...input, url: selected.uri });
+ const sharing = /^(file|content):/.test(uri)
+ ? shareLocalAttachment({ ...input, uri })
+ : downloadAndShareAttachment({ ...input, url: uri });
void sharing.catch(() => Dialog.alert("Could not share file", "Please try again."));
},
},
@@ -152,7 +161,7 @@ function ResolvedFilePreview(props: {
};
return (
<FilePreview
- source={{ ...selected, gallery }}
+ source={{ ...selected, kind: selected.kind, uri }}
onRequestClose={props.onRequestClose}
onOpenError={onOpenError}
/>
diff --git a/apps/mobile/src/components/FilePreviewModal.types.ts b/apps/mobile/src/components/FilePreviewModal.types.ts
index cc0643828aa..83ee7207b8e 100644
--- a/apps/mobile/src/components/FilePreviewModal.types.ts
+++ b/apps/mobile/src/components/FilePreviewModal.types.ts
@@ -23,7 +23,22 @@ export type FilePreviewSource = FilePreviewItem & {
readonly gallery?: readonly FilePreviewItem[];
};
-export interface ResolvedFilePreviewSource extends FilePreviewMetadata {
+export interface ResolvedFilePreviewDocument extends FilePreviewMetadata {
+ readonly kind: "pdf" | "document";
readonly uri: string;
- readonly gallery?: readonly (FilePreviewMetadata & { readonly uri: string })[];
}
+
+/** `uri` is absent while it resolves; `failed` marks one that never will. */
+export interface FilePreviewImage extends FilePreviewMetadata {
+ readonly uri?: string;
+ readonly failed?: boolean;
+}
+
+/** Opens before every URL resolves; images keep their slot as URLs arrive. */
+export interface FilePreviewImages {
+ readonly kind: "image";
+ readonly images: readonly FilePreviewImage[];
+ readonly selectedIndex: number;
+}
+
+export type ResolvedFilePreviewSource = ResolvedFilePreviewDocument | FilePreviewImages;
diff --git a/apps/mobile/src/components/MediaImagePreview.tsx b/apps/mobile/src/components/MediaImagePreview.tsx
index fc53c01d7e1..52c294e3646 100644
--- a/apps/mobile/src/components/MediaImagePreview.tsx
+++ b/apps/mobile/src/components/MediaImagePreview.tsx
@@ -1,4 +1,4 @@
-import { createContext, useContext, useState } from "react";
+import { createContext, useContext } from "react";
import { Pressable, View } from "react-native";
import ImageViewing from "react-native-image-viewing";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -6,12 +6,12 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useMediaActions } from "../state/mediaActions";
import { AppText } from "./ui/AppText";
import { SymbolView } from "./ui/AppSymbol";
-import type { ResolvedFilePreviewSource } from "./FilePreviewModal.types";
+import type { FilePreviewImages } from "./FilePreviewModal.types";
import { MediaActionsMenu } from "./MediaActionsMenu";
import { MediaSourceCaption } from "./MediaSourceCaption";
type MediaImagePreviewProps = {
- readonly source: ResolvedFilePreviewSource;
+ readonly source: FilePreviewImages;
readonly onRequestClose: () => void;
};
@@ -19,14 +19,14 @@ const ImagePreviewContext = createContext<MediaImagePreviewProps | null>(null);
function ImagePreviewHeader(header: { readonly imageIndex: number }) {
const props = useContext(ImagePreviewContext)!;
- const source = props.source.gallery?.[header.imageIndex] ?? props.source;
+ const source = props.source.images[header.imageIndex];
const insets = useSafeAreaInsets();
- const mediaActions = useMediaActions(source.actionsSource, props.onRequestClose);
+ const mediaActions = useMediaActions(source?.actionsSource, props.onRequestClose);
return (
<View className="bg-black/70" style={{ paddingTop: insets.top }}>
<View className="flex-row items-center gap-2 px-3">
<AppText className="flex-1 text-base text-white" numberOfLines={2}>
- {source.name ?? "Image"}
+ {source?.name ?? "Image"}
</AppText>
<MediaActionsMenu media={mediaActions} inModal />
<Pressable
@@ -43,20 +43,21 @@ function ImagePreviewHeader(header: { readonly imageIndex: number }) {
);
}
+// Images still resolving show the viewer's loading page, and remount by key once their URL arrives.
+export function imageViewingProps(source: FilePreviewImages) {
+ return {
+ images: source.images.map((image) => (image.uri ? { uri: image.uri } : {})),
+ keyExtractor: (_: unknown, index: number) => source.images[index]?.uri ?? `pending:${index}`,
+ // Stays fixed: react-native-image-viewing remounts the Modal and replays its fade when it changes.
+ imageIndex: source.selectedIndex,
+ };
+}
+
export function MediaImagePreview(props: MediaImagePreviewProps) {
- const gallery = props.source.gallery ?? [props.source];
- // Freeze imageIndex: react-native-image-viewing remounts the Modal and replays its fade when it changes.
- const [initialIndex] = useState(() =>
- Math.max(
- 0,
- gallery.findIndex((item) => item.uri === props.source.uri),
- ),
- );
return (
<ImagePreviewContext value={props}>
<ImageViewing
- images={gallery.map((item) => ({ uri: item.uri }))}
- imageIndex={initialIndex}
+ {...imageViewingProps(props.source)}
visible
presentationStyle="fullScreen"
onRequestClose={props.onRequestClose}
diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts
index 809b4ff4704..7089b20ccd2 100644
--- a/apps/mobile/vite.config.ts
+++ b/apps/mobile/vite.config.ts
@@ -27,6 +27,7 @@ const reactTests = [
"src/features/settings/components/BranchNamingSettings.test.tsx",
"src/features/settings/components/SettingsDragHandle.test.tsx",
"src/features/threads/ThreadMarkdownImage.test.tsx",
+ "src/components/FilePreviewModal.test.tsx",
"src/features/threads/UsageLimitRecoveryCard.test.tsx",
"src/features/threads/NewTaskDraftRouteScreen.test.tsx",
"src/native/NativeHeaderToolbar.test.tsx",
@@ -55,6 +56,7 @@ const babel: {
) => Promise<{ code?: string | null; map?: object | null } | null>;
} = require("@babel/core");
const babelConfig = require("./babel.config.js")({ cache: () => {} });
+const testPlatform = process.env.T3_MOBILE_TEST_PLATFORM === "android" ? "android" : "ios";
export default defineConfig({
test: {
@@ -77,7 +79,7 @@ export default defineConfig({
extends: true,
plugins: [
{
- name: "mobile-release-react-compiler",
+ name: `mobile-release-react-compiler-${testPlatform}`,
enforce: "pre",
async transform(code, id) {
if (
@@ -101,7 +103,7 @@ export default defineConfig({
caller: {
name: "metro",
bundler: "metro",
- platform: "ios",
+ platform: testPlatform,
isDev: false,
isServer: false,
isNodeModule: false,