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 useEffect(() => {
38 let canceled = false;
39 const presentation =
40 gallery && gallery.length > 1
41 ? NativeControls.presentFiles(
42 gallery.map((item) => item.uri),
43 gallery.map((item) => item.name ?? "Preview"),
44 Math.max(
45 0,
46 gallery.findIndex((item) => item.uri === uri),
47 ),
48 gallery.map((item) => item.sourceIdentifier ?? ""),
49 identifier,
50 )
51 : NativeControls.presentFile(uri, name ?? "Preview", sourceIdentifier ?? "", identifier);
52 void presentation
53 .catch((error: unknown) => {
54 if (!canceled) onOpenError(error);
55 })
56 .finally(() => {
57 if (!canceled) onRequestClose();
58 });
59 return () => {
60 canceled = true;
61 void NativeControls.dismissFile(identifier).catch(() => undefined);
62 };
63 }, [uri, name, sourceIdentifier, identifier, gallery]);
64
65 return null;
66}
67
68export function FilePreview(props: {
69 readonly source: ResolvedFilePreviewSource;
70 readonly onRequestClose: () => void;
71 readonly onOpenError?: (error: unknown) => void;
72}) {
73 return <NativeFilePreview {...props} />;
74}