Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import * as Effect from "effect/Effect";
3import { Atom, AsyncResult } from "effect/reactivity";
4import { Image } from "expo-image";
5import { useIsFocused } from "@react-navigation/native";
6import type { VideoThumbnail } from "expo-video";
7import { useState } from "react";
8import { StyleSheet } from "react-native";
9
10import type { DraftComposerFileAttachment } from "../lib/composerImages";
11import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
12import { cachedVideoThumbnail, loadVideoThumbnail } from "../lib/videoThumbnails";
13
14interface VideoThumbnailTarget {
15 readonly cacheKey: string;
16 readonly source: string | DraftComposerFileAttachment;
17}
18
19// Plain-object keys compare structurally (Effect `Equal`/`Hash`).
20const videoThumbnailAtom = Atom.family((target: VideoThumbnailTarget) =>
21 Atom.make(
22 Effect.promise((signal) =>
23 loadVideoThumbnail(
24 target.cacheKey,
25 async (sourceSignal) =>
26 typeof target.source === "string"
27 ? { uri: target.source, dispose: () => undefined }
28 : loadLocalAttachmentPreview(target.source, sourceSignal),
29 signal,
30 ),
31 ),
32 ).pipe(Atom.withLabel(`video-thumbnail:${target.cacheKey}`)),
33);
34
35const noVideoThumbnail = Atom.make(AsyncResult.initial<VideoThumbnail | null>()).pipe(
36 Atom.withLabel("video-thumbnail:none"),
37);
38
39export function VideoThumbnailImage(props: {
40 readonly cacheKey: string;
41 readonly source: string | DraftComposerFileAttachment | null;
42 readonly contentFit?: "cover" | "contain";
43}) {
44 const { cacheKey, source } = props;
45 // Extraction starts only while the screen is focused; leaving it skips queued loads.
46 const isFocused = useIsFocused();
47 const loaded = useAtomValue(
48 source && isFocused ? videoThumbnailAtom({ cacheKey, source }) : noVideoThumbnail,
49 );
50 const thumbnail =
51 (loaded._tag === "Success" ? loaded.value : null) ?? cachedVideoThumbnail(cacheKey);
52
53 // iOS draws a frame object the moment its prop is set, with the contentFit the view has then,
54 // and a later contentFit never refits it. Send the frame after mount so contentFit is set first.
55 const [laidOut, setLaidOut] = useState(false);
56 return (
57 <Image
58 onLayout={() => setLaidOut(true)}
59 source={laidOut ? thumbnail : null}
60 style={StyleSheet.absoluteFill}
61 contentFit={props.contentFit ?? "cover"}
62 recyclingKey={cacheKey}
63 accessible={false}
64 />
65 );
66}