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

ExpandedImagePreview.tsx

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