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

ExpandedImagePreview.tsx

203 lines6.5 KB

1import type { SnapShotSource } from "@t3tools/contracts";
2​
3import type { ComposerFileAttachment } from "../../composerDraftStore";
4import { type ChatFileAttachment, type ChatImageAttachment, isVideoAttachment } from "../../types";
5import type {
6 AssetCreateUrlResult,
7 AssetResource,
8 EnvironmentId,
9 ScopedThreadRef,
10} from "@t3tools/contracts";
11import { videoMimeType } from "@t3tools/shared/video";
12import { resolveMediaSource } from "@t3tools/client-runtime/media-source";
13import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
14import {
15 squashAtomCommandFailure,
16 type AtomCommandResult,
17} from "@t3tools/client-runtime/state/runtime";
18import { resolveExternalWebLinkHost } from "./externalLinkContextMenu";
19import type { MediaActionSource } from "../media/MediaActions";
20import { resolveProtocolRelativeMediaUrl } from "../media/mediaContent";
21​
22export interface ExpandedImageItem {
23 src: string | null;
24 name: string;
25 type?: "video";
26 /** The preview created this object URL and must revoke it; other blob URLs belong to the timeline. */
27 ownsSrc?: boolean;
28 source?: SnapShotSource;
29 autoPlay?: boolean;
30 originalUrl?: string;
31 srcFragment?: string;
32 actionsSource?: MediaActionSource;
34​
35export interface ExpandedImagePreview {
36 images: ExpandedImageItem[];
37 index: number;
39​
40export function wrapExpandedImageIndex(index: number, imageCount: number): number {
41 return imageCount > 0 ? ((index % imageCount) + imageCount) % imageCount : 0;
43​
44export async function resolveMarkdownMediaPreview(input: {
45 source: string;
46 resolvedFilePath?: string | undefined;
47 cwd?: string | undefined;
48 threadRef?: ScopedThreadRef | undefined;
49 httpBaseUrl?: string | undefined;
50 onOpenFile?: ((relativePath: string) => void) | undefined;
51 createAssetUrl: (input: {
52 environmentId: EnvironmentId;
53 input: { resource: AssetResource };
54 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
55}): Promise<ExpandedImagePreview | null> {
56 const media = resolveMediaSource(input.source, {
57 threadId: input.threadRef?.threadId,
58 workspaceRoot: input.cwd,
59 resolvedFilePath: input.resolvedFilePath,
60 });
61 if (media === null) return null;
62 const { kind, name, reference } = media;
63 const relativePath = reference?.kind === "file" ? reference.relativePath : undefined;
64​
65 let src: string;
66 let asset: MediaActionSource["asset"];
67 if (media.access === "direct") {
68 src = resolveProtocolRelativeMediaUrl(media.uri);
69 } else {
70 if (media.access === "unavailable" || !input.threadRef || !input.httpBaseUrl) {
71 throw new Error("Reconnect to this environment and open the media again.");
72 }
73 asset = { environmentId: input.threadRef.environmentId, resource: media.resource };
74 const result = await input.createAssetUrl({
75 environmentId: asset.environmentId,
76 input: { resource: asset.resource },
77 });
78 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
79 const assetUrl = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
80 if (assetUrl === null) throw new Error("The environment returned an invalid media URL.");
81 src = assetUrl + media.srcFragment;
82 }
83 return {
84 images: [
85 {
86 src,
87 name,
88 ...(kind === "video" ? { type: "video", autoPlay: false } : {}),
89 ...(media.access === "direct" && resolveExternalWebLinkHost(media.uri) !== null
90 ? { originalUrl: media.uri }
91 : {}),
92 ...(media.srcFragment ? { srcFragment: media.srcFragment } : {}),
93 actionsSource: {
94 kind,
95 name,
96 src,
97 ...(reference ? { reference } : {}),
98 ...(asset ? { asset } : {}),
99 ...(relativePath && input.onOpenFile
100 ? { onOpenFile: () => input.onOpenFile?.(relativePath) }
101 : {}),
102 },
103 },
104 ],
105 index: 0,
106 };
108​
109export function buildAttachmentVideoAsset(
110 environmentId: EnvironmentId,
111 attachment: Pick<ChatFileAttachment, "id" | "name" | "mimeType">,
112): NonNullable<MediaActionSource["asset"]> {
113 return {
114 environmentId,
115 resource: {
116 _tag: "attachment" as const,
117 attachmentId: attachment.id,
118 fileName: attachment.name,
119 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
120 },
121 };
123​
124export function buildAttachmentVideoPreview(
125 environmentId: EnvironmentId,
126 attachment: ChatFileAttachment,
127): ExpandedImagePreview | null {
128 if (!isVideoAttachment(attachment)) return null;
129 const src = attachment.previewUrl ?? null;
130 const asset =
131 attachment.downloadable === false
132 ? undefined
133 : buildAttachmentVideoAsset(environmentId, attachment);
134 if (src === null && asset === undefined) return null;
135 return {
136 images: [
137 {
138 src,
139 name: attachment.name,
140 type: "video",
141 actionsSource: {
142 kind: "video",
143 name: attachment.name,
144 src,
145 ...(asset ? { asset } : {}),
146 },
147 },
148 ],
149 index: 0,
150 };
152​
153export function expandedImageKey(preview: ExpandedImagePreview): string {
154 const item = preview.images[preview.index];
155 const asset = item?.actionsSource?.asset;
156 return `${item?.src ?? (asset ? JSON.stringify([asset.environmentId, asset.resource]) : "image")}:${preview.index}`;
158​
159export function attachVideoThumbnail(video: HTMLVideoElement, file: File): () => void {
160 const url = URL.createObjectURL(file);
161 video.src = url;
162 return () => URL.revokeObjectURL(url);
164​
165export function buildExpandedImagePreview(
166 images: ReadonlyArray<ChatImageAttachment | ComposerFileAttachment>,
167 selectedImageId: string,
168): ExpandedImagePreview | null {
169 const selected = images.find((image) => image.id === selectedImageId);
170 if (selected?.type === "file" && selected.file && isVideoAttachment(selected)) {
171 return {
172 images: [
173 {
174 src: URL.createObjectURL(selected.file),
175 name: selected.name,
176 type: "video",
177 ownsSrc: true,
178 },
179 ],
180 index: 0,
181 };
182 }
183 const previewableImages = images.flatMap((image) =>
184 image.type === "image" && image.previewUrl
185 ? [{ id: image.id, src: image.previewUrl, name: image.name, source: image.source }]
186 : [],
187 );
188 if (previewableImages.length === 0) {
189 return null;
190 }
191 const selectedIndex = previewableImages.findIndex((image) => image.id === selectedImageId);
192 if (selectedIndex < 0) {
193 return null;
194 }
195 return {
196 images: previewableImages.map((image) => ({
197 src: image.src,
198 name: image.name,
199 ...(image.source?.kind === "snap-shot" ? { source: image.source } : {}),
200 })),
201 index: selectedIndex,
202 };