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