Open History to see the last commit
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 { msg } from "gt-react";
13import { m } from "~/i18n/messages";
14import { resolveMediaSource } from "@t3tools/client-runtime/media-source";
15import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
16import {
17 squashAtomCommandFailure,
18 type AtomCommandResult,
19} from "@t3tools/client-runtime/state/runtime";
20import { resolveExternalWebLinkHost } from "./externalLinkContextMenu";
21import type { MediaActionSource } from "../media/MediaActions";
22import { resolveProtocolRelativeMediaUrl } from "../media/mediaContent";
23import { isHeicImageFile } from "../../lib/imageCompression";
24import type { EditedImage, ImageAnnotationTarget } from "./ImageAnnotationOverlay";
25
26export interface ExpandedImageItem {
27 src: string | null;
28 name: string;
29 mimeType?: string;
30 type?: "video";
31 /** Revoke this owned object URL; other blob URLs belong to the timeline. */
32 ownsSrc?: boolean;
33 source?: SnapShotSource;
34 onCopySnapshot?: (() => Promise<void>) | undefined;
35 /** Draft images can be drawn on in place; only they have bytes to replace. */
36 edit?: ImageAnnotationTarget | undefined;
37 autoPlay?: boolean;
38 originalUrl?: string;
39 srcFragment?: string;
40 actionsSource?: MediaActionSource;
41}
42
43export interface ExpandedImagePreview {
44 images: ExpandedImageItem[];
45 index: number;
46}
47
48export async function resolveMarkdownMediaPreview(input: {
49 source: string;
50 resolvedFilePath?: string | undefined;
51 cwd?: string | undefined;
52 threadRef?: ScopedThreadRef | undefined;
53 httpBaseUrl?: string | undefined;
54 onOpenFile?: ((relativePath: string) => void) | undefined;
55 createAssetUrl: (input: {
56 environmentId: EnvironmentId;
57 input: { resource: AssetResource };
58 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
59}): Promise<ExpandedImagePreview | null> {
60 const media = resolveMediaSource(input.source, {
61 threadId: input.threadRef?.threadId,
62 workspaceRoot: input.cwd,
63 resolvedFilePath: input.resolvedFilePath,
64 });
65 if (media === null) return null;
66 const { kind, name, reference } = media;
67 const relativePath = reference?.kind === "file" ? reference.relativePath : undefined;
68
69 let src: string;
70 let asset: MediaActionSource["asset"];
71 if (media.access === "direct") {
72 src = resolveProtocolRelativeMediaUrl(media.uri);
73 } else {
74 if (media.access === "unavailable" || !input.threadRef || !input.httpBaseUrl) {
75 throw new Error(m(msg("Reconnect to this environment and open the media again.")));
76 }
77 asset = { environmentId: input.threadRef.environmentId, resource: media.resource };
78 const result = await input.createAssetUrl({
79 environmentId: asset.environmentId,
80 input: { resource: asset.resource },
81 });
82 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
83 const assetUrl = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
84 if (assetUrl === null) {
85 throw new Error(m(msg("The environment returned an invalid media URL.")));
86 }
87 src = assetUrl + media.srcFragment;
88 }
89 return {
90 images: [
91 {
92 src,
93 name,
94 ...(kind === "video" ? { type: "video", autoPlay: false } : {}),
95 ...(media.access === "direct" && resolveExternalWebLinkHost(media.uri) !== null
96 ? { originalUrl: media.uri }
97 : {}),
98 ...(media.srcFragment ? { srcFragment: media.srcFragment } : {}),
99 actionsSource: {
100 kind,
101 name,
102 src,
103 ...(reference ? { reference } : {}),
104 ...(asset ? { asset } : {}),
105 ...(relativePath && input.onOpenFile
106 ? { onOpenFile: () => input.onOpenFile?.(relativePath) }
107 : {}),
108 },
109 },
110 ],
111 index: 0,
112 };
113}
114
115export function buildAttachmentVideoAsset(
116 environmentId: EnvironmentId,
117 attachment: Pick<ChatFileAttachment, "id" | "name" | "mimeType">,
118): NonNullable<MediaActionSource["asset"]> {
119 return {
120 environmentId,
121 resource: {
122 _tag: "attachment" as const,
123 attachmentId: attachment.id,
124 fileName: attachment.name,
125 mimeType: videoMimeType(attachment) ?? attachment.mimeType,
126 },
127 };
128}
129
130export function buildAttachmentVideoPreview(
131 environmentId: EnvironmentId,
132 attachment: ChatFileAttachment,
133): ExpandedImagePreview | null {
134 if (!isVideoAttachment(attachment)) return null;
135 const src = attachment.previewUrl ?? null;
136 const asset =
137 attachment.downloadable === false
138 ? undefined
139 : buildAttachmentVideoAsset(environmentId, attachment);
140 if (src === null && asset === undefined) return null;
141 return {
142 images: [
143 {
144 src,
145 name: attachment.name,
146 type: "video",
147 actionsSource: {
148 kind: "video",
149 name: attachment.name,
150 src,
151 ...(asset ? { asset } : {}),
152 },
153 },
154 ],
155 index: 0,
156 };
157}
158
159export function expandedImageKey(preview: ExpandedImagePreview): string {
160 const item = preview.images[preview.index];
161 const asset = item?.actionsSource?.asset;
162 return `${item?.src ?? (asset ? JSON.stringify([asset.environmentId, asset.resource]) : "image")}:${preview.index}`;
163}
164
165export function attachVideoThumbnail(video: HTMLVideoElement, file: File): () => void {
166 const url = URL.createObjectURL(file);
167 video.src = url;
168 return () => URL.revokeObjectURL(url);
169}
170
171export function buildExpandedImagePreview(
172 images: ReadonlyArray<ChatImageAttachment | ComposerFileAttachment>,
173 selectedImageId: string,
174 onCopySnapshot?: (id: string) => Promise<void>,
175 onSaveImageEdit?: (id: string, file: File) => Promise<EditedImage | null>,
176): ExpandedImagePreview | null {
177 const selected = images.find((image) => image.id === selectedImageId);
178 if (selected?.type === "file" && selected.file && isVideoAttachment(selected)) {
179 return {
180 images: [
181 {
182 src: URL.createObjectURL(selected.file),
183 name: selected.name,
184 type: "video",
185 ownsSrc: true,
186 },
187 ],
188 index: 0,
189 };
190 }
191 const previewableImages = images.flatMap((image) =>
192 image.type === "image" && image.previewUrl
193 ? [
194 {
195 id: image.id,
196 src: image.previewUrl,
197 name: image.name,
198 mimeType: image.mimeType,
199 source: image.source,
200 file:
201 "file" in image &&
202 image.file instanceof File &&
203 !isHeicImageFile({ name: image.name, type: image.mimeType })
204 ? image.file
205 : null,
206 },
207 ]
208 : [],
209 );
210 if (previewableImages.length === 0) {
211 return null;
212 }
213 const selectedIndex = previewableImages.findIndex((image) => image.id === selectedImageId);
214 if (selectedIndex < 0) {
215 return null;
216 }
217 return {
218 images: previewableImages.map((image) => ({
219 src: image.src,
220 name: image.name,
221 mimeType: image.mimeType,
222 ...(onSaveImageEdit && image.file
223 ? {
224 edit: {
225 file: image.file,
226 name: image.name,
227 mimeType: image.mimeType,
228 save: (file: File) => onSaveImageEdit(image.id, file),
229 },
230 }
231 : {}),
232 ...(image.source?.kind === "snap-shot"
233 ? {
234 source: image.source,
235 onCopySnapshot: onCopySnapshot ? () => onCopySnapshot(image.id) : undefined,
236 }
237 : {}),
238 })),
239 index: selectedIndex,
240 };
241}