Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

VideoThumbnailImage.tsx

61 lines2.1 KB

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 { StyleSheet } from "react-native";
8​
9import type { DraftComposerFileAttachment } from "../lib/composerImages";
10import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
11import { cachedVideoThumbnail, loadVideoThumbnail } from "../lib/videoThumbnails";
12​
13interface VideoThumbnailTarget {
14 readonly cacheKey: string;
15 readonly source: string | DraftComposerFileAttachment;
17​
18// Plain-object keys compare structurally (Effect `Equal`/`Hash`).
19const videoThumbnailAtom = Atom.family((target: VideoThumbnailTarget) =>
20 Atom.make(
21 Effect.promise((signal) =>
22 loadVideoThumbnail(
23 target.cacheKey,
24 async (sourceSignal) =>
25 typeof target.source === "string"
26 ? { uri: target.source, dispose: () => undefined }
27 : loadLocalAttachmentPreview(target.source, sourceSignal),
28 signal,
29 ),
30 ),
31 ).pipe(Atom.withLabel(`video-thumbnail:${target.cacheKey}`)),
32);
33​
34const noVideoThumbnail = Atom.make(AsyncResult.initial<VideoThumbnail | null>()).pipe(
35 Atom.withLabel("video-thumbnail:none"),
36);
37​
38export function VideoThumbnailImage(props: {
39 readonly cacheKey: string;
40 readonly source: string | DraftComposerFileAttachment | null;
41 readonly contentFit?: "cover" | "contain";
42}) {
43 const { cacheKey, source } = props;
44 // Extraction runs only while the screen is focused; leaving it interrupts the load.
45 const isFocused = useIsFocused();
46 const loaded = useAtomValue(
47 source && isFocused ? videoThumbnailAtom({ cacheKey, source }) : noVideoThumbnail,
48 );
49 const thumbnail =
50 (loaded._tag === "Success" ? loaded.value : null) ?? cachedVideoThumbnail(cacheKey);
51​
52 return thumbnail ? (
53 <Image
54 source={thumbnail}
55 style={StyleSheet.absoluteFill}
56 contentFit={props.contentFit ?? "cover"}
57 recyclingKey={cacheKey}
58 accessible={false}
59 />
60 ) : null;