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

previewAnnotation.ts

49 lines1.8 KB

1import type { PreviewAnnotationPayload } from "@t3tools/contracts";
2​
3async function previewAnnotationScreenshotFile(
4 annotation: PreviewAnnotationPayload,
5): Promise<File | null> {
6 if (!annotation.screenshot) return null;
7 const response = await fetch(annotation.screenshot.dataUrl);
8 const blob = await response.blob();
9 return new File([blob], `preview-annotation-${annotation.id}.png`, {
10 type: blob.type || "image/png",
11 });
13​
14/** Upper bound on turning a picked element's crop into a composer attachment. */
15const PREVIEW_ANNOTATION_CAPTURE_TIMEOUT_MS = 5_000;
16​
17export type PreviewAnnotationCapture =
18 /** The crop is ready to attach. */
19 | { readonly status: "captured"; readonly file: File }
20 /** The pick carried no crop, which is normal for comment-only annotations. */
21 | { readonly status: "none" }
22 /** The crop stalled or threw. Send the annotation without it. */
23 | { readonly status: "failed" };
24​
25/**
26 * Bounded wrapper around `previewAnnotationScreenshotFile`. The picker holds the
27 * composer while this runs, so it must always settle: a stalled crop resolves as
28 * `failed` instead of leaving the caller waiting.
29 */
30export async function capturePreviewAnnotationScreenshot(
31 annotation: PreviewAnnotationPayload,
32 timeoutMs: number = PREVIEW_ANNOTATION_CAPTURE_TIMEOUT_MS,
33): Promise<PreviewAnnotationCapture> {
34 if (!annotation.screenshot) return { status: "none" };
35 let timer: ReturnType<typeof setTimeout> | undefined;
36 try {
37 const file = await Promise.race([
38 previewAnnotationScreenshotFile(annotation),
39 new Promise<null>((resolve) => {
40 timer = setTimeout(() => resolve(null), timeoutMs);
41 }),
42 ]);
43 return file ? { status: "captured", file } : { status: "failed" };
44 } catch {
45 return { status: "failed" };
46 } finally {
47 clearTimeout(timer);
48 }