Open History to see the last commit
1import type { ComposerFileAttachment } from "../../composerDraftStore";
2import { type ChatImageAttachment, isVideoAttachment } from "../../types";
3import type {
4 AssetCreateUrlResult,
5 AssetResource,
6 EnvironmentId,
7 ScopedThreadRef,
8} from "@t3tools/contracts";
9import {
10 classifyMarkdownImageSource,
11 markdownImageSourceFragment,
12} from "@t3tools/client-runtime/markdown-images";
13import { mediaFileReference, mediaUrlReference } from "@t3tools/client-runtime/media-reference";
14import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
15import {
16 squashAtomCommandFailure,
17 type AtomCommandResult,
18} from "@t3tools/client-runtime/state/runtime";
19import { mediaKindFromPath, mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview";
20import { resolveExternalWebLinkHost } from "./externalLinkContextMenu";
21import type { MediaActionSource } from "../media/MediaActions";
22import { resolveProtocolRelativeMediaUrl } from "../media/mediaContent";
23
24export interface ExpandedImageItem {
25 src: string;
26 name: string;
27 type?: "video";
28 autoPlay?: boolean;
29 /** Authored remote destination to open when embedding fails, never a generated asset URL. */
30 originalUrl?: string;
31 actionsSource?: MediaActionSource;
32}
33
34export interface ExpandedImagePreview {
35 images: ExpandedImageItem[];
36 index: number;
37}
38
39/** Resolves a chat media reference on its owning environment, without downloading its bytes. */
40export async function resolveMarkdownMediaPreview(input: {
41 source: string;
42 resolvedFilePath?: string | undefined;
43 cwd?: string | undefined;
44 threadRef?: ScopedThreadRef | undefined;
45 httpBaseUrl?: string | undefined;
46 onOpenFile?: ((relativePath: string) => void) | undefined;
47 createAssetUrl: (input: {
48 environmentId: EnvironmentId;
49 input: { resource: AssetResource };
50 }) => Promise<AtomCommandResult<AssetCreateUrlResult, unknown>>;
51}): Promise<ExpandedImagePreview | null> {
52 const source =
53 input.resolvedFilePath === undefined
54 ? classifyMarkdownImageSource(input.source, input.cwd)
55 : { _tag: "WorkspaceFile" as const, path: input.resolvedFilePath };
56 if (source._tag === "Blocked") return null;
57
58 const path =
59 source._tag === "Direct"
60 ? source.uri.split(/[?#]/, 1)[0]!
61 : source.path.replace(/:\d+(?::\d+)?$/, "");
62 const name = path.split(/[\\/]/).at(-1) ?? "";
63 const extensionIndex = name.lastIndexOf(".");
64 const fileMimeType =
65 extensionIndex < 0 ? null : mediaMimeTypeFromExtension(name.slice(extensionIndex));
66 const kind =
67 source._tag === "Direct"
68 ? mediaKindFromPath(source.uri)
69 : fileMimeType === null
70 ? null
71 : fileMimeType.startsWith("video/")
72 ? "video"
73 : "image";
74 if (kind === null) return null;
75
76 const reference =
77 source._tag === "Direct" ? mediaUrlReference(source.uri) : mediaFileReference(path, input.cwd);
78 const relativePath = reference?.kind === "file" ? reference.relativePath : undefined;
79 let src: string;
80 let asset: MediaActionSource["asset"];
81 if (source._tag === "Direct") {
82 src = resolveProtocolRelativeMediaUrl(source.uri);
83 } else {
84 if (!input.threadRef || !input.httpBaseUrl) {
85 throw new Error("Reconnect to this environment and open the media again.");
86 }
87 asset = {
88 environmentId: input.threadRef.environmentId,
89 resource: { _tag: "media-file", threadId: input.threadRef.threadId, path },
90 };
91 const result = await input.createAssetUrl({
92 environmentId: asset.environmentId,
93 input: { resource: asset.resource },
94 });
95 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
96 const assetUrl = resolveAssetUrl(input.httpBaseUrl, result.value.relativeUrl);
97 if (assetUrl === null) throw new Error("The environment returned an invalid media URL.");
98 src = assetUrl + markdownImageSourceFragment(input.source);
99 }
100 return {
101 images: [
102 {
103 src,
104 name: name || kind,
105 ...(kind === "video" ? { type: "video", autoPlay: false } : {}),
106 ...(source._tag === "Direct" && resolveExternalWebLinkHost(source.uri) !== null
107 ? { originalUrl: source.uri }
108 : {}),
109 actionsSource: {
110 kind,
111 name: name || kind,
112 src,
113 ...(reference ? { reference } : {}),
114 ...(asset ? { asset } : {}),
115 ...(relativePath && input.onOpenFile
116 ? { onOpenFile: () => input.onOpenFile?.(relativePath) }
117 : {}),
118 },
119 },
120 ],
121 index: 0,
122 };
123}
124
125export function attachVideoThumbnail(video: HTMLVideoElement, file: File): () => void {
126 const url = URL.createObjectURL(file);
127 video.src = url;
128 return () => URL.revokeObjectURL(url);
129}
130
131export function buildExpandedImagePreview(
132 images: ReadonlyArray<ChatImageAttachment | ComposerFileAttachment>,
133 selectedImageId: string,
134): ExpandedImagePreview | null {
135 const selected = images.find((image) => image.id === selectedImageId);
136 if (selected?.type === "file" && selected.file && isVideoAttachment(selected)) {
137 return {
138 images: [{ src: URL.createObjectURL(selected.file), name: selected.name, type: "video" }],
139 index: 0,
140 };
141 }
142 const previewableImages = images.flatMap((image) =>
143 image.type === "image" && image.previewUrl
144 ? [{ id: image.id, src: image.previewUrl, name: image.name }]
145 : [],
146 );
147 if (previewableImages.length === 0) {
148 return null;
149 }
150 const selectedIndex = previewableImages.findIndex((image) => image.id === selectedImageId);
151 if (selectedIndex < 0) {
152 return null;
153 }
154 return {
155 images: previewableImages.map((image) => ({
156 src: image.src,
157 name: image.name,
158 })),
159 index: selectedIndex,
160 };
161}