Open History to see the last commit
1import type { SnapShotSource } from "@t3tools/contracts";
2
3import type { ComposerFileAttachment } from "../../composerDraftStore";
4import { type ChatImageAttachment, isVideoAttachment } from "../../types";
5import type {
6 AssetCreateUrlResult,
7 AssetResource,
8 ChatFileAttachment,
9 EnvironmentId,
10 ScopedThreadRef,
11} from "@t3tools/contracts";
12import { videoMimeType } from "@t3tools/shared/video";
13import { resolveMediaSource } from "@t3tools/client-runtime/media-source";
14import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
15import {
16 squashAtomCommandFailure,
17 type AtomCommandResult,
18} from "@t3tools/client-runtime/state/runtime";
19import { resolveExternalWebLinkHost } from "./externalLinkContextMenu";
20import type { MediaActionSource } from "../media/MediaActions";
21import { resolveProtocolRelativeMediaUrl } from "../media/mediaContent";
22
23export interface ExpandedImageItem {
24 /** A loadable URL, or null when the dialog must mint one from `asset` first. */
25 src: string | null;
26 name: string;
27 type?: "video";
28 source?: SnapShotSource;
29 autoPlay?: boolean;
30 /** Authored remote destination to open when embedding fails, never a generated asset URL. */
31 originalUrl?: string;
32 srcFragment?: string;
33 actionsSource?: MediaActionSource;
34}
35
36export interface ExpandedImagePreview {
37 images: ExpandedImageItem[];
38 index: number;
39}
40
41/** Resolves a chat media reference on its owning environment, without downloading its bytes. */
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 expandedImageKey(preview: ExpandedImagePreview): string {
123 const item = preview.images[preview.index];
124 const asset = item?.actionsSource?.asset;
125 return `${item?.src ?? (asset ? JSON.stringify([asset.environmentId, asset.resource]) : "image")}:${preview.index}`;
126}
127
128export function attachVideoThumbnail(video: HTMLVideoElement, file: File): () => void {
129 const url = URL.createObjectURL(file);
130 video.src = url;
131 return () => URL.revokeObjectURL(url);
132}
133
134export function buildExpandedImagePreview(
135 images: ReadonlyArray<ChatImageAttachment | ComposerFileAttachment>,
136 selectedImageId: string,
137): ExpandedImagePreview | null {
138 const selected = images.find((image) => image.id === selectedImageId);
139 if (selected?.type === "file" && selected.file && isVideoAttachment(selected)) {
140 return {
141 images: [{ src: URL.createObjectURL(selected.file), name: selected.name, type: "video" }],
142 index: 0,
143 };
144 }
145 const previewableImages = images.flatMap((image) =>
146 image.type === "image" && image.previewUrl
147 ? [{ id: image.id, src: image.previewUrl, name: image.name, source: image.source }]
148 : [],
149 );
150 if (previewableImages.length === 0) {
151 return null;
152 }
153 const selectedIndex = previewableImages.findIndex((image) => image.id === selectedImageId);
154 if (selectedIndex < 0) {
155 return null;
156 }
157 return {
158 images: previewableImages.map((image) => ({
159 src: image.src,
160 name: image.name,
161 ...(image.source?.kind === "snap-shot" ? { source: image.source } : {}),
162 })),
163 index: selectedIndex,
164 };
165}