Open History to see the last commit
1import * as Dialog from "./ui/Dialog";
2import { requireNativeModule } from "expo";
3import { useEffect, useEffectEvent, useId } from "react";
4
5import type { ResolvedFilePreviewSource } from "./FilePreviewModal.types";
6
7const NativeControls = requireNativeModule<{
8 presentFile(
9 uri: string,
10 name: string,
11 sourceIdentifier: string,
12 identifier: string,
13 ): Promise<void>;
14 presentFiles(
15 uris: readonly string[],
16 names: readonly string[],
17 selectedIndex: number,
18 sourceIdentifiers: readonly string[],
19 identifier: string,
20 ): Promise<void>;
21 dismissFile(identifier: string): Promise<void>;
22}>("T3NativeControls");
23
24function NativeFilePreview(props: {
25 readonly source: ResolvedFilePreviewSource;
26 readonly onRequestClose: () => void;
27 readonly onOpenError?: (error: unknown) => void;
28}) {
29 const { uri, name, sourceIdentifier, gallery } = props.source;
30 const identifier = useId();
31 const onRequestClose = useEffectEvent(props.onRequestClose);
32 const onOpenError = useEffectEvent((error: unknown) => {
33 if (props.onOpenError) props.onOpenError(error);
34 else Dialog.alert("Could not open preview", "The file could not be loaded. Please try again.");
35 });
36
37 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- presents the native file preview and dismisses it on cleanup
38 useEffect(() => {
39 let canceled = false;
40 const presentation =
41 gallery && gallery.length > 1
42 ? NativeControls.presentFiles(
43 gallery.map((item) => item.uri),
44 gallery.map((item) => item.name ?? "Preview"),
45 Math.max(
46 0,
47 gallery.findIndex((item) => item.uri === uri),
48 ),
49 gallery.map((item) => item.sourceIdentifier ?? ""),
50 identifier,
51 )
52 : NativeControls.presentFile(uri, name ?? "Preview", sourceIdentifier ?? "", identifier);
53 void presentation
54 .catch((error: unknown) => {
55 if (!canceled) onOpenError(error);
56 })
57 .finally(() => {
58 if (!canceled) onRequestClose();
59 });
60 return () => {
61 canceled = true;
62 void NativeControls.dismissFile(identifier).catch(() => undefined);
63 };
64 }, [uri, name, sourceIdentifier, identifier, gallery]);
65
66 return null;
67}
68
69export function FilePreview(props: {
70 readonly source: ResolvedFilePreviewSource;
71 readonly onRequestClose: () => void;
72 readonly onOpenError?: (error: unknown) => void;
73}) {
74 return <NativeFilePreview {...props} />;
75}